answer
stringlengths
17
10.2M
package com.tpb.projects.data.models; import android.support.annotation.Nullable; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; public class User extends DataModel { private static final String TAG = User.class.getSimpleName(); private User() { } private static final String LOGIN = "login"; private String login; private int id; private static final String AVATAR_URL = "avatar_url"; private String avatarUrl; private static final String URL = "url"; private String url; private static final String REPOS_URL = "repos_url"; private String reposUrl; private static final String NAME = "name"; private String name; private static final String LOCATION = "location"; private String location; private static final String EMAIL = "email"; private String email; private static final String REPOS = "public_repos"; private int repos; private static final String FOLLOWERS = "followers"; private int followers; private static final String BIO = "bio"; private String bio; public int getId() { return id; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getUrl() { return url; } public String getReposUrl() { return reposUrl; } @Nullable public String getName() { return name; } @Nullable public String getLocation() { return location; } public String getEmail() { return email; } public int getRepos() { return repos; } public int getFollowers() { return followers; } public String getBio() { return bio; } public static User parse(JSONObject obj) { final User u = new User(); try { u.id = obj.getInt(ID); u.login = obj.getString(LOGIN); u.avatarUrl = obj.getString(AVATAR_URL); u.url = obj.getString(URL); u.reposUrl = obj.getString(REPOS_URL); if(obj.has(REPOS)) u.repos = obj.getInt(REPOS); if(obj.has(FOLLOWERS)) u.followers = obj.getInt(FOLLOWERS); if(obj.has(BIO)) u.bio = obj.getString(BIO); if(obj.has(EMAIL)) u.email = obj.getString(EMAIL); if(obj.has(LOCATION)) u.location = obj.getString(LOCATION); if(obj.has(NAME)) u.name = obj.getString(NAME); } catch(JSONException jse) { Log.e(TAG, "parse: ", jse); } return u; } public static JSONObject parse(User user) { final JSONObject obj = new JSONObject(); try { obj.put(ID, user.id); obj.put(LOGIN, user.login); obj.put(AVATAR_URL, user.avatarUrl); obj.put(URL, user.url); obj.put(REPOS_URL, user.reposUrl); obj.put(REPOS, user.repos); obj.put(FOLLOWERS, user.followers); if(user.bio != null) obj.put(BIO, user.bio); if(user.email != null) obj.put(EMAIL, user.email); if(user.location != null) obj.put(LOCATION, user.location); if(user.name != null) obj.put(NAME, user.name); } catch(JSONException jse) { Log.e(TAG, "parse: ", jse); } return obj; } @Override public String toString() { return "User{" + "login='" + login + '\'' + ", id=" + id + ", avatarUrl='" + avatarUrl + '\'' + ", url='" + url + '\'' + ", reposUrl='" + reposUrl + '\'' + ", name='" + name + '\'' + ", location='" + location + '\'' + ", email='" + email + '\'' + ", repos=" + repos + ", followers=" + followers + ", bio='" + bio + '\'' + '}'; } }
package de.mygrades.main.core; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.mygrades.database.dao.GradeEntry; import de.mygrades.database.dao.Overview; import de.mygrades.database.dao.Rule; import de.mygrades.database.dao.TransformerMapping; import de.mygrades.util.SemesterMapper; import de.mygrades.util.exceptions.ParseException; /** * Creates GradeEntry Objects from given HTML with given TransformerMappings. */ public class Transformer { // mapping from TransformerMapping Name -> GradeEntry Property private static final String ITERATOR = "iterator"; public static final String EXAM_ID = "exam_id"; public static final String NAME = "name"; private static final String SEMESTER = "semester"; private static final String GRADE = "grade"; private static final String STATE = "state"; private static final String CREDIT_POINTS = "credit_points"; private static final String ANNOTATION = "annotation"; public static final String ATTEMPT = "attempt"; private static final String EXAM_DATE = "exam_date"; private static final String TESTER = "tester"; private static final String OVERVIEW_POSSIBLE = "overview_possible"; // mapping from TransformerMapping Name -> Overview Property private static final String OVERVIEW_SECTION_1 = "overview_section1"; private static final String OVERVIEW_SECTION_2 = "overview_section2"; private static final String OVERVIEW_SECTION_3 = "overview_section3"; private static final String OVERVIEW_SECTION_4 = "overview_section4"; private static final String OVERVIEW_SECTION_5 = "overview_section5"; private static final String OVERVIEW_PARTICIPANTS = "overview_participants"; private static final String OVERVIEW_AVERAGE = "overview_average"; /** * Parser to extract values into Models. */ private Parser parser; /** * HTML from which the data gets extracted. */ private String html; /** * Map of String -> TransformerMapping for easy access. */ private Map<String, TransformerMapping> transformerMapping; /** * Map of String -> TransformerMapping for easy access to overview Mappings. */ private Map<String, List<TransformerMapping>> transformerMappingOverviewSection; /** * Rule getting transformed */ private Rule rule; /** * SemesterTransformer to transform the specific semester pattern. */ private SemesterTransformer semesterTransformer; /** * SemesterMapper is used to create a map for semester->semesterNumber. */ private SemesterMapper semesterMapper; public Transformer(Rule rule, String html, Parser parser) { this.rule = rule; this.parser = parser; this.html = html; this.semesterTransformer = new SemesterTransformer(rule); this.semesterMapper = new SemesterMapper(); // initialize transformerMapping and transformerMappingOverviewSection createTransformerMappingMap(rule.getTransformerMappings()); } /** * Creates Overview object from HTML via * xPath expressions from TransformerMapping. * * @return Overview * @throws ParseException if something goes wrong at parsing */ public Overview transformOverview(Double userGrade) throws ParseException { // get Node as XML document -> so it must not created every time Document xmlDocument = parser.getStringAsDocument(html); // create Pattern for Integer Extraction Pattern pattern = Pattern.compile("[0-9]+"); // extract Overview values Overview overview = new Overview(); overview.setSection1(getIntegerPropertyOverview(xmlDocument, OVERVIEW_SECTION_1, pattern)); overview.setSection2(getIntegerPropertyOverview(xmlDocument, OVERVIEW_SECTION_2, pattern)); overview.setSection3(getIntegerPropertyOverview(xmlDocument, OVERVIEW_SECTION_3, pattern)); overview.setSection4(getIntegerPropertyOverview(xmlDocument, OVERVIEW_SECTION_4, pattern)); overview.setSection5(getIntegerPropertyOverview(xmlDocument, OVERVIEW_SECTION_5, pattern)); overview.setParticipants(getIntegerProperty(xmlDocument, OVERVIEW_PARTICIPANTS)); overview.setAverage(getDoubleProperty(xmlDocument, OVERVIEW_AVERAGE)); overview.setUserSection((int) Math.round(userGrade)); // calculate participants from the sections if it is not given if (overview.getParticipants() == null) { int participants = overview.getSection(1) + overview.getSection(2) + overview.getSection(3) + overview.getSection(4) + overview.getSection(5); overview.setParticipants(participants); } // calculate average from the sections and the participants if it is not given if (overview.getAverage() == null) { if (overview.getParticipants() != null && overview.getParticipants() != 0) { double average = (overview.getSection(1) + overview.getSection(2) * 2 + overview.getSection(3) * 3 + overview.getSection(4) * 4 + overview.getSection(5) * 5) / (double)overview.getParticipants(); overview.setAverage(average); } } return overview; } /** * Creates GradeEntry objects for all matching elements from html via * xPath expression 'iterator' from TransformerMapping. * * @return List of extracted GradeEntries * @throws ParseException if something goes wrong at parsing */ public List<GradeEntry> transform() throws ParseException { return this.transform(null); } /** * Creates GradeEntry objects for all matching elements from html via * xPath expression 'iterator' from TransformerMapping. * The property semester of a grade entry is respectively set to globalSemester * for all created grade entries if it is not null. * * @param globalSemester A global semester for all created grade entries. If it is null, it's ignored. * @return List of extracted GradeEntries * @throws ParseException if something goes wrong at parsing */ public List<GradeEntry> transform(String globalSemester) throws ParseException { List<GradeEntry> gradeEntries = new ArrayList<>(); // get List to iterate through and respectively extract GradeEntry values NodeList nodeList = parser.parseToNodeList(transformerMapping.get(ITERATOR).getParseExpression(), html); for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i); // get Node as XML document -> so it must not created every time Document xmlDocument = parser.getNodeAsDocument(nNode); // create new GradeEntry and add all extracted values GradeEntry gradeEntry = new GradeEntry(); gradeEntry.setExamId(getStringProperty(xmlDocument, EXAM_ID)); gradeEntry.setName(getStringProperty(xmlDocument, NAME)); // extract semester from line if there is no global semester given String semester; if (globalSemester == null) { // ignore entry if there could no semester determined semester = semesterTransformer.calculateGradeEntrySemester(getStringProperty(xmlDocument, SEMESTER)); if (semester == null) { continue; } } else { // use global semester as semester semester = globalSemester; } gradeEntry.setSemester(semester); gradeEntry.setGrade(getDoubleProperty(xmlDocument, GRADE, rule.getGradeFactor())); gradeEntry.setState(getStringProperty(xmlDocument, STATE)); gradeEntry.setCreditPoints(getDoubleProperty(xmlDocument, CREDIT_POINTS)); gradeEntry.setAnnotation(getStringProperty(xmlDocument, ANNOTATION)); gradeEntry.setAttempt(getStringProperty(xmlDocument, ATTEMPT)); gradeEntry.setExamDate(getStringProperty(xmlDocument, EXAM_DATE)); gradeEntry.setTester(getStringProperty(xmlDocument, TESTER)); gradeEntry.setOverviewPossible(getBooleanProperty(xmlDocument, OVERVIEW_POSSIBLE)); // set default weight gradeEntry.setWeight(1.0); // update hash, used as primary key gradeEntry.updateHash(); // add GradeEntry to list gradeEntries.add(gradeEntry); } return gradeEntries; } /** * Gets the value from Document determined by type of TransformerMapping as String. * * @param xmlDocument Document which should get parsed * @param type Type of TransformerMapping regarding to GradeEntry * @return extracted value as String * @throws ParseException if something goes wrong at parsing */ private String getStringProperty(Document xmlDocument, String type) throws ParseException { TransformerMapping transformerMappingVal = transformerMapping.get(type); if (transformerMappingVal == null) { return null; } String parseResult = parser.parseToString(transformerMappingVal.getParseExpression(), xmlDocument); parseResult = trimAdvanced(parseResult); return parseResult.equals("") ? null : parseResult; } /** * Gets the value from Document determined by type of TransformerMapping as String. * * @param xmlDocument Document which should get parsed * @param type Type of TransformerMapping regarding to GradeEntry * @return extracted value as String * @throws ParseException if something goes wrong at parsing */ private boolean getBooleanProperty(Document xmlDocument, String type) throws ParseException { TransformerMapping transformerMappingVal = transformerMapping.get(type); if (transformerMappingVal == null) { return false; } Boolean parseResult = parser.parseToBoolean(transformerMappingVal.getParseExpression(), xmlDocument); return parseResult == null ? false : parseResult; } /** * Gets the value from Document determined by type of TransformerMapping as Double. * * @param xmlDocument Document which should get parsed * @param type Type of TransformerMapping regarding to GradeEntry * @param factor A factor can be used to multiply the double value * @return extracted value as Double * @throws ParseException if something goes wrong at parsing */ private Double getDoubleProperty(Document xmlDocument, String type, Double factor) throws ParseException { TransformerMapping transformerMappingVal = transformerMapping.get(type); if (transformerMappingVal == null) { return null; } Double property; String result = parser.parseToString(transformerMappingVal.getParseExpression(), xmlDocument); result = trimAdvanced(result); result = result.replace(',', '.'); // if cannot parse to Double -> return null try { property = Double.parseDouble(result); } catch (NumberFormatException e) { return null; } // if factor is given -> multiply if (factor != null) { property = property * factor; } return property; } /** * Gets the value from Document determined by type of TransformerMapping as Double. * * @param xmlDocument Document which should get parsed * @param type Type of TransformerMapping regarding to GradeEntry * @return extracted value as Double * @throws ParseException if something goes wrong at parsing */ private Double getDoubleProperty(Document xmlDocument, String type) throws ParseException { return getDoubleProperty(xmlDocument, type, null); } /** * Gets the value for overview_section* from Document determined by type of TransformerMapping as Integer. * The integers are extracted from string via Regex. * * @param xmlDocument Document which should get parsed * @param type Type of TransformerMapping regarding to Overview * @param pattern Regex pattern of how to extract Integer * @return extracted value as Integer * @throws ParseException if something goes wrong at parsing */ private Integer getIntegerPropertyOverview(Document xmlDocument, String type, Pattern pattern) throws ParseException { List<TransformerMapping> transformerMappingList = transformerMappingOverviewSection.get(type); Integer propertySum = 0; Integer property; // iterate all transformerMappings for specific section and add up results for (TransformerMapping tsMapping : transformerMappingList) { property = extractIntegerFromDoc(xmlDocument, tsMapping, pattern); if (property != null) { propertySum += property; } } return propertySum; } /** * Gets the value from Document determined by type of TransformerMapping as Integer. * * @param xmlDocument Document which should get parsed * @param type Type of TransformerMapping regarding to Overview * @return extracted value as Integer * @throws ParseException if something goes wrong at parsing */ private Integer getIntegerProperty(Document xmlDocument, String type) throws ParseException { return getIntegerProperty(xmlDocument, type, null); } /** * Gets the value from Document determined by type of TransformerMapping as Integer. * The integer is extracted from string via Regex. * * @param xmlDocument Document which should get parsed * @param type Type of TransformerMapping regarding to Overview * @param pattern Regex pattern of how to extract Integer * @return extracted value as Integer * @throws ParseException if something goes wrong at parsing */ private Integer getIntegerProperty(Document xmlDocument, String type, Pattern pattern) throws ParseException { TransformerMapping transformerMappingVal = transformerMapping.get(type); return extractIntegerFromDoc(xmlDocument, transformerMappingVal, pattern); } /** * Gets the value from Document determined by TransformerMapping as Integer. * The integer is extracted from string via Regex. * * @param xmlDocument Document which should get parsed * @param transformerMappingVal TransformerMapping -> which value should get extracted * @param pattern Regex pattern of how to extract Integer * @return extracted value as Integer * @throws ParseException if something goes wrong at parsing */ private Integer extractIntegerFromDoc(Document xmlDocument, TransformerMapping transformerMappingVal, Pattern pattern) throws ParseException { if (transformerMappingVal == null) { return null; } Integer property; String result = parser.parseToString(transformerMappingVal.getParseExpression(), xmlDocument); result = trimAdvanced(result); if (pattern != null) { Matcher matcher = pattern.matcher(result); if (matcher.find()) { result = matcher.group(0); } } // if cannot parse to Integer -> return null try { property = Integer.parseInt(result); } catch (NumberFormatException e) { return null; } return property; } /** * Creates HashMaps for TransformerMappings for easy access. * * @param transformerMappings which are put into Maps transformerMapping or transformerMappingOverviewSection */ private void createTransformerMappingMap(List<TransformerMapping> transformerMappings) { transformerMapping = new HashMap<>(); transformerMappingOverviewSection = new HashMap<>(); // iterate all transformerMappings and add to respective list for (TransformerMapping tsMapping : transformerMappings) { String tsName = tsMapping.getName(); if (tsName == null) { continue; } if (tsName.startsWith("overview_section")) { List<TransformerMapping> list = transformerMappingOverviewSection.get(tsName); if (list == null) { list = new ArrayList<>(); list.add(tsMapping); transformerMappingOverviewSection.put(tsName, list); } else { list.add(tsMapping); } } else { transformerMapping.put(tsMapping.getName(), tsMapping); } } } private String trimAdvanced(String value) { if (value == null) { return ""; } int strLength = value.length(); int len = value.length(); int st = 0; char[] val = value.toCharArray(); if (strLength == 0) { return ""; } while ((st < len) && (val[st] <= ' ') || (val[st] == '\u00A0')) { st++; if (st == strLength) { break; } } while ((st < len) && (val[len - 1] <= ' ') || (val[len - 1] == '\u00A0')) { len if (len == 0) { break; } } return (st > len) ? "" : ((st > 0) || (len < strLength)) ? value.substring(st, len) : value; } }
package javax.microedition.m3g; import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import java.util.Hashtable; import java.util.Vector; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL10; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Graphics; import java.nio.IntBuffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; public final class Graphics3D { public static final int ANTIALIAS = 2; public static final int DITHER = 4; public static final int OVERWRITE = 16; public static final int TRUE_COLOR = 8; private static final String PROPERTY_SUPPORT_ANTIALIASING = "supportAntialiasing"; private static final String PROPERTY_SUPPORT_TRUECOLOR = "supportTrueColor"; private static final String PROPERTY_SUPPORT_DITHERING = "supportDithering"; private static final String PROPERTY_SUPPORT_MIPMAPPING = "supportMipmapping"; private static final String PROPERTY_SUPPORT_PERSPECTIVE_CORRECTION = "supportPerspectiveCorrection"; private static final String PROPERTY_MAX_LIGHTS = "maxLights"; private static final String PROPERTY_MAX_VIEWPORT_WIDTH = "maxViewportWidth"; private static final String PROPERTY_MAX_VIEWPORT_HEIGHT = "maxViewportHeight"; private static final String PROPERTY_MAX_VIEWPORT_DIMENSION = "maxViewportDimension"; private static final String PROPERTY_MAX_TEXTURE_DIMENSION = "maxTextureDimension"; private static final String PROPERTY_MAX_SPRITE_CROP_DIMENSION = "maxSpriteCropDimension"; private static final String PROPERTY_MAX_TRANSFORM_PER_VERTEX = "maxTransformsPerVertex"; private static final String PROPERTY_MAX_TEXTURE_UNITS = "numTextureUnits"; private static Graphics3D instance = null; private int maxTextureUnits = 1; private int maxTextureSize; private int viewportX = 0; private int viewportY = 0; private int viewportWidth = 0; private int viewportHeight = 0; private int maxViewportWidth = 0; private int maxViewportHeight = 0; private EGL10 egl; private EGLConfig eglConfig; private EGLDisplay eglDisplay; private EGLSurface eglWindowSurface; private EGLContext eglContext; private GL10 gl = null; private Object renderTarget; private boolean targetBound = false; private Camera camera; private Transform cameraTransform; private Vector lights = new Vector(); private Vector lightTransforms = new Vector(); private static boolean[] lightFlags; private int maxLights = 1; private boolean lightHasChanged = false; private CompositingMode defaultCompositioningMode = new CompositingMode(); private PolygonMode defaultPolygonMode = new PolygonMode(); private Background defaultBackground = new Background(); private boolean cameraHasChanged = false; private float depthRangeNear = 0; private float depthRangeFar = 1; private boolean depthRangeHasChanged = false; private boolean depthBufferEnabled; private int hints; private static Hashtable implementationProperties = new Hashtable(); private int width, height; private int clipX0, clipY0, clipX1, clipY1; private int scissorX, scissorY, scissorWidth, scissorHeight; private Graphics3D() { initGLES(); populateProperties(); } public static Graphics3D getInstance() { if (instance == null) { instance = new Graphics3D(); } return instance; } private void initGLES() { // Create EGL context this.egl = (EGL10) EGLContext.getEGL(); this.eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); EGL_ASSERT(eglDisplay != EGL10.EGL_NO_DISPLAY); int[] major_minor = new int[2]; EGL_ASSERT(egl.eglInitialize(eglDisplay, major_minor)); int[] num_config = new int[1]; //EGL_ASSERT(egl.eglGetConfigs(eglDisplay, null, 0, num_config)); int[] s_configAttribs = { //EGL10.EGL_SURFACE_TYPE, EGL10.EGL_PBUFFER_BIT, EGL10.EGL_RED_SIZE, 8, EGL10.EGL_GREEN_SIZE, 8, EGL10.EGL_BLUE_SIZE, 8, EGL10.EGL_ALPHA_SIZE, 8, EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_STENCIL_SIZE, EGL10.EGL_DONT_CARE, EGL10.EGL_NONE }; EGLConfig[] eglConfigs = new EGLConfig[1]; EGL_ASSERT(egl.eglChooseConfig(eglDisplay, s_configAttribs, eglConfigs, 1, num_config)); this.eglConfig = eglConfigs[0]; this.eglContext = egl.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, null); EGL_ASSERT(eglContext != EGL10.EGL_NO_CONTEXT); // Create an offscreen surface width = Canvas.width; height = Canvas.height; int[] s_surfaceAttribs = { EGL10.EGL_WIDTH, width, EGL10.EGL_HEIGHT, height, EGL10.EGL_NONE }; this.eglWindowSurface = egl.eglCreatePbufferSurface(eglDisplay, eglConfig, s_surfaceAttribs); EGL_ASSERT(egl.eglMakeCurrent(eglDisplay, eglWindowSurface, eglWindowSurface, eglContext)); this.gl = (GL10) eglContext.getGL(); // Get parameters from the GL instance int[] params = new int[2]; gl.glGetIntegerv(GL10.GL_MAX_TEXTURE_UNITS, params, 0); maxTextureUnits = params[0]; gl.glGetIntegerv(GL10.GL_MAX_LIGHTS, params, 0); maxLights = params[0]; lightFlags = new boolean[maxLights]; gl.glGetIntegerv(GL10.GL_MAX_VIEWPORT_DIMS, params, 0); maxViewportWidth = params[0]; maxViewportHeight = params[1]; gl.glGetIntegerv(GL10.GL_MAX_TEXTURE_SIZE, params, 0); maxTextureSize = params[0]; // Set default clipping rectangle clipX0 = 0; clipY0 = 0; clipX1 = width; clipY1 = height; gl.glEnable(GL10.GL_SCISSOR_TEST); gl.glPixelStorei(GL10.GL_UNPACK_ALIGNMENT, 1); gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); } private void populateProperties() { implementationProperties.put(PROPERTY_SUPPORT_ANTIALIASING, new Boolean(false)); implementationProperties.put(PROPERTY_SUPPORT_TRUECOLOR, new Boolean(true)); implementationProperties.put(PROPERTY_SUPPORT_DITHERING, new Boolean(false)); implementationProperties.put(PROPERTY_SUPPORT_MIPMAPPING, new Boolean(false)); implementationProperties.put(PROPERTY_SUPPORT_PERSPECTIVE_CORRECTION, new Boolean(false)); implementationProperties.put(PROPERTY_MAX_LIGHTS, new Integer(maxLights)); implementationProperties.put(PROPERTY_MAX_VIEWPORT_WIDTH, new Integer(maxViewportWidth)); implementationProperties.put(PROPERTY_MAX_VIEWPORT_HEIGHT, new Integer(maxViewportHeight)); implementationProperties.put(PROPERTY_MAX_VIEWPORT_DIMENSION, new Integer(Math.min(maxViewportWidth, maxViewportHeight))); implementationProperties.put(PROPERTY_MAX_TEXTURE_DIMENSION, new Integer(maxTextureSize)); implementationProperties.put(PROPERTY_MAX_SPRITE_CROP_DIMENSION, new Integer(maxTextureSize)); implementationProperties.put(PROPERTY_MAX_TRANSFORM_PER_VERTEX, new Integer(4)); implementationProperties.put(PROPERTY_MAX_TEXTURE_UNITS, new Integer(maxTextureUnits)); } public void bindTarget(Object target) { bindTarget(target, true, 0); } public void bindTarget(Object target, boolean depthBuffer, int hints) { if (target == null) { throw new NullPointerException("Rendering target must not be null"); } // Depth buffer depthBufferEnabled = depthBuffer; if (depthBuffer) gl.glEnable(GL10.GL_DEPTH_TEST); else gl.glDisable(GL10.GL_DEPTH_TEST); this.hints = hints; // A target should not be already bound if (targetBound) { return; } // Now bind the target targetBound = true; // Create a new window surface if the target changes (i.e, for MIDP2, the target Canvas changed) if (target != renderTarget) { renderTarget = target; /*Displayable disp = ContextHolder.getCurrentActivity().getCurrent(); if (disp != null && disp instanceof javax.microedition.lcdui.Canvas) { SurfaceView sv = (SurfaceView) disp.getDisplayableView(); SurfaceHolder holder = sv.getHolder(); while (holder == null) { try { Thread.sleep(50); } catch (Exception e) { } holder = sv.getHolder(); } this.eglWindowSurface = egl.eglCreateWindowSurface(eglDisplay, eglConfig, target, null); //this.eglWindowSurface = egl.eglCreatePixmapSurface(eglDisplay, eglConfig, Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888), null); EGL_ASSERT(eglWindowSurface != EGL10.EGL_NO_SURFACE); }*/ } this.gl = (GL10) eglContext.getGL(); setViewport(0, 0, width, height); } private static void EGL_ASSERT(boolean val) { if (!val) { System.out.println("EGL_ASSERT failed!"); throw new IllegalStateException(); } } public Object getTarget() { return this.renderTarget; } public void releaseTarget() { if (targetBound) { int b[]=new int[width*height]; int bt[]=new int[width*height]; IntBuffer ib=IntBuffer.wrap(b); ib.position(0); gl.glFinish(); gl.glReadPixels(0, 0, width, height, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, ib); for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { int pix=b[i*width+j]; int pb=(pix>>>16)&0xff; int pr=(pix<<16)&0x00ff0000; int pix1=(pix&0xff00ff00) | pr | pb | (((pix & 0xff000000) == 0) ? 0 : 0xff000000); bt[(height-i-1)*width+j]=pix1; } } ((Graphics)renderTarget).drawRGB(bt, 0, width, 0, 0, width, height, true); targetBound = false; gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); } } public void clear(Background background) { if (background != null) background.setupGL(gl); else { defaultBackground.setupGL(gl); } } public int addLight(Light light, Transform transform) { if (light == null) throw new NullPointerException("Light must not be null"); lights.addElement(light); // Use identity transform if the given transform is null Transform t = new Transform(); if (transform != null) { t.set(transform); } lightTransforms.addElement(t); int index = lights.size() - 1; // limit the number of lights if (index < maxLights) { lightFlags[index] = true; } lightHasChanged = true; return index; } public void setLight(int index, Light light, Transform transform) { lights.setElementAt(light, index); lightTransforms.setElementAt(transform, index); if (index < maxLights) { lightFlags[index] = true; } lightHasChanged = true; } public void resetLights() { lights.removeAllElements(); lightTransforms.removeAllElements(); for (int i = 0; i < maxLights; i++) { lightFlags[i] = false; } lightHasChanged = true; } public int getLightCount() { return lights.size(); } public Light getLight(int index, Transform transform) { if (transform != null) { transform.set((Transform) lightTransforms.elementAt(index)); } return (Light) lights.elementAt(index); } public int getHints() { return hints; } public boolean isDepthBufferEnabled() { return depthBufferEnabled; } public void setViewport(int x, int y, int width, int height) { if ((width <= 0) || (height <= 0) || (width > maxViewportWidth) || (height > maxViewportHeight)) { throw new IllegalArgumentException("Viewport coordinates are out of the allowed range"); } this.viewportX = x; this.viewportY = y; this.viewportWidth = width; this.viewportHeight = height; int sx0 = Math.max(viewportX, clipX0); int sy0 = Math.max(viewportY, clipY0); int sx1 = Math.min(viewportX + viewportWidth, clipX1); int sy1 = Math.min(viewportY + viewportHeight, clipY1); scissorX = sx0; scissorY = sy0; if (sx0 < sx1 && sy0 < sy1) { scissorWidth = sx1 - sx0; scissorHeight = sy1 - sy0; } else scissorWidth = scissorHeight = 0; gl.glViewport(x, y, width, height); } public int getViewportX() { return this.viewportX; } public int getViewportY() { return this.viewportY; } public int getViewportWidth() { return this.viewportWidth; } public int getViewportHeight() { return this.viewportHeight; } public void setDepthRange(float near, float far) { if ((near < 0) || (near > 1) || (far < 0) || (far > 1)) { throw new IllegalArgumentException("Bad depth range"); } if ((depthRangeNear != near) || (depthRangeFar != far)) { depthRangeNear = near; depthRangeFar = far; depthRangeHasChanged = true; } } public float getDepthRangeNear() { return depthRangeNear; } public float getDepthRangeFar() { return depthRangeFar; } public static final Hashtable getProperties() { // Force initialization of Graphics3D in order to populate implementationProperties if (instance == null) { getInstance(); } return implementationProperties; } public void setCamera(Camera camera, Transform transform) { this.camera = camera; Transform t = new Transform(); if (transform != null) { t.set(transform); } t.mtx.invertMatrix(); this.cameraTransform = t; cameraHasChanged = true; } public Camera getCamera(Transform transform) { if (transform != null) transform.set(this.cameraTransform); return camera; } public void render(Node node, Transform transform) { if (camera == null) throw new IllegalStateException("Graphics3D does not have a current camera"); // If the given transform is null, use the identity matrix if (transform == null) { transform = new Transform(); } // Apply Graphics3D settings to the OpenGL pipeline initRender(); if ((node instanceof Mesh) || (node instanceof Sprite3D) || (node instanceof Group)) { renderNode(node, transform); } else { throw new IllegalArgumentException("Node is not a Sprite3D, Mesh, or Group"); } } private void initRender() { if (cameraHasChanged) { Transform t = new Transform(); gl.glMatrixMode(GL10.GL_PROJECTION); camera.getProjection(t); t.setGL(gl); gl.glMatrixMode(GL10.GL_MODELVIEW); t.set(cameraTransform); //t.mtx.invertMatrix(); t.setGL(gl); gl.glViewport(viewportX, viewportY, viewportWidth, viewportHeight); gl.glScissor(scissorX, scissorY, scissorWidth, scissorHeight); cameraHasChanged = false; } if (lightHasChanged) { for (int i = 0; i < maxLights; i++) { if (lightFlags[i]) { Light light = (Light) lights.elementAt(i); Transform transform = (Transform) lightTransforms.elementAt(i); gl.glEnable(GL10.GL_LIGHT0 + i); gl.glPushMatrix(); transform.multGL(gl); light.setupGL(gl, GL10.GL_LIGHT0 + i); gl.glPopMatrix(); } else { gl.glDisable(GL10.GL_LIGHT0 + i); } } lightHasChanged = false; } if (depthRangeHasChanged) { gl.glDepthRangef(depthRangeNear, depthRangeFar); depthRangeHasChanged = false; } } public void render(VertexBuffer vertices, IndexBuffer triangles, Appearance appearance, Transform transform) { if (vertices == null) throw new NullPointerException("vertices == null"); if (triangles == null) throw new NullPointerException("triangles == null"); if (appearance == null) throw new NullPointerException("appearance == null"); if (camera == null) throw new IllegalStateException("Graphics3D does not have a current camera"); // TODO Check if vertices or triangles violates the constraints defined in VertexBuffer or IndexBuffer // If the given transform is null, use the identity matrix if (transform == null) { transform = new Transform(); } // Apply Graphics3D settings to the OpenGL pipeline initRender(); // Vertices float[] scaleBias = new float[4]; VertexArray positions = vertices.getPositions(scaleBias); if (positions.getComponentType() == 1) { ByteBuffer pos = (ByteBuffer) positions.getBuffer(); pos.position(0); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(positions.getComponentCount(), GL10.GL_BYTE, 4, pos); } else { ShortBuffer pos = (ShortBuffer) positions.getBuffer(); pos.position(0); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(positions.getComponentCount(), GL10.GL_SHORT, positions.stride, pos); } // Normals VertexArray normals = vertices.getNormals(); if (normals != null) { gl.glEnable(GL10.GL_NORMALIZE); if (normals.getComponentType() == 1) { ByteBuffer norm = (ByteBuffer) normals.getBuffer(); norm.position(0); gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glNormalPointer(GL10.GL_BYTE, 4, norm); } else { ShortBuffer norm = (ShortBuffer) normals.getBuffer(); norm.position(0); gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glNormalPointer(GL10.GL_SHORT, normals.stride, norm); } } else { gl.glDisable(GL10.GL_NORMALIZE); gl.glDisableClientState(GL10.GL_NORMAL_ARRAY); } // Colors VertexArray colors = vertices.getColors(); if (colors != null) { Buffer buffer = colors.getARGBBuffer(); buffer.position(0); // Force number of color components to 4 (i.e. don't use colors.getComponentCount()) gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 4, buffer); } else { // Use default color as we don't have color per vertex Color color = new Color(vertices.getDefaultColor()); float[] colorArray = color.toRGBAArray(); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); gl.glColor4f(colorArray[0], colorArray[1], colorArray[2], colorArray[3]); } // Textures for (int i = 0; i < maxTextureUnits; ++i) { float[] texScaleBias = new float[4]; VertexArray texcoords = vertices.getTexCoords(i, texScaleBias); gl.glClientActiveTexture(GL10.GL_TEXTURE0 + i); if ((texcoords != null) && (appearance.getTexture(i) != null)) { // Enable the texture coordinate array gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Activate the texture unit gl.glActiveTexture(GL10.GL_TEXTURE0 + i); appearance.getTexture(i).setupGL(gl, texScaleBias); // Set the texture coordinates if (texcoords.getComponentType() == 1) { ByteBuffer buffer = (ByteBuffer) texcoords.getBuffer(); buffer.position(0); gl.glTexCoordPointer(texcoords.getComponentCount(), GL10.GL_BYTE, 4, buffer); } else { ShortBuffer buffer = (ShortBuffer) texcoords.getBuffer(); buffer.position(0); gl.glTexCoordPointer(texcoords.getComponentCount(), GL10.GL_SHORT, texcoords.stride, buffer); } } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); } } // Appearance setAppearance(appearance); // Scene gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPushMatrix(); transform.multGL(gl); gl.glTranslatef(scaleBias[1], scaleBias[2], scaleBias[3]); gl.glScalef(scaleBias[0], scaleBias[0], scaleBias[0]); // Draw ShortBuffer indices = triangles.getBuffer(); indices.position(0); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, triangles.getIndexCount(), GL10.GL_UNSIGNED_SHORT, indices); gl.glPopMatrix(); } public void render(VertexBuffer vertices, IndexBuffer triangles, Appearance appearance, Transform transform, int scope) { // TODO: check scope render(vertices, triangles, appearance, transform); } public void render(World world) { clear(world.getBackground()); Transform t = new Transform(); // Setup camera Camera c = world.getActiveCamera(); if (c == null) throw new IllegalStateException("World has no active camera."); if (!c.getTransformTo(world, t)) throw new IllegalStateException("Camera is not in world."); // Camera setCamera(c, t); initRender(); resetLights(); populateLights(world, world); initRender(); // Begin traversal of scene graph renderDescendants(world, world); } private void populateLights(World world, Object3D obj) { int numReferences = obj.getReferences(null); if (numReferences > 0) { Object3D[] objArray = new Object3D[numReferences]; obj.getReferences(objArray); for (int i = 0; i < numReferences; ++i) { if (objArray[i] instanceof Light) { Transform t = new Transform(); Light light = (Light) objArray[i]; if (light.isRenderingEnabled() && light.getTransformTo(world, t)) addLight(light, t); } populateLights(world, objArray[i]); } } } private void renderDescendants(Node topNode, Object3D obj) { int numReferences = obj.getReferences(null); if (numReferences > 0) { Object3D[] objArray = new Object3D[numReferences]; obj.getReferences(objArray); for (int i = 0; i < numReferences; ++i) { if (objArray[i] instanceof Node) { Node subNode = (Node) objArray[i]; if (subNode instanceof Group) { renderDescendants(topNode, subNode); } else { Transform t = new Transform(); subNode.getTransformTo(topNode, t); renderNode(subNode, t); } } } } } private void drawMesh(VertexBuffer vb, IndexBuffer ib, Appearance app, Transform modelTransform) { initRender(); if (modelTransform != null) { float transform[] = new float[16]; modelTransform.mtx.getMatrixColumns(transform); gl.glPushMatrix(); FloatBuffer tr = ByteBuffer.allocateDirect(transform.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); tr.put(transform).position(0); gl.glMultMatrixf(tr); } setAppearance(app); VertexArray colors = vb.getColors(); if (colors != null) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); Buffer buffer = colors.getARGBBuffer(); buffer.position(0); // Force number of color components to 4 (i.e. don't use colors.getComponentCount()) gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 4, buffer); } else { gl.glDisableClientState(GL10.GL_COLOR_ARRAY); // Use default color as we don't have color per vertex Color color = new Color(vb.getDefaultColor()); float[] colorArray = color.toRGBAArray(); gl.glColor4f(colorArray[0], colorArray[1], colorArray[2], colorArray[3]); } VertexArray normals = vb.getNormals(); if (normals != null) { /* gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); FloatBuffer norm = normals.getFloatBuffer(); norm.position(0); gl.glEnable(GL10.GL_NORMALIZE); gl.glNormalPointer(GL10.GL_FLOAT, 0, norm);*/ //FloatBuffer norm = normals.getFloatBuffer(); gl.glEnable(GL10.GL_NORMALIZE); if (normals.getComponentType() == 1) { ByteBuffer norm = (ByteBuffer) normals.getBuffer(); norm.position(0); gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glNormalPointer(GL10.GL_BYTE, 4, norm); } else { ShortBuffer norm = (ShortBuffer) normals.getBuffer(); norm.position(0); gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glNormalPointer(GL10.GL_SHORT, normals.stride, norm); } /*norm.position(0); gl.glEnable(GL10.GL_NORMALIZE); gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glNormalPointer(GL10.GL_FLOAT, 0, norm);*/ } else { //gl.glDisable(GL10.GL_NORMALIZE); gl.glDisableClientState(GL10.GL_NORMAL_ARRAY); } // Vertices float[] scaleBias = new float[4]; VertexArray vertices = vb.getPositions(scaleBias); if (vertices != null) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); //FloatBuffer pos = vertices.getFloatBuffer(); if (vertices.getComponentType() == 1) { ByteBuffer buffer = (ByteBuffer) vertices.getBuffer(); buffer.position(0); gl.glVertexPointer(vertices.getComponentCount(), GL10.GL_BYTE, 4, buffer); } else { ShortBuffer buffer = (ShortBuffer) vertices.getBuffer(); buffer.position(0); gl.glVertexPointer(vertices.getComponentCount(), GL10.GL_SHORT, vertices.stride, buffer); } //pos.position(0); //gl.glVertexPointer(vertices.getComponentCount(), GL10.GL_FLOAT, 0, pos); } else { gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } // Textures for (int i = 0; i < maxTextureUnits; i++) { float[] texScaleBias = new float[4]; VertexArray texcoords = vb.getTexCoords(i, texScaleBias); gl.glClientActiveTexture(GL10.GL_TEXTURE0 + i); gl.glActiveTexture(GL10.GL_TEXTURE0 + i); if ((texcoords != null) && (app.getTexture(i) != null)) { // Enable the texture coordinate array gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); //FloatBuffer tex = texcoords.getFloatBuffer(); //tex.position(0); // Activate the texture unit //appearance.getTexture(i).setupGL(gl, texScaleBias); // Set the texture coordinates if (texcoords.getComponentType() == 1) { ByteBuffer buffer = (ByteBuffer) texcoords.getBuffer(); buffer.position(0); gl.glTexCoordPointer(texcoords.getComponentCount(), GL10.GL_BYTE, 4, buffer); } else { ShortBuffer buffer = (ShortBuffer) texcoords.getBuffer(); buffer.position(0); gl.glTexCoordPointer(texcoords.getComponentCount(), GL10.GL_SHORT, texcoords.stride, buffer); } } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); } } gl.glMatrixMode(GL10.GL_TEXTURE); for (int i = 0; i < maxTextureUnits; i++) { float[] texScaleBias = new float[4]; VertexArray texcoords = vb.getTexCoords(i, texScaleBias); if (texcoords != null && app.getTexture(i) != null) { //appearance.getTexture(i).setupGL(gl, texScaleBias); gl.glActiveTexture(GL10.GL_TEXTURE0 + i); gl.glTranslatef(texScaleBias[1], texScaleBias[2], texScaleBias[3]); gl.glScalef(texScaleBias[0], texScaleBias[0], texScaleBias[0]); } } gl.glMatrixMode(GL10.GL_MODELVIEW); if (vertices != null) { gl.glTranslatef(scaleBias[1], scaleBias[2], scaleBias[3]); gl.glScalef(scaleBias[0], scaleBias[0], scaleBias[0]); } // Draw ShortBuffer indices = ib.getBuffer(); indices.position(0); //if (triangles instanceof TriangleStripArray) { gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, ib.getIndexCount(), GL10.GL_UNSIGNED_SHORT, indices); /*} else { gl.glDrawElements(GL10.GL_TRIANGLES, ib.getIndexCount(), GL10.GL_UNSIGNED_SHORT, indices); }*/ if (modelTransform != null) gl.glPopMatrix(); } private void renderNode(Node node, Transform transform) { if (node instanceof Mesh) { Mesh mesh = (Mesh) node; int subMeshes = mesh.getSubmeshCount(); VertexBuffer vertices = mesh.getVertexBuffer(); for (int i = 0; i < subMeshes; ++i) if (mesh.getAppearance(i) != null) /*drawMesh*/render(vertices, mesh.getIndexBuffer(i), mesh.getAppearance(i), transform); } else if (node instanceof Sprite3D) { Sprite3D sprite = (Sprite3D) node; sprite.render(gl, transform); } else if (node instanceof Group) { renderDescendants(node, node); } } void setAppearance(Appearance appearance) { if (appearance == null) throw new NullPointerException("Appearance must not be null"); // Polygon mode PolygonMode polyMode = appearance.getPolygonMode(); if (polyMode == null) { polyMode = defaultPolygonMode; } polyMode.setupGL(gl); // Material if (appearance.getMaterial() != null) { appearance.getMaterial().setupGL(gl, polyMode.getLightTarget()); } else { gl.glDisable(GL10.GL_LIGHTING); } // Fog if (appearance.getFog() != null) { appearance.getFog().setupGL(gl); } else { gl.glDisable(GL10.GL_FOG); } // Compositing mode if (appearance.getCompositingMode() != null) { appearance.getCompositingMode().setupGL(gl, depthBufferEnabled); } else { defaultCompositioningMode.setupGL(gl, depthBufferEnabled); } } int getTextureUnitCount() { return maxTextureUnits; } int getMaxTextureSize() { return maxTextureSize; } void disableTextureUnits() { for (int i = 0; i < maxTextureUnits; i++) { gl.glActiveTexture(GL10.GL_TEXTURE0 + i); gl.glDisable(GL10.GL_TEXTURE_2D); } } }
package jp.blanktar.ruumusic; import java.io.File; import java.util.Arrays; import java.util.ArrayList; import java.util.Map; import java.util.LinkedHashMap; import java.util.Collections; import android.support.annotation.NonNull; import android.content.Context; public class RuuDirectory extends RuuFileBase{ private final static LinkedHashMap<String, RuuDirectory> cache = new LinkedHashMap<String, RuuDirectory>(){ @Override protected boolean removeEldestEntry(Map.Entry<String, RuuDirectory> eldest){ return size() > 128; } }; private final static LinkedHashMap<String, ArrayList<RuuFile>> recursiveMusicsCache = new LinkedHashMap<String, ArrayList<RuuFile>>(){ @Override protected boolean removeEldestEntry(Map.Entry<String, ArrayList<RuuFile>> eldest){ return size() > 3; } }; private final static LinkedHashMap<String, ArrayList<File>> recursiveAllCache = new LinkedHashMap<String, ArrayList<File>>(){ @Override protected boolean removeEldestEntry(Map.Entry<String, ArrayList<File>> eldest){ return size() > 3; } }; private ArrayList<File> musicsCache = null; private ArrayList<File> directoriesCache = null; private File[] files = null; private RuuDirectory(@NonNull Context context, @NonNull String path) throws RuuFileBase.CanNotOpen{ super(context, path); files = this.path.listFiles(); if(files == null){ throw new CanNotOpen(path); } Arrays.sort(files); } public static RuuDirectory getInstance(@NonNull Context context, @NonNull String path) throws RuuFileBase.CanNotOpen{ RuuDirectory result = cache.get(path); if(result == null){ result = new RuuDirectory(context, path); } cache.put(path, result); return result; } @NonNull public static RuuDirectory rootDirectory(@NonNull Context context) throws RuuFileBase.CanNotOpen{ return RuuDirectory.getInstance(context, getRootDirectory(context)); } @Override public boolean isDirectory(){ return true; } @Override @NonNull public String getFullPath(){ String result = path.getPath(); if(!result.endsWith("/")){ result += "/"; } return result; } public boolean contains(@NonNull RuuFileBase file){ return file.getFullPath().startsWith(getFullPath()); } @NonNull public ArrayList<RuuDirectory> getDirectories() throws RuuFileBase.CanNotOpen{ ArrayList<RuuDirectory> result = new ArrayList<>(); if(directoriesCache != null){ for(File file: directoriesCache){ result.add(RuuDirectory.getInstance(context, file.getPath())); } }else{ directoriesCache = new ArrayList<>(); for(File file: files){ if(file.getName().lastIndexOf(".") != 0){ try{ RuuDirectory dir = RuuDirectory.getInstance(context, file.getPath()); result.add(dir); directoriesCache.add(dir.path); }catch(RuuFileBase.CanNotOpen e){ } } } if(musicsCache != null){ files = null; } } return result; } @NonNull public ArrayList<RuuFile> getMusics() throws RuuFileBase.CanNotOpen{ ArrayList<RuuFile> result = new ArrayList<>(); if(musicsCache != null){ for(File file: musicsCache){ result.add(new RuuFile(context, file.getPath())); } }else{ musicsCache = new ArrayList<>(); String before = ""; for(File file: files){ if(file.getName().lastIndexOf(".") <= 0){ continue; } String path = file.getPath(); int dotPos = path.lastIndexOf("."); String name = path.substring(0, dotPos); String ext = path.substring(dotPos); if(!file.isDirectory() && !name.equals(before) && getSupportedTypes().contains(ext)){ try{ RuuFile music = new RuuFile(context, name); result.add(music); musicsCache.add(music.path); }catch(RuuFileBase.CanNotOpen e){ continue; } before = name; } } if(directoriesCache != null){ files = null; } } return result; } @NonNull public ArrayList<RuuFile> getMusicsRecursiveWithoutCache() throws RuuFileBase.CanNotOpen{ ArrayList<RuuFile> list = new ArrayList<>(); for(RuuDirectory dir: getDirectories()){ try{ list.addAll(dir.getMusicsRecursiveWithoutCache()); }catch(RuuFileBase.CanNotOpen e){ } } list.addAll(getMusics()); return list; } @NonNull public ArrayList<RuuFile> getMusicsRecursive() throws RuuFileBase.CanNotOpen{ ArrayList<RuuFile> list = recursiveMusicsCache.get(getFullPath()); if(list == null){ list = getMusicsRecursiveWithoutCache(); } recursiveMusicsCache.put(getFullPath(), list); return list; } @NonNull public ArrayList<RuuFileBase> getAllRecursiveWithoutCache() throws RuuFileBase.CanNotOpen{ ArrayList<RuuFileBase> list = new ArrayList<>(); ArrayList<RuuDirectory> dirs = getDirectories(); for(RuuDirectory dir: dirs){ try{ list.addAll(dir.getAllRecursiveWithoutCache()); }catch(RuuFileBase.CanNotOpen e){ } } list.addAll(dirs); list.addAll(getMusics()); Collections.sort(list); return list; } @NonNull public ArrayList<RuuFileBase> getAllRecursive() throws RuuFileBase.CanNotOpen{ ArrayList<File> list = recursiveAllCache.get(getFullPath()); ArrayList<RuuFileBase> result; if(list == null){ result = getAllRecursiveWithoutCache(); list = new ArrayList<>(); for(RuuFileBase file: result){ list.add(file.path); } }else{ result = new ArrayList<>(); for(File file: list){ try{ if(file.isDirectory()){ result.add(RuuDirectory.getInstance(context, file.getPath())); }else{ result.add(new RuuFile(context, file.getPath())); } }catch(RuuFile.CanNotOpen e){ } } } recursiveAllCache.put(getFullPath(), list); return result; } }
package net.kwmt27.codesearch.util; import android.util.Log; import net.kwmt27.codesearch.BuildConfig; /** * * <p/> * <p><br/> * </p> */ public class Logger { private static final Boolean DEBUG = BuildConfig.DEBUG; /** * DEBUG * * @param msg */ public static void d(String msg) { if (DEBUG) { Log.d(Logger.getLogTagWithMethod(), msg); } } /** * ERROR * * @param msg */ public static void e(String msg) { if (DEBUG) { Log.e(Logger.getLogTagWithMethod(), msg); } } /** * ERRORException * * @param msg * @param tr */ public static void e(String msg, Throwable tr) { if (DEBUG) { Log.e(Logger.getLogTagWithMethod(), msg, tr); } } /** * ERROR Exception * * @param tr */ public static void e(Throwable tr) { if (DEBUG) { Log.e(Logger.getLogTagWithMethod(), tr.getMessage(), tr); } } /** * INFO * * @param msg */ public static void i(String msg) { if (DEBUG) { Log.i(Logger.getLogTagWithMethod(), msg); } } /** * VERBOSE * * @param msg */ public static void v(String msg) { if (DEBUG) { Log.v(Logger.getLogTagWithMethod(), msg); } } /** * WARN * * @param msg */ public static void w(String msg) { if (DEBUG) { Log.w(Logger.getLogTagWithMethod(), msg); } } /** * WARNException * * @param msg * @param tr */ public static void w(String msg, Throwable tr) { if (DEBUG) { Log.w(Logger.getLogTagWithMethod(), msg, tr); } } /** * @return */ private static String getLogTagWithMethod() { Throwable stack = new Throwable().fillInStackTrace(); StackTraceElement[] trace = stack.getStackTrace(); return trace[2].getClassName() + "." + trace[2].getMethodName() + ":" + trace[2].getLineNumber(); } public static void methodOnly() { if(DEBUG) { d(getMethodName()); } } private static String getMethodName() { Throwable stack = new Throwable().fillInStackTrace(); StackTraceElement[] trace = stack.getStackTrace(); return trace[2].getClassName() + "." + trace[2].getMethodName() + " is called."; } }
package sevenbits.sevenbeats; import android.app.AlertDialog; import android.app.SearchManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.media.AudioManager; import android.media.Image; import android.media.MediaPlayer; import android.media.SoundPool; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.webkit.URLUtil; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import android.widget.Toolbar; import java.util.ArrayList; import java.util.List; /** * Tengo que tener un menu lateral que hay que rellenar con * las distintas opciones. De primeras se rellena con las canciones. * */ public class MainActivity extends AppCompatActivity { private BaseDatosAdapter bbdd; public static final String CANCION_NOMBRE = "titulo"; public static final String ALBUM_NOMBRE = "titulo"; public static final String ARTISTA_NOMBRE = "nombre"; public static final String LISTA_NOMBRE = "nombre"; private ListView listaPrincipal; private ListView listaMenu; private GridView gridPrincipal; private DrawerLayout drawerPrincipal; private ArrayList<String> contenidoListaMenu; public static final int EDIT_ID = Menu.FIRST; public static final int DELETE_ID = Menu.FIRST + 1; public static final int SEE_ID = Menu.FIRST + 2; public static final int ADD_ID = Menu.FIRST + 3; public static final int PLAY_ID = Menu.FIRST + 4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ruido al abrir la aplicacion setContentView(R.layout.main_activity); bbdd = new BaseDatosAdapter(this); bbdd.open(); // rellenar lista lateral y lista central setContentView(R.layout.main_activity); listaPrincipal = (ListView) findViewById(R.id.MainActivity_lista_principal); listaMenu = (ListView) findViewById(R.id.MainActivity_lista_menu); gridPrincipal = (GridView) findViewById(R.id.MainActivity_lista_cuadrada); drawerPrincipal = (DrawerLayout) findViewById(R.id.drawer_layout); final float ancho = getResources().getDisplayMetrics().widthPixels; gridPrincipal.setColumnWidth((int) (ancho / 3)); setHandler(); fillData(); fillListaMenuData(); registerForContextMenu(listaPrincipal); registerForContextMenu(gridPrincipal); } protected void onResume(){ super.onResume(); fillData(); } private void setHandler(){ gridPrincipal.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(getApplicationContext(), SeeAlbum.class); Log.d("Debug", "El id es: " + id); i.putExtra("SeeAlbum_album", id); startActivity(i); } }); listaPrincipal.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent; int i = getIntent().getIntExtra("queMostrar", 0); // segun sea una cancion o una artista lanzamos la actividad correspondiente switch (i) { case 0: intent = new Intent(getApplicationContext(), SeeSong.class); intent.putExtra("SeeCancion_cancion", id); startActivity(intent); break; case 2: intent = new Intent(getApplicationContext(), SeeArtist.class); intent.putExtra("SeeArtist_artista", id); startActivity(intent); break; default: break; } } }); } private void fillData(){ int i = getIntent().getIntExtra("queMostrar",0); switch (i){ case 0: setTitle("Canciones"); fillSongData(); break; case 1: setTitle("Albums"); fillAlbumData(); break; case 2: setTitle("Artistas"); fillArtistData(); break; case 3: setTitle("Listas de reproducción"); fillListaData(); break; default: fillSongData(); break; } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); //int orientation = this.getResources().getConfiguration().orientation; final float ancho = getResources().getDisplayMetrics().widthPixels; if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { gridPrincipal.setColumnWidth((int) (ancho / 3)); Log.d("Debug", "Vertical " + (ancho / 3)); gridPrincipal.refreshDrawableState(); } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { gridPrincipal.setColumnWidth((int) (ancho / 3)); Log.d("Debug", "Horizontal" + (ancho / 3)); gridPrincipal.refreshDrawableState(); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Editar"); menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Borrar"); menu.add(Menu.NONE, ADD_ID, Menu.NONE, "Anadir a lista de reproduccion"); menu.add(Menu.NONE, PLAY_ID, Menu.NONE, "Reproducir"); } @Override public boolean onContextItemSelected(MenuItem item) { Log.d("Debug", "Al menu intenta entrar"); final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); switch(item.getItemId()) { case EDIT_ID: int gridOP = getIntent().getIntExtra("queMostrar",0); switch(gridOP){ case 0: Intent i = new Intent(this, SongEdit.class); i.putExtra("id_cancion", info.id); startActivity(i); fillData(); return true; case 1: //ITERACION 2 return true; case 2: i = new Intent(this, SeeArtist.class); i.putExtra("id_artista", info.id); startActivity(i); fillData(); return true; default: return true; } case DELETE_ID: gridOP = getIntent().getIntExtra("queMostrar",0); switch(gridOP){ case 0: bbdd.deleteCancion(info.id); fillData(); return true; case 1: bbdd.deleteAlbum(info.id); fillData(); return true; case 2: bbdd.deleteArtista(info.id); fillData(); return true; default: return true; } case ADD_ID: gridOP = getIntent().getIntExtra("queMostrar",0); switch(gridOP) { case 0: //Anadir cancion a la lista de reproduccion final EditText txtLista = new EditText(this); txtLista.setHint("Pon aqui el nombre de la lista. (Si no existe se creará"); new AlertDialog.Builder(this) .setTitle("Añadir a lista") .setView(txtLista) .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String url = txtLista.getText().toString(); int id = bbdd.fetchIdLista(url); if ( id == -1){ bbdd.createList(url); id = bbdd.fetchIdLista(url); } bbdd.addSongToList(id, info.id); } }) .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .show(); return true; case 1: //ITERACION 2 return true; default: return true; } case PLAY_ID: gridOP = getIntent().getIntExtra("queMostrar",0); switch(gridOP){ case 0: //Reproducir cancion return true; case 1: //ITERACION 2 return true; default: return true; } } return super.onContextItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView search = (SearchView) menu.findItem(R.id.MainActivity_boton_busqueda).getActionView(); search.setSearchableInfo(manager.getSearchableInfo(getComponentName())); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.MainActivity_boton_anyadir: Intent i = new Intent(this, SongEdit.class); startActivity(i); fillData(); return true; default: return super.onOptionsItemSelected(item); } } /** * Rellenamos la informacion de la lista de canciones. */ private void fillSongData() { Cursor cursor = bbdd.fetchAllCancionesByABC(); String[] fromColumns = {CANCION_NOMBRE}; int[] toViews = {R.id.MainActivity_texto_testolista}; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.main_activity_list, cursor, fromColumns, toViews); gridPrincipal.setAdapter(null); listaPrincipal.setAdapter(adapter); } /** * Rellenamos la informacion del grid de caratulas de los albumes. */ private void fillAlbumData() { Cursor cursor = bbdd.fetchAllAlbumsByABC(); GridCursorAdapter adapter = new GridCursorAdapter(this, cursor, getResources().getDisplayMetrics().widthPixels); listaPrincipal.setAdapter(null); gridPrincipal.setAdapter(adapter); } /** * Rellena la lista principal con la informacion de artistas que aparezcan en la base de datos. */ private void fillArtistData() { Cursor cursor = bbdd.fetchAllArtistasByABC(); String[] fromColumns = {ARTISTA_NOMBRE}; int[] toViews = {R.id.MainActivity_texto_testolista}; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.main_activity_list, cursor, fromColumns, toViews); gridPrincipal.setAdapter(null); listaPrincipal.setAdapter(adapter); } /** * Rellenamos la lista principal con la informacion de listas de reproduccion. */ private void fillListaData() { Cursor cursor = bbdd.fetchAllListasByABC(); String[] fromColumns = {LISTA_NOMBRE}; int[] toViews = {R.id.MainActivity_texto_testolista}; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.main_activity_list, cursor, fromColumns, toViews); gridPrincipal.setAdapter(null); listaPrincipal.setAdapter(adapter); } /** * Rellenamos el menu lateral que nos permite cambiar entre canciones, albumes, artistas y * listas de reproduccion. */ private void fillListaMenuData() { contenidoListaMenu = new ArrayList<String>(); contenidoListaMenu.add("Canciones"); contenidoListaMenu.add("Álbumes"); contenidoListaMenu.add("Artistas"); contenidoListaMenu.add("Listas de reproducción"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.main_activity_listmenu, contenidoListaMenu); listaMenu.setAdapter(adapter); listaMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch(position){ case 0: getIntent().putExtra("queMostrar", 0); fillData(); break; case 1: getIntent().putExtra("queMostrar", 1); fillData(); break; case 2: getIntent().putExtra("queMostrar", 2); fillData(); // Toast.makeText(getApplicationContext(),"Artistas",Toast.LENGTH_SHORT).show(); break; case 3: getIntent().putExtra("queMostrar", 3); fillData(); default: Toast.makeText(getApplicationContext(),"Nada",Toast.LENGTH_SHORT).show(); break; } drawerPrincipal.closeDrawer(listaMenu); } }); } }
package teammemes.tritonbudget; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Enter_Info extends AppCompatActivity { SharedPreferences sharedpreferences; // backend //Database mydb; //MenuDataSource menuDS; // frontend private EditText name; private EditText money; //private EditText id; private Button btnDone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_enter__info); // Frontend inti. name = (EditText) findViewById(R.id.EnterName); money = (EditText) findViewById(R.id.EnterMoney); btnDone = (Button) findViewById(R.id.btnConfirm); sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE); // add data button addData(); } public void addData() { btnDone.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { User you=User.getInstance(getApplicationContext()); you.setName( name.getText().toString()); you.setBalance(Double.parseDouble(money.getText().toString())); Toast.makeText(Enter_Info.this,"Thanks",Toast.LENGTH_LONG).show(); finish(); } } ); } }
package general; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class SimpleSeleniumTest { public SimpleSeleniumTest() { driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } public void openMainPageAndClickLogin() { driver.get("szkolenia.forprogress.com.pl:8000/gardenstore");
package WAVLCore; import com.sun.javaws.exceptions.InvalidArgumentException; /** * * WAVLTree * * An implementation of a WAVL Tree with * distinct integer keys and info * */ public class WAVLTree { /** * The root node of the tree, in an empty tree this is null. */ private WAVLNode root = null; /** * An external leaf to be used */ private final WAVLNode externalLeaf = new WAVLNode(); /** * public boolean empty() * <p> * returns true if and only if the tree is empty * @Complexity O(1) */ public boolean empty() { return root == null; } /** * public String search(int k) * <p> * returns the info of an item with key k if it exists in the tree * otherwise, returns null * @Complexity O(log(n)), where n is the number of nodes in the tree (calls searchNode). */ public String search(int k) { WAVLNode node = searchNode(k); if (node != null) { return node.getValue(); } else { return null; } } /** * * returns the node with key k if it exists in the tree * otherwise, returns null * @complexity O(log(n)), where n is the number of nodes in the tree (travels all the way to a node in the w.c). */ public WAVLNode searchNode(int k) { WAVLNode currentNode = root; if (root == null) { return null; }; while (currentNode.isRealNode()) if (k == currentNode.getKey()) { // Match return currentNode; } else if (k < currentNode.getKey()) { if (!currentNode.getRealLeft().isRealNode()) return currentNode; currentNode = currentNode.getRealLeft(); } else { if (!currentNode.getRealRight().isRealNode()) return currentNode; currentNode = currentNode.getRealRight(); } return null; // No match } /** * public int insert(int k, String i) * <p> * inserts an item with key k and info i to the WAVL tree. * the tree must remain valid (keep its invariants). * returns the number of rebalancing operations, or 0 if no rebalancing operations were necessary. * returns -1 if an item with key k already exists in the tree. * @complexity O(log(n)), where n is the number of nodes in the tree (calls searchNode, insertRebalance). */ public int insert(int k, String i) { // Create the root if the tree is empty: if (empty()) { root = new WAVLNode(k, i, null, null, null); // External leaf, no father. return 0; } // Find the father of the insert point: WAVLNode father = searchNode(k); int fatherKey = father.getKey(); if (k == fatherKey) return -1; // Already exists // Create the new node WAVLNode newNode = new WAVLNode(k, i, null, null, father); if (k < fatherKey) { father.setLeft(newNode); } else { father.setRight(newNode); } father.reSetSubtreeSize(); // Re-balance tree if needed: return insertRebalance(newNode); } /** * Re-balance the tree defined by node after an insert. * returns the number of re-balancing operations preformed. * @complexity O(log(n)), where n is the number of nodes in this (in w.c we promote until the root, we also * need to adjust the subtree size in O(log(n)). */ private int insertRebalance(WAVLNode node) { if (node.getFather() == null) { // Root, no need to re-balance. node.reSetSubtreeSize(); return 0; } WAVLNode father = node.getFather(); // No need to re-balance since the new inserted node is with a legit rank: if(father.getRank() != node.getRank()) { reSetSubTreeSizeOfTree(node); // Terminal case, set subtree size all the way to root. return 0; } int fatherRankDif = Math.abs(father.getRankDifferenceFromLeft() - father.getRankDifferenceFromRight()); if (fatherRankDif == 1) { // Case 1: Promote. father.setRank(father.getRank() + 1); father.reSetSubtreeSize(); return 1 + insertRebalance(father); } else if (fatherRankDif == 2) { int nodeRankDif = (node.getRankDifferenceFromLeft()) - (node.getRankDifferenceFromRight()); if ((node.isRightChild() && nodeRankDif == 1) || (node.isLeftChild() && nodeRankDif == -1)) { //Case 2: Single rotate if (node.isRightChild()) { // Right Child, rotate left leftRotate(node); } else { rightRotate(node); } // Update Rank, terminal case: father.setRank(father.getRank() - 1); reSetSubTreeSizeOfTree(node); // Terminal case, set subtree size all the way to root. return 1; } else { // Case 3: Double rotate. if (node.isRightChild()) { // Right Child, double rotate left WAVLNode leftChild = node.getRealLeft(); doubleRotateWithLeftChild(leftChild); leftChild.setRank(leftChild.getRank() + 1); } else { // Left child, double rotate right WAVLNode rightChild = node.getRealRight(); doubleRotateWithRightChild(rightChild); rightChild.setRank(rightChild.getRank() + 1); } // Update ranks: node.setRank(node.getRank() - 1); father.setRank(father.getRank() - 1); reSetSubTreeSizeOfTree(node); // Terminal case, set subtree size all the way to root. return 2; } } return -1; // Can't get here... } /** * Recursively resetting the subtree size starting from node going up until te root * @Complexity O(log(n)), where n is the number of nodes in this */ private void reSetSubTreeSizeOfTree(WAVLNode node) { WAVLNode currentNode = node; while (currentNode.getKey() != root.getKey()) { currentNode.reSetSubtreeSize(); currentNode = currentNode.getFather(); } currentNode.reSetSubtreeSize(); } /** * public int delete(int k) * <p> * deletes an item with key k from the binary tree, if it is there; * the tree must remain valid (keep its invariants). * returns the number of rebalancing operations, or 0 if no rebalancing operations were needed. * returns -1 if an item with key k was not found in the tree. * @complexity O(log(n)), where n is the number of nodes in the tree (calls deleteNode) */ public int delete(int k) { WAVLNode nodeToDelete = searchNode(k); if (nodeToDelete == null) { return -1; } else { return deleteNode(nodeToDelete); } } /** * @param wavlNode the node to delete * @return the number of rebalancing operations, or 0 if no rebalancing operations were needed. * @complexity O(log(n)), where n is the number of nodes in the tree (calls postDeletionRebalancing, getSuccessor). */ public int deleteNode(WAVLNode wavlNode) { WAVLNode wavlNodeAncestor = wavlNode.getFather(); if (wavlNode.isLeaf()) { if (wavlNode.getFather() == null) // one node in tree { root = null; return 0; } else if (wavlNode.isLeftChild()) // left child { wavlNodeAncestor.setLeft(null); } else { //right child wavlNodeAncestor.setRight(null); } return postDeletionRebalancing(wavlNodeAncestor); // rebalancing from ancestor } else if (wavlNode.getRealLeft().isRealNode() && !wavlNode.getRealRight().isRealNode()) { // unary with left node replaceWith(wavlNode, wavlNode.getRealLeft()); return postDeletionRebalancing(wavlNodeAncestor); // rebalancing from ancestor } else if ((!wavlNode.getRealLeft().isRealNode()) && wavlNode.getRealRight().isRealNode()) { // unary with right node replaceWith(wavlNode, wavlNode.getRealRight()); return postDeletionRebalancing(wavlNodeAncestor); // rebalancing from ancestor } else { //binary node WAVLNode successor = getSuccessor(wavlNode); WAVLNode successorAncestor = successor.getFather(); replaceWith(wavlNode, successor); // replace successor with node to delete and balance //System.out.println("asdfasdfasdfasdf: " + successorAncestor.getKey() + " " + wavlNode.getKey()); if (successorAncestor == wavlNode) { //System.out.println(root.getKey() + " " + root.getRealLeft().getKey() + " " + successor.getKey()); return postDeletionRebalancing(successor); // rebalancing from successor in case the node deleted was his ancestor } return postDeletionRebalancing(successorAncestor); // rebalancing tree from successor's ancestor } } // TODO: add complexity docs. /** * rebalance the tree after deletion from a certain point matching the ways we showed at class * * @param node the node to rebalance the wavl tree from * @return the number of rebalancing operations */ private int postDeletionRebalancing(WAVLNode node) { if (node == null) { // We got all the way to the top return 0; } //System.out.println("Here3: " + node.getKey()); // Leaf has rank of 0, rank differences must be 1,1 if (node.isLeaf()) { //System.out.println("Here4: " + node.getKey()); Integer x = postDeletionRebalancingForNode(node); if (x != null) { reSetSubTreeSizeOfTree(node); return x; } } // if false no further actions required. if (node.getRankDifferenceFromRight() <= 2 && node.getRankDifferenceFromLeft() <= 2) { reSetSubTreeSizeOfTree(node); return 0; } // Needs rebalancing. //System.out.println("Here 6:"); // Left rank difference == 3 if (node.getRankDifferenceFromLeft() == 3) { if (node.getRankDifferenceFromRight() == 2) {// Demote node.setRank(node.getRank() - 1); node.reSetSubtreeSize(); return 1 + postDeletionRebalancing(node.getFather()); } if (node.getRankDifferenceFromRight() == 1) { WAVLNode rightChild = node.getRealRight(); if (rightChild.getRankDifferenceFromLeft() == 2 && rightChild.getRankDifferenceFromRight() == 2) { // DoubleDemote rightChild.setRank(rightChild.getRank() - 1); node.setRank(node.getRank() - 1); node.reSetSubtreeSize(); return 2 + postDeletionRebalancing(node.getFather()); } if (rightChild.getRankDifferenceFromRight() == 1) { // Rotate Left leftRotate(rightChild); rightChild.setRank(rightChild.getRank() + 1); node.setRank(node.getRank() - 1); reSetSubTreeSizeOfTree(node); if (node.isLeaf()) { node.setRank(node.getRank() - 1); return 2; } else return 1; } if (rightChild.getRankDifferenceFromRight() == 2) { // Double Rotate WAVLNode left = rightChild.getRealLeft(); doubleRotateWithLeftChild(left); left.setRank(left.getRank() + 2); rightChild.setRank(rightChild.getRank() - 1); node.setRank(node.getRank() - 2); reSetSubTreeSizeOfTree(node); return 2; } } } else { // Right rank difference == 3 //System.out.println("Here 7:"); if (node.getRankDifferenceFromLeft() == 2) {// Demote //System.out.println("Here 8:"); node.setRank(node.getRank() - 1); node.reSetSubtreeSize(); return 1 + postDeletionRebalancing(node.getFather()); } if (node.getRankDifferenceFromLeft() == 1) { WAVLNode leftChild = node.getRealLeft(); if (leftChild.getRankDifferenceFromLeft() == 2 && leftChild.getRankDifferenceFromRight() == 2) { // DoubleDemote leftChild.setRank(leftChild.getRank() - 1); node.setRank(node.getRank() - 1); node.reSetSubtreeSize(); return 2 + postDeletionRebalancing(node.getFather()); } if (leftChild.getRankDifferenceFromLeft() == 1) { // Rotate Right rightRotate(leftChild); leftChild.setRank(leftChild.getRank() + 1); node.setRank(node.getRank() - 1); reSetSubTreeSizeOfTree(node); if (node.isLeaf()) { node.setRank(node.getRank() - 1); return 2; } else return 1; } if (leftChild.getRankDifferenceFromLeft() == 2) { // Double Rotate WAVLNode right = leftChild.getRealRight(); doubleRotateWithRightChild(right); right.setRank(right.getRank() + 2); leftChild.setRank(leftChild.getRank() - 1); node.setRank(node.getRank() - 2); reSetSubTreeSizeOfTree(node); return 2; } } } //System.out.println("Here2: " + node.getKey()); return 0; } // TODO: add docs. private Integer postDeletionRebalancingForNode(WAVLNode node) { if (node.getRankDifferenceFromLeft() == 2 && node.getRankDifferenceFromRight() == 2) { node.setRank(node.getRank() - 1); return 1 + postDeletionRebalancing(node.getFather()); } else if (node.getRankDifferenceFromLeft() == 1 && node.getRankDifferenceFromRight() == 1) return 0; return null; } /** * get successor to a given node * * @param node a node to find successor to * @return successor to a given node, null if it doesn't have one(largest key in tree) * @complexity O(log(n)), where n is the number of nodes in this. might traverse all the way to root. */ private WAVLNode getSuccessor(WAVLNode node) { if (node == null) { return null; } WAVLNode searchNode = node; if (node.getRight() != null) {// if i have a node that is my right child, the most left node in his subtree is my successor searchNode = node.getRealRight(); while (searchNode.getLeft() != null) { searchNode = searchNode.getRealLeft(); } return searchNode; } if (node.getFather() == null) // if i am the root and i didn't find successor by now, it's null return null; if (node.isLeftChild()) // if i'm left to a node he is my successor return node.getFather(); while (searchNode.isRightChild()) { // going up the tree searchNode = node.getFather(); } if (searchNode.getFather() != null) return searchNode.getFather(); return null; } // TODO: add complexity docs /** * private void replaceWith(WAVLNode firstNode, WAVLNode secondNode) * replace a node with another node * Gets two WAVLnodes, firstNode to replace and secondNode to replace it with. * the function place secondNode in place of firstNode according to the algorithm presented to us in class. * and from that can be derived we treat correctly only the following cases: * firstNode is Unary or firstNode is Binary and secondNode is either unary or a leaf. */ /** * we replace a node with other node. we use this for deleting * * @param firstNode the node to replace(unary or binary) * @param secondNode the node to replace with(unary or leaf) */ private void replaceWith(WAVLNode firstNode, WAVLNode secondNode) { WAVLNode firstNodeAncestor = firstNode.getFather(); WAVLNode secondNodeRightBeforeSwitch = secondNode.getRealRight(); WAVLNode secondNodeLeftBeforeSwitch = secondNode.getRealLeft(); WAVLNode secondNodeAncestorBeforeSwitch = secondNode.getFather(); if (firstNode.getRight() != null && firstNode.getLeft() != null) { secondNode.setRank(firstNode.getRank()); if (firstNode.getRealLeft() != secondNode) { secondNode.setLeft(firstNode.getLeft()); firstNode.getRealLeft().setFather(secondNode); } if (firstNode.getRealRight() != secondNode) { secondNode.setRight(firstNode.getRight()); firstNode.getRealRight().setFather(secondNode); } // Detaching secondNode from it's old position attention if secondNode is firstNode's son. if (firstNode.getRight() != secondNode && firstNode.getLeft() != secondNode) { if (!secondNodeLeftBeforeSwitch.isRealNode() && !secondNodeRightBeforeSwitch.isRealNode()) { if (secondNode.isLeftChild()) { secondNodeAncestorBeforeSwitch.setLeft(null); } else { secondNodeAncestorBeforeSwitch.setRight(null); } } else if (secondNodeLeftBeforeSwitch.isRealNode() && !secondNodeRightBeforeSwitch.isRealNode()) { if (secondNode.isLeftChild()) { secondNodeAncestorBeforeSwitch.setLeft(secondNodeLeftBeforeSwitch); secondNodeLeftBeforeSwitch.setFather(secondNodeAncestorBeforeSwitch); } else { secondNodeAncestorBeforeSwitch.setRight(secondNodeLeftBeforeSwitch); secondNodeLeftBeforeSwitch.setFather(secondNodeAncestorBeforeSwitch); } } else if (!secondNodeLeftBeforeSwitch.isRealNode() && secondNodeRightBeforeSwitch.isRealNode()) { if (secondNode.isLeftChild()) { secondNodeAncestorBeforeSwitch.setLeft(secondNodeRightBeforeSwitch); secondNodeRightBeforeSwitch.setFather(secondNodeAncestorBeforeSwitch); } else { secondNodeAncestorBeforeSwitch.setRight(secondNodeRightBeforeSwitch); secondNodeRightBeforeSwitch.setFather(secondNodeAncestorBeforeSwitch); } } } } // Attaching secondNode to it's new parent firstNode's father. if (firstNode.getFather() != null) { secondNode.setFather(firstNodeAncestor); if (firstNode.isRightChild()) firstNodeAncestor.setRight(secondNode); else firstNodeAncestor.setLeft(secondNode); } else { // Special case if firstNode is root. this.root = secondNode; secondNode.setFather(null); } } // Helper Rotation Methods: /** * Performing a rotation with the left child of node. * * @return The new node(tree) after the rotation * @complexity O(1) */ private void leftRotate(WAVLNode node) { WAVLNode father = node.getFather(); WAVLNode grandfather = father.getFather(); WAVLNode leftChild = node.getRealLeft(); if (father == root) { root = node; } if (grandfather != null) { if (grandfather.getRealRight() == father) { grandfather.setRight(node); } else { grandfather.setLeft(node); } } node.setFather(grandfather); node.setLeft(father); father.setFather(node); father.setRight(leftChild); if (leftChild.isRealNode()) { leftChild.setFather(father); } // Re-set subtree size: father.reSetSubtreeSize(); node.reSetSubtreeSize(); if (grandfather != null) { grandfather.reSetSubtreeSize(); } } /** * Performing a rotation with the right child of node. * * @return The new node(tree) after the rotation * @complexity O(1) */ private void rightRotate(WAVLNode node) { WAVLNode father = node.getFather(); WAVLNode grandfather = father.getFather(); WAVLNode rightChild = node.getRealRight(); if (father == root) { root = node; } if (grandfather != null) { if (grandfather.getRealRight() == father) { grandfather.setRight(node); } else { grandfather.setLeft(node); } } node.setFather(grandfather); node.setRight(father); father.setFather(node); father.setLeft(rightChild); if (rightChild.isRealNode()) { rightChild.setFather(father); } // Re-set subtree size: father.reSetSubtreeSize(); node.reSetSubtreeSize(); if (grandfather != null) { grandfather.reSetSubtreeSize(); } } /** * Performing a double rotation with left child. * * @return The new node(tree) after the rotation * @complexity O(1) */ private void doubleRotateWithLeftChild(WAVLNode node) { rightRotate(node); leftRotate(node); } /** * Performing a double rotation with right child. * * @return The new node(tree) after the rotation * @complexity O(1) */ private void doubleRotateWithRightChild(WAVLNode node) { leftRotate(node); rightRotate(node); } /** * public String min() * <p> * Returns the info of the item with the smallest key in the tree, * or null if the tree is empty * @complexity O(log(n)), where n is the number of nodes in the tree */ public String min() { if (empty()) { return null; } else { WAVLNode node = root; while (node.getRealLeft().isRealNode()) { node = node.getRealLeft(); } return node.getValue(); } } /** * public String max() * <p> * Returns the info of the item with the largest key in the tree, * or null if the tree is empty * @complexity O(log(n)), where n is the number of nodes in the tree */ public String max() { if (empty()) { return null; } else { WAVLNode node = root; while (node.getRealRight().isRealNode()) { node = node.getRealRight(); } return node.getValue(); } } /** * @return the in-order traversal of this as an array * @complexity O(n), where n is the number of nodes in this tree. */ private WAVLNode[] inOrderTraversal() { if (empty()) { return new WAVLNode[0]; } WAVLNode[] inOrder = new WAVLNode[size()]; recursiveInOrderTraversal(inOrder, root, 0); return inOrder; } /** * Continuing the in-order traversal from a given node with a given array of pre-inserted nodes. */ private int recursiveInOrderTraversal(WAVLNode[] insertedNodes, WAVLNode node, int numInsertedNodes) { if (!node.isRealNode()) { return numInsertedNodes; } numInsertedNodes = recursiveInOrderTraversal(insertedNodes, node.getRealLeft(), numInsertedNodes); insertedNodes[numInsertedNodes] = node; numInsertedNodes += 1; numInsertedNodes = recursiveInOrderTraversal(insertedNodes, node.getRealRight(), numInsertedNodes); return numInsertedNodes; } /** * public int[] keysToArray() * <p> * Returns a sorted array which contains all keys in the tree, * or an empty array if the tree is empty. * @complexity O(n), where n is the number of nodes in the tree. (calls inOrderTraversal). */ public int[] keysToArray() { WAVLNode[] nodes = inOrderTraversal(); int[] keys = new int[nodes.length]; for (int i = 0; i < nodes.length; i++) { keys[i] = nodes[i].getKey(); } return keys; } /** * public String[] infoToArray() * <p> * Returns an array which contains all info in the tree, * sorted by their respective keys, * or an empty array if the tree is empty. * @complexity O(n), where n is the number of nodes in the tree. (calls inOrderTraversal). */ public String[] infoToArray() { WAVLNode[] nodes = inOrderTraversal(); String[] info = new String[nodes.length]; for (int i = 0; i < nodes.length; i++) { info[i] = nodes[i].getValue(); } return info; } /** * public int size() * <p> * Returns the number of nodes in the tree. * <p> * precondition: none * postcondition: none */ public int size() { return root.getSubtreeSize(); } /** * public int getRoot() * <p> * Returns the root WAVL node, or null if the tree is empty * <p> * precondition: none * postcondition: none */ public WAVLNode getRoot() { return root; } /** * public int select(int i) * <p> * Returns the value of the i'th smallest key (return -1 if tree is empty) * Example 1: select(1) returns the value of the node with minimal key * Example 2: select(size()) returns the value of the node with maximal key * Example 3: select(2) returns the value 2nd smallest minimal node, i.e the value of the node minimal node's successor * <p> * precondition: size() >= i > 0 * postcondition: none */ public String select(int i) { return recursiveSelect(root, i).getValue(); } private WAVLNode recursiveSelect(WAVLNode node, int i) { int r = node.getRealLeft().getSubtreeSize(); if (i == r) { return node; } else if (i < r) { return recursiveSelect(node.getRealLeft(), i); } else { return recursiveSelect(node.getRealRight(), i - r - 1); } } /** * public interface IWAVLNode * ! Do not delete or modify this - otherwise all tests will fail ! */ public interface IWAVLNode{ public int getKey(); //returns node's key (for virtuval node return -1) public String getValue(); //returns node's value [info] (for virtuval node return null) public IWAVLNode getLeft(); //returns left child (if there is no left child return null) public IWAVLNode getRight(); //returns right child (if there is no right child return null) public boolean isRealNode(); // Returns True if this is a non-virtual WAVL node (i.e not a virtual leaf or a sentinal) public int getSubtreeSize(); // Returns the number of real nodes in this node's subtree (Should be implemented in O(1)) } /** * public class WAVLNode * <p> * If you wish to implement classes other than WAVLTree * (for example WAVLNode), do it in this file, not in * another file. * This class can and must be modified. * (It must implement IWAVLNode) */ public class WAVLNode implements IWAVLNode { /** * The right child of this if exists */ private WAVLNode rightChild; /** * The left child of this if exists */ private WAVLNode leftChild; /** * The info (String) of this */ private String info; /** * The key (Integer) of this */ private Integer key; /** * The number of nodes in the tree defined by this as its root. */ private Integer subTreeSize; /** * The rank of this */ private Integer rank; /** * The father of this */ private WAVLNode father; /** * For external leafs only. */ private WAVLNode() { this.rank = -1; this.subTreeSize = 0; } public WAVLNode(Integer key, String info, WAVLNode rightChild, WAVLNode leftChild, WAVLNode father) { if (key == null) { throw new IllegalArgumentException("Key cloud not be null"); } if (rightChild == null) { this.rightChild = externalLeaf; } else { this.rightChild = rightChild; } if (leftChild == null) { this.leftChild = externalLeaf; } else { this.leftChild = leftChild; } this.info = info; this.key = key; reSetSubtreeSize(); this.rank = max(this.rightChild.getRank(), this.leftChild.getRank()) + 1; this.father = father; } public int getKey() { if (isRealNode()) { return this.key; } else { return -1; } } public String getValue() { if (isRealNode()) { return this.info; } else { return null; } } /** * get the real right node, not null for external but the static external node * * @return the real right node, not null for external but the static external node */ public WAVLNode getRealRight() { return this.rightChild; } /** * get the real left node, not null for external but the static external node * * @return the real left node, not null for external but the static external node */ public WAVLNode getRealLeft() { return this.leftChild; } public WAVLNode getLeft() { return this.getRealLeft() == externalLeaf ? null : this.getRealLeft(); } public WAVLNode getRight() { return this.getRealRight() == externalLeaf ? null : this.getRealRight(); } /** * @return True if this is a non-virtual WAVL node (i.e not a virtual leaf or a sentinal) */ public boolean isRealNode() { return this.key != null; } public int getSubtreeSize() { return subTreeSize; } public int getRank() { return this.rank; } public void setRight(WAVLNode rightChild) { if (rightChild == null) { this.rightChild = externalLeaf; } else { this.rightChild = rightChild; } } public void setLeft(WAVLNode leftChild) { if (leftChild == null) { this.leftChild = externalLeaf; } else { this.leftChild = leftChild; } } public void setSubTreeSize(Integer subTreeSize) { this.subTreeSize = subTreeSize; } public void setRank(Integer rank) { this.rank = rank; } public WAVLNode getFather() { return this.father; } public void setFather(WAVLNode father) { this.father = father; } /** * @return boolean to tell if the node is leaf or not */ public boolean isLeaf() { return ((getLeft() == null) && (getRight() == null)); } /** * check if a node is a left child * * @return true if a node is a left child, false if it's not */ public boolean isLeftChild() { return ((this.getFather() != null) && (this.getFather().getLeft() == this)); } /** * check if node is a right child * * @return true if a node is a right child, false if it's not */ public boolean isRightChild() { return ((this.getFather() != null) && (this.getFather().getRight() == this)); } /** * get rank difference from right node * * @return rank difference from right node */ private int getRankDifferenceFromRight() { return this.getRank() - this.getRealRight().getRank(); } /** * get rank difference from left node * * @return rank difference from left node */ private int getRankDifferenceFromLeft() { return this.getRank() - this.getRealLeft().getRank(); } /** * Resetting the subtree size var according to the right and the left children * @Complexity O(1) */ public void reSetSubtreeSize() { this.setSubTreeSize(getRealRight().getSubtreeSize() + getRealLeft().getSubtreeSize() + 1); } /** * @return the bigger between x and y */ private int max(int x, int y) { if (x > y) { return x; } else { return y; } } } }
package model; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Stack; import java.util.logging.Level; import java.util.logging.Logger; import com.thoughtworks.xstream.annotations.XStreamAlias; import controller.LastState; import controller.LastState.LastCommand; import controller.UserInput.RepeatDate; import exception.RedoException; import exception.TaskDoneException; import exception.TaskInvalidDateException; import exception.TaskInvalidIdException; import exception.TaskNoSuchTagException; import exception.TaskTagDuplicateException; import exception.TaskTagException; import exception.UndoException; public class TaskList { /** * This Comparator is used in outputting task list order by deadline * * @author Jiang Sheng * */ static class DeadlineComparator implements Comparator<Task> { @Override public int compare(Task o1, Task o2) { try { return o1.getDeadline().compareTo(o2.getDeadline()); } catch (TaskInvalidDateException e) { logger.log(Level.WARNING, "Error comparing deadline."); } return 0; } } /** * This Comparator is used in outputting task list order by added time * * @author Jiang Sheng * */ static class AddedDateComparator implements Comparator<Task> { @Override public int compare(Task o1, Task o2) { return o1.getAddedTime().compareTo(o2.getAddedTime()); } } static class DoneDateComparator implements Comparator<Task> { @Override public int compare(Task o1, Task o2) { return o1.getDoneDate().compareTo(o2.getDoneDate()); } } private static Logger logger = Logger.getLogger("TaskList"); static Stack<LastState> undoStack = new Stack<LastState>(); static Stack<LastState> redoStack = new Stack<LastState>(); @XStreamAlias("TaskListTimed") private List<Task> tasksTimed; @XStreamAlias("TaskListUntimed") private List<Task> tasksUntimed; @XStreamAlias("TaskFinished") private List<Task> tasksFinished; @XStreamAlias("TaskToDisplay") private List<Task> tasksToDisplay; @XStreamAlias("showDisplay") private boolean isDisplay; @XStreamAlias("showDone") private boolean isShowingDone; @XStreamAlias("TasksCount") private int totalTasks; @XStreamAlias("Tags") private HashMap<String, List<Task>> tags; // count the total number of tasks finished. @XStreamAlias("TotalTaskFinished") private int totalFinished; public TaskList() { // let the logger only display warning log message. logger.setLevel(Level.WARNING); this.tasksTimed = new SortedArrayList<Task>(new DeadlineComparator()); this.tasksUntimed = new SortedArrayList<Task>(new AddedDateComparator()); this.tasksFinished = new SortedArrayList<Task>(new DoneDateComparator()); this.tasksToDisplay = new ArrayList<Task>(); this.totalTasks = this.tasksTimed.size() + this.tasksUntimed.size(); this.tags = new HashMap<String, List<Task>>(); this.totalFinished = 0; this.isDisplay = false; } /** * If setShowDisplayListToFalse is called, display the whole list. */ public void setShowDisplayListToFalse() { this.isDisplay = false; this.tasksToDisplay.clear(); } public Task getTask(int taskIndex) { if (isDisplay) { if ((taskIndex >= tasksToDisplay.size()) || (taskIndex < 0)) { throw new TaskInvalidIdException("Error index for editing!"); } else { return tasksToDisplay.get(taskIndex); } } else { if ((taskIndex >= totalTasks) || (taskIndex < 0)) { throw new TaskInvalidIdException("Error index for editing!"); } else { // get edit id from timed/ untimed list if (taskIndex < tasksTimed.size()) { return tasksTimed.get(taskIndex); } else { return tasksUntimed.get(taskIndex - tasksTimed.size()); } } } } /** * * @param task * @return taskid of given task */ public int getTaskIndex(Task task) { if (tasksTimed.contains(task)) { return tasksTimed.indexOf(task); } else if (tasksUntimed.contains(task)) { return tasksUntimed.indexOf(task) + tasksTimed.size(); } else { return -1; } } /** * @param task * * this method is called by markTaskDone, if task is a repeat task * this method is called by undo, to undo the deleting of tasks. * this method will not call the addToUndoList function */ private void addToList(Task task) { if (task.getIsDone()) { System.out.println(this.tasksFinished.getClass()); ((SortedArrayList<Task>) this.tasksFinished).addOrder(task); } else { System.out.println(this.tasksUntimed.getClass()); if (task instanceof FloatingTask) { ((SortedArrayList<Task>) this.tasksUntimed).addOrder(task); } else { ((SortedArrayList<Task>) this.tasksTimed).addOrder(task); } this.totalTasks++; } } /** * Adding a floating task * * @param description * the description of the task */ public void addToList(String description) { Task newTask = new FloatingTask(description); this.tasksUntimed.add(newTask); this.totalTasks++; logger.log(Level.INFO, "A floating task added"); addToUndoList(LastCommand.ADD, newTask, this.getTaskIndex(newTask)); } /** * Add a deadline task * * @param description * the description of the task * @param time * the deadline of the task */ public void addToList(String description, Date time) { Task newTask = new DeadlineTask(description, time); ((SortedArrayList<Task>) this.tasksTimed).addOrder(newTask); this.totalTasks++; logger.log(Level.INFO, "A deadline task added"); addToUndoList(LastCommand.ADD, newTask, this.getTaskIndex(newTask)); } /** * Add a Repeated Task * * @param description * the description of the task * @param time * the deadline of the task * @param repeatDate * the repeat frequency */ public void addToList(String description, Date time, RepeatDate repeatDate) { Task newTask = new RepeatedTask(description, time, repeatDate); ((SortedArrayList<Task>) this.tasksTimed).addOrder(newTask); this.totalTasks++; logger.log(Level.INFO, "A repeated task added"); addToUndoList(LastCommand.ADD, newTask, this.getTaskIndex(newTask)); } /** * Add a fixed(timed) task * * @param description * the description of the task * @param startTime * the start time of the task * @param endTime * the deadline of the task * @throws TaskInvalidDateException */ public void addToList(String description, Date startTime, Date endTime) throws TaskInvalidDateException { Task newTask = new FixedTask(description, startTime, endTime); if (!startTime.before(endTime)) { throw new TaskInvalidDateException( "Invalid: Start date/time cannot be after end date/time."); } else { ((SortedArrayList<Task>) this.tasksTimed).addOrder(newTask); this.totalTasks++; logger.log(Level.INFO, "A fixed task added"); addToUndoList(LastCommand.ADD, newTask, this.getTaskIndex(newTask)); } } public void editTaskDescription(int taskIndex, String description) throws TaskInvalidIdException { if (isInvalidIndex(taskIndex)) { throw new TaskInvalidIdException("Error index for editing!"); } else { int indexToEdit = taskIndex - 1; Task taskToRemove = getTask(indexToEdit); // if the index comes from a list used for displaying, use time to // find if (isDisplay) { boolean isFound = false; // trace the task by added time. for (Task task : this.tasksTimed) { if (task.getAddedTime().equals(taskToRemove.getAddedTime())) { task.setDescription(description); isFound = true; break; } } if (!isFound) { for (Task task : this.tasksUntimed) { if (task.getAddedTime().equals( taskToRemove.getAddedTime())) { task.setDescription(description); break; } } } } else { if (indexToEdit < tasksTimed.size()) { this.tasksTimed.get(indexToEdit) .setDescription(description); } else { // update the index to the proper value in tasksUntimed. indexToEdit -= tasksTimed.size(); this.tasksUntimed.get(indexToEdit).setDescription( description); } } } } public void editTaskDeadline(int taskIndex, Date time) throws TaskInvalidIdException, TaskInvalidDateException { if (isInvalidIndex(taskIndex)) { throw new TaskInvalidIdException("Error index for editing!"); } else { int indexToEdit = taskIndex - 1; Task taskToRemove = getTask(indexToEdit); // if the index comes from a list used for displaying, use time to // find if (isDisplay) { boolean isFound = false; // trace the task by added time. for (Task task : this.tasksTimed) { if (task.getAddedTime().equals(taskToRemove.getAddedTime())) { task.setDeadline(time); isFound = true; break; } } if (!isFound) { for (Task task : this.tasksUntimed) { if (task.getAddedTime().equals( taskToRemove.getAddedTime())) { task.setDeadline(time); break; } } } } else { if (indexToEdit < tasksTimed.size()) { this.tasksTimed.get(indexToEdit).setDeadline(time); } else { // update the index to the proper value in tasksUntimed. indexToEdit -= tasksTimed.size(); this.tasksUntimed.get(indexToEdit).setDeadline(time); } } ((SortedArrayList<Task>) this.tasksTimed) .updateListOrder(taskIndex - 1); } } public void editTaskStartDate(int taskIndex, Date startDate) throws TaskInvalidIdException { if (isInvalidIndex(taskIndex)) { throw new TaskInvalidIdException("Error index for editing!"); } else { int indexToEdit = taskIndex - 1; Task taskToRemove = getTask(indexToEdit); // if the index comes from a list used for displaying, use time to // find if (isDisplay) { boolean isFound = false; // trace the task by added time. for (Task task : this.tasksTimed) { if (task.getAddedTime().equals(taskToRemove.getAddedTime())) { task.setStartTime(startDate); isFound = true; break; } } if (!isFound) { for (Task task : this.tasksUntimed) { if (task.getAddedTime().equals( taskToRemove.getAddedTime())) { task.setStartTime(startDate); break; } } } } else { if (indexToEdit < tasksTimed.size()) { this.tasksTimed.get(indexToEdit).setStartTime(startDate); } else { // update the index to the proper value in tasksUntimed. indexToEdit -= tasksTimed.size(); this.tasksUntimed.get(indexToEdit).setStartTime(startDate); } } } } /* * public void editTaskRepeatPeriod(int taskIndex, String repeatPeriod) { if * ((taskIndex > totalTasks) || (taskIndex <= 0)) { // error here } else { * this.tasks.get(taskIndex-1).setRepeatPeriod(repeatPeriod); } * * } */ /** * @param task * * this method is called by undo, to undo the adding of tasks. * this method will not call the addToUndoList function */ private void deleteFromList(Task task) { if (tasksTimed.contains(task)) { tasksTimed.remove(task); } else { tasksUntimed.remove(task); } } public void deleteFromList(List<Integer> taskIndexList) throws TaskInvalidIdException { if (taskIndexList.isEmpty()) { throw new TaskInvalidIdException("Nothing to delete"); } else { ArrayList<Task> tasksRemoved = new ArrayList<Task>(); Collections.sort(taskIndexList); for (int i = taskIndexList.size() - 1; i >= 0; i int indexToRemove = taskIndexList.get(i); if (isShowingDone) { // displaying done tasks if (indexToRemove>this.tasksFinished.size() || indexToRemove<=0) { throw new TaskInvalidIdException("Error index for deleting!"); } else { tasksRemoved.add(this.tasksFinished.remove(indexToRemove - 1)); } this.totalTasks } else { if (isInvalidIndex(indexToRemove)) { throw new TaskInvalidIdException("Error index for deleting!"); } else { Task taskToRemove = getTask(indexToRemove - 1); tasksRemoved.add(taskToRemove); // if the index comes from a list used for displaying, use // time to find boolean isFound = false; // trace the task by added time. for (Task task : this.tasksTimed) { if (task.getAddedTime().equals( taskToRemove.getAddedTime())) { this.tasksTimed.remove(task); isFound = true; break; } } if (!isFound) { for (Task task : this.tasksUntimed) { if (task.getAddedTime().equals( taskToRemove.getAddedTime())) { this.tasksUntimed.remove(task); break; } } } this.totalTasks } } } addToUndoList(LastCommand.DELETE, tasksRemoved, -1); } } public void clearList() { ArrayList<Task> tasksRemoved = new ArrayList<Task>(); tasksRemoved.addAll(tasksUntimed); tasksRemoved.addAll(tasksTimed); tasksRemoved.addAll(tasksFinished); addToUndoList(LastCommand.DELETE, tasksRemoved, -1); this.isDisplay = false; this.tasksUntimed.clear(); this.tasksTimed.clear(); this.tasksUntimed.clear(); this.tasksFinished.clear(); this.tags.clear(); this.totalTasks = 0; this.totalFinished = 0; } public void markTaskDone(List<Integer> taskIndexList) throws TaskDoneException, TaskInvalidIdException { if (taskIndexList.isEmpty()) { throw new TaskInvalidIdException("Error index input."); } else { List<Task> tasksToMarkDone = new ArrayList<Task>(); List<Task> tasksMarkedDone = new ArrayList<Task>(); // putting the tasks to be marked done into a list, // since marking a task done would move it into a new list, // changing the order (using index might not work) for (int i = 0; i < taskIndexList.size(); i++) { int taskIdToMarkDone = taskIndexList.get(i); if (isInvalidIndex(taskIdToMarkDone)) { throw new TaskInvalidIdException("Error index input."); } else { Task taskToMarkDone = getTask(taskIdToMarkDone - 1); tasksToMarkDone.add(taskToMarkDone); } } for (Task target : tasksToMarkDone) { tasksMarkedDone.add(target.clone()); Task newRepeatTask = null; if (this.tasksUntimed.contains(target)) { newRepeatTask = target.markDone(); this.tasksUntimed.remove(target); this.tasksFinished.add(target); } else if (this.tasksTimed.contains(target)) { newRepeatTask = target.markDone(); this.tasksTimed.remove(target); this.tasksFinished.add(target); } this.totalFinished++; if (newRepeatTask != null) { this.addToList((RepeatedTask) newRepeatTask); } } addToUndoList(LastCommand.DONE, tasksMarkedDone, -1); } } public void tagTask(int taskIndexToTag, String tag) throws TaskInvalidIdException, TaskTagDuplicateException { if (isInvalidIndex(taskIndexToTag)) { throw new TaskInvalidIdException(); } else { Task taskToTag = getTask(taskIndexToTag - 1); taskToTag.addTag(tag); if (!tags.containsKey(tag.toLowerCase())) { List<Task> tagTaskList = new ArrayList<Task>(); tagTaskList.add(taskToTag); tags.put(tag.toLowerCase(), tagTaskList); } else { List<Task> tagTaskList = tags.remove(tag.toLowerCase()); tagTaskList.add(taskToTag); tags.put(tag.toLowerCase(), tagTaskList); } } } public void untagTask(int taskIndexToUntag, String tag) throws TaskInvalidIdException, TaskTagException { if (isInvalidIndex(taskIndexToUntag)) { throw new TaskInvalidIdException(); } else if (tag.isEmpty()) { untagTaskAll(taskIndexToUntag - 1); } else { Task taskToTag = getTask(taskIndexToUntag - 1); taskToTag.deleteTag(tag); if (tags.get(tag.toLowerCase()).size() == 1) { tags.remove(tag.toLowerCase()); } else { List<Task> tagTaskList = tags.remove(tag.toLowerCase()); tagTaskList.remove(taskToTag); tags.put(tag.toLowerCase(), tagTaskList); } } } private void untagTaskAll(int taskIndexToUntag) throws TaskTagException { Task taskToUntag = getTask(taskIndexToUntag); List<String> taskTags = taskToUntag.getTags(); if (taskTags.isEmpty()) { throw new TaskTagException("No tags to remove"); } while (!taskTags.isEmpty()) { String tag = taskTags.remove(0); assert tags.get(tag.toLowerCase()).contains(taskToUntag); tags.get(tag.toLowerCase()).remove(taskToUntag); taskToUntag.deleteTag(tag); } } public List<Task> getFinishedTasks() { isShowingDone = true; return this.tasksFinished; } public List<Task> getTasksWithTag(String tag) throws TaskNoSuchTagException { if (tags.containsKey(tag.toLowerCase())) { List<Task> taskListOfTag = tags.get(tag.toLowerCase()); return taskListOfTag; } else { throw new TaskNoSuchTagException(); } } /*** * This method search tasks by a given keyword * * @param keyword * the keyword for searching * @return a list of result * * Noticed: this method will find keyword in a task's description as * well as tags */ public List<Task> searchTaskByKeyword(String keyword) { keyword = keyword.toLowerCase(); List<Task> result = new ArrayList<Task>(); if (isShowingDone) { for (Task task : tasksFinished) { if (task.getDescription().toLowerCase().indexOf(keyword) != -1) { System.out.println("find one"); result.add(task); continue; // find one } else { for (String tag : task.getTags()) { if (tag.toLowerCase().indexOf(keyword) != -1) { result.add(task); break; // find one } } } } } else { // search task in timed list, search description and tags for (Task task : tasksTimed) { if (task.getDescription().toLowerCase().indexOf(keyword) != -1) { result.add(task); continue; // find one } else { for (String tag : task.getTags()) { if (tag.toLowerCase().indexOf(keyword) != -1) { result.add(task); break; // find one } } } } // search task in untimed list, search description and tags for (Task task : tasksUntimed) { if (task.getDescription().toLowerCase().indexOf(keyword) != -1) { result.add(task); continue; // find one } else { for (String tag : task.getTags()) { if (tag.toLowerCase().indexOf(keyword) != -1) { result.add(task); break; // find one } } } } isDisplay = true; } tasksToDisplay = result; return tasksToDisplay; } public List<Task> prepareDisplayList(String tag) throws TaskNoSuchTagException { if (tags.containsKey(tag.toLowerCase())) { tasksToDisplay = tags.get(tag.toLowerCase()); // check overdue for each task for (Task task : tasksToDisplay) { try { task.checkOverdue(); } catch (TaskInvalidDateException e) { logger.log(Level.WARNING, "Invalid Deadline when checking Overdue!"); } } isDisplay = true; return tasksToDisplay; } else { throw new TaskNoSuchTagException(); } } public List<Task> prepareDisplayList(boolean isDisplayedByAddTime) { List<Task> output; // check overdue for each task for (Task task : tasksTimed) { try { task.checkOverdue(); } catch (TaskInvalidDateException e) { logger.log(Level.WARNING, "Invalid Deadline when checking Overdue!"); } } if (isDisplayedByAddTime) { // using comparator AddedDateComparator output = new SortedArrayList<Task>(this.count(), new AddedDateComparator()); output.addAll(tasksTimed); output.addAll(tasksUntimed); isDisplay = true; tasksToDisplay = output; } else { output = new ArrayList<Task>(this.tasksTimed); for (int i = 0; i < tasksUntimed.size(); i++) { output.add(tasksUntimed.get(i)); } isDisplay = false; } // add all tasks from Timed task list and Untimed task list to the // output list return output; } public boolean isShowingDone() { return this.isShowingDone; } public void setNotShowingDone() { this.isShowingDone = false; } /** * @param taskIndex * @return */ public boolean isInvalidIndex(int taskIndex) { return (taskIndex > this.countUndone()) || (taskIndex <= 0); } public void undo() throws UndoException { if (undoStack.isEmpty()) { throw new UndoException(); } else { setShowDisplayListToFalse(); LastState lastState = undoStack.pop(); if (lastState.getLastCommand() == LastCommand.ADD) { Task task = lastState.getPreviousTaskState(); deleteFromList(task); } else if (lastState.getLastCommand() == LastCommand.DELETE) { List<Task> tasksToReadd = lastState.getPreviousTaskStateList(); for (Task task : tasksToReadd) { addToList(task); } } else { // do other undo operations here } } } public void redo() throws RedoException{ if (redoStack.isEmpty()) { throw new RedoException(); } else { //redo here based on cmd type } } private void addToUndoList(LastCommand cmd, Task task, int taskIndex) { LastState currentTaskState = new LastState(cmd, task, taskIndex); undoStack.push(currentTaskState); } private void addToUndoList(LastCommand cmd, List<Task> tasks, int taskIndex) { LastState currentTaskState = new LastState(cmd, tasks, taskIndex); undoStack.push(currentTaskState); } private void addToUndoList(LastCommand cmd, List<Task> tasks, List<Integer> taskIndices) { LastState currentTasksState = new LastState(cmd, tasks, taskIndices); undoStack.push(currentTasksState); } public int count() { return this.totalTasks; } public int countUndone() { return this.countTimedTask()+this.countUntimedTask(); } public int countTimedTask() { return this.tasksTimed.size(); } public int countUntimedTask() { return this.tasksUntimed.size(); } public int countFinished() { return this.totalFinished; } }
package org.pcap4j.core; import java.net.Inet4Address; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.pcap4j.core.BpfProgram.BpfCompileMode; import org.pcap4j.core.NativeMappings.PcapErrbuf; import org.pcap4j.core.NativeMappings.PcapLibrary; import org.pcap4j.core.NativeMappings.bpf_program; import org.pcap4j.core.NativeMappings.pcap_if; import org.pcap4j.packet.namednumber.DataLinkType; import org.pcap4j.util.ByteArrays; import org.pcap4j.util.Inet4NetworkAddress; import org.pcap4j.util.MacAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; /** * @author Kaito Yamada * @since pcap4j 0.9.1 */ public final class Pcaps { private static final Logger logger = LoggerFactory.getLogger(Pcaps.class); private Pcaps() { throw new AssertionError(); } /** * * @return a list of PcapNetworkInterfaces. * @throws PcapNativeException */ public static List<PcapNetworkInterface> findAllDevs() throws PcapNativeException { PointerByReference alldevsPP = new PointerByReference(); PcapErrbuf errbuf = new PcapErrbuf(); int rc = NativeMappings.pcap_findalldevs(alldevsPP, errbuf); if (rc != 0) { StringBuilder sb = new StringBuilder(50); sb.append("Return code: ") .append(rc) .append(", Message: ") .append(errbuf); throw new PcapNativeException(sb.toString(), rc); } if (errbuf.length() != 0) { logger.warn("{}", errbuf); } Pointer alldevsp = alldevsPP.getValue(); if (alldevsp == null) { logger.info("No NIF was found."); return Collections.<PcapNetworkInterface>emptyList(); } pcap_if pcapIf = new pcap_if(alldevsp); List<PcapNetworkInterface> ifList = new ArrayList<PcapNetworkInterface>(); for (pcap_if pif = pcapIf; pif != null; pif = pif.next) { ifList.add(PcapNetworkInterface.newInstance(pif, true)); } NativeMappings.pcap_freealldevs(pcapIf.getPointer()); logger.info("{} NIF(s) found.", ifList.size()); return ifList; } /** * * @param addr * @return a PcapNetworkInterface. * @throws PcapNativeException */ public static PcapNetworkInterface getDevByAddress( InetAddress addr ) throws PcapNativeException { if (addr == null) { StringBuilder sb = new StringBuilder(); sb.append("addr: ").append(addr); throw new NullPointerException(sb.toString()); } List<PcapNetworkInterface> allDevs = findAllDevs(); for (PcapNetworkInterface pif: allDevs) { for (PcapAddress paddr: pif.getAddresses()) { if (paddr.getAddress().equals(addr)) { return pif; } } } return null; } /** * * @param name * @return a PcapNetworkInterface. * @throws PcapNativeException */ public static PcapNetworkInterface getDevByName( String name ) throws PcapNativeException { if (name == null) { StringBuilder sb = new StringBuilder(); sb.append("name: ").append(name); throw new NullPointerException(sb.toString()); } List<PcapNetworkInterface> allDevs = findAllDevs(); for (PcapNetworkInterface pif: allDevs) { if (pif.getName().equals(name)) { return pif; } } return null; } /** * * @return a name of a network interface. * @throws PcapNativeException */ public static String lookupDev() throws PcapNativeException { PcapErrbuf errbuf = new PcapErrbuf(); Pointer result = NativeMappings.pcap_lookupdev(errbuf); if (result == null || errbuf.length() != 0) { throw new PcapNativeException(errbuf.toString()); } return result.getWideString(0); } /** * * @param devName * @return an {@link org.pcap4j.util.Inet4NetworkAddress Inet4NetworkAddress} object. * @throws PcapNativeException */ public static Inet4NetworkAddress lookupNet( String devName ) throws PcapNativeException { if (devName == null) { StringBuilder sb = new StringBuilder(); sb.append("devName: ").append(devName); throw new NullPointerException(sb.toString()); } PcapErrbuf errbuf = new PcapErrbuf(); IntByReference netp = new IntByReference(); IntByReference maskp = new IntByReference(); int rc = NativeMappings.pcap_lookupnet(devName, netp, maskp, errbuf); if (rc < 0) { throw new PcapNativeException(errbuf.toString(), rc); } int net = netp.getValue(); int mask = maskp.getValue(); return new Inet4NetworkAddress( Inets.itoInetAddress(net), Inets.itoInetAddress(mask) ); } /** * * @param filePath "-" means stdin * @return a new PcapHandle object. * @throws PcapNativeException */ public static PcapHandle openOffline( String filePath ) throws PcapNativeException { if (filePath == null) { StringBuilder sb = new StringBuilder(); sb.append("filePath: ").append(filePath); throw new NullPointerException(sb.toString()); } PcapErrbuf errbuf = new PcapErrbuf(); Pointer handle = NativeMappings.pcap_open_offline(filePath, errbuf); if (handle == null || errbuf.length() != 0) { throw new PcapNativeException(errbuf.toString()); } return new PcapHandle(handle); } /** * * @param filePath "-" means stdin * @param precision * @return a new PcapHandle object. * @throws PcapNativeException */ public static PcapHandle openOffline ( String filePath, TimestampPrecision precision ) throws PcapNativeException { if (filePath == null) { StringBuilder sb = new StringBuilder(); sb.append("filePath: ").append(filePath); throw new NullPointerException(sb.toString()); } PcapErrbuf errbuf = new PcapErrbuf(); Pointer handle; try { handle = PcapLibrary.INSTANCE.pcap_open_offline_with_tstamp_precision( filePath, precision.value, errbuf ); } catch (UnsatisfiedLinkError e) { throw new PcapNativeException( "pcap_open_offline_with_tstamp_precision is not supported by the pcap library" + " installed in this environment." ); } if (handle == null || errbuf.length() != 0) { throw new PcapNativeException(errbuf.toString()); } return new PcapHandle(handle); } /** * * @param dlt * @param snaplen Snapshot length, which is the number of bytes captured for each packet. * @return a new PcapHandle object. * @throws PcapNativeException */ public static PcapHandle openDead( DataLinkType dlt, int snaplen ) throws PcapNativeException { if (dlt == null) { StringBuilder sb = new StringBuilder(); sb.append("dlt: ").append(dlt); throw new NullPointerException(sb.toString()); } Pointer handle = NativeMappings.pcap_open_dead(dlt.value(), snaplen); if (handle == null) { StringBuilder sb = new StringBuilder(50); sb.append("Failed to open a PcapHandle. dlt: ").append(dlt) .append(" snaplen: ").append(snaplen); throw new PcapNativeException(sb.toString()); } return new PcapHandle(handle); } /** * * @param snaplen * @param dlt * @param bpfExpression * @param mode * @param netmask * @return a {@link org.pcap4j.core.BpfProgram BpfProgram} object. * @throws PcapNativeException */ public static BpfProgram compileFilter( int snaplen, DataLinkType dlt, String bpfExpression, BpfCompileMode mode, Inet4Address netmask ) throws PcapNativeException { if ( dlt == null || bpfExpression == null || mode == null || netmask == null ) { StringBuilder sb = new StringBuilder(); sb.append("dlt: ").append(dlt) .append(" bpfExpression: ").append(bpfExpression) .append(" mode: ").append(mode) .append(" netmask: ").append(netmask); throw new NullPointerException(sb.toString()); } bpf_program prog = new bpf_program(); int rc = NativeMappings.pcap_compile_nopcap( snaplen, dlt.value(), prog, bpfExpression, mode.getValue(), ByteArrays.getInt(ByteArrays.toByteArray(netmask), 0) ); if (rc < 0) { throw new PcapNativeException( "Failed to compile the BPF expression: " + bpfExpression, rc ); } return new BpfProgram(prog, bpfExpression); } /** * @param name a data link type name, which is a DLT_ name with the DLT_ removed. * @return a {@link org.pcap4j.packet.namednumber.DataLinkType DataLinkType} object. * @throws PcapNativeException */ public static DataLinkType dataLinkNameToVal( String name ) throws PcapNativeException { if (name == null) { StringBuilder sb = new StringBuilder(); sb.append("name: ").append(name); throw new NullPointerException(sb.toString()); } int rc = NativeMappings.pcap_datalink_name_to_val(name); if (rc < 0) { throw new PcapNativeException( "Failed to convert the data link name to the value: " + name, rc ); } return DataLinkType.getInstance(rc); } /** * @param dlt * @return data link type name * @throws PcapNativeException */ public static String dataLinkTypeToName( DataLinkType dlt ) throws PcapNativeException { if (dlt == null) { StringBuilder sb = new StringBuilder(); sb.append("dlt: ").append(dlt); throw new NullPointerException(sb.toString()); } return dataLinkValToName(dlt.value()); } /** * @param dataLinkVal * @return data link type name * @throws PcapNativeException */ public static String dataLinkValToName( int dataLinkVal ) throws PcapNativeException { String name = NativeMappings.pcap_datalink_val_to_name(dataLinkVal); if (name == null) { throw new PcapNativeException( "Failed to convert the data link value to the name: " + dataLinkVal ); } return name; } /** * @param dlt * @return a short description of that data link type. * @throws PcapNativeException */ public static String dataLinkTypeToDescription( DataLinkType dlt ) throws PcapNativeException { if (dlt == null) { StringBuilder sb = new StringBuilder(); sb.append("dlt: ").append(dlt); throw new NullPointerException(sb.toString()); } return dataLinkValToDescription(dlt.value()); } /** * @param dataLinkVal * @return a short description of that data link type. * @throws PcapNativeException */ public static String dataLinkValToDescription( int dataLinkVal ) throws PcapNativeException { String descr = NativeMappings.pcap_datalink_val_to_description(dataLinkVal); if (descr == null) { throw new PcapNativeException( "Failed to convert the data link value to the description: " + dataLinkVal ); } return descr; } /** * @param error * @return an error message. */ public static String strError(int error) { return NativeMappings.pcap_strerror(error).getString(0); } /** * @return a string giving information about the version of the libpcap library being used; * note that it contains more information than just a version number. */ public static String libVersion() { return NativeMappings.pcap_lib_version(); } /** * * @param inetAddr Inet4Address or Inet6Address * @return a string representation of an InetAddress for BPF. */ public static String toBpfString(InetAddress inetAddr){ if (inetAddr == null) { StringBuilder sb = new StringBuilder(); sb.append("inetAddr: ").append(inetAddr); throw new NullPointerException(sb.toString()); } String strAddr = inetAddr.toString(); return strAddr.substring(strAddr.lastIndexOf("/") + 1); } /** * * @param macAddr * @return a string representation of a MAC address for BPF. */ public static String toBpfString(MacAddress macAddr) { if (macAddr == null) { StringBuilder sb = new StringBuilder(); sb.append("macAddr: ").append(macAddr); throw new NullPointerException(sb.toString()); } StringBuffer buf = new StringBuffer(); byte[] address = macAddr.getAddress(); for (int i = 0; i < address.length; i++) { buf.append(String.format("%02x", address[i])); buf.append(":"); } buf.deleteCharAt(buf.length() - 1); return buf.toString(); } /** * @author Kaito Yamada * @version pcap4j 1.5.1 */ public static enum TimestampPrecision { /** * use timestamps with microsecond precision, default */ MICRO(0), /** * use timestamps with nanosecond precision */ NANO(1); private final int value; private TimestampPrecision(int value) { this.value = value; } /** * * @return value */ public int getValue() { return value; } } }
package abc.player; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JDialog; import org.antlr.v4.gui.Trees; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.misc.Utils; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import abc.parser.HeaderLexer; import abc.parser.HeaderListener; import abc.parser.HeaderParser; import abc.parser.HeaderParser.CommentContext; import abc.parser.HeaderParser.ComposerContext; import abc.parser.HeaderParser.EndlineContext; import abc.parser.HeaderParser.HeaderContext; import abc.parser.HeaderParser.IndexContext; import abc.parser.HeaderParser.KeyContext; import abc.parser.HeaderParser.LengthContext; import abc.parser.HeaderParser.MeterContext; import abc.parser.HeaderParser.OtherfieldsContext; import abc.parser.HeaderParser.RootContext; import abc.parser.HeaderParser.TempoContext; import abc.parser.HeaderParser.TextContext; import abc.parser.HeaderParser.TitleContext; import abc.parser.HeaderParser.VoiceContext; import abc.parser.MusicLexer; import abc.parser.MusicListener; import abc.parser.MusicParser; import abc.parser.MusicParser.ChordContext; import abc.parser.MusicParser.DoublebarmeasureContext; import abc.parser.MusicParser.ElementContext; import abc.parser.MusicParser.EndrepeatmeasureContext; import abc.parser.MusicParser.FirstendingmeasureContext; import abc.parser.MusicParser.MeasureContext; import abc.parser.MusicParser.MusicContext; import abc.parser.MusicParser.NormalmeasureContext; import abc.parser.MusicParser.NoteContext; import abc.parser.MusicParser.NoteelementContext; import abc.parser.MusicParser.NotelengthContext; import abc.parser.MusicParser.PitchContext; import abc.parser.MusicParser.RestContext; import abc.parser.MusicParser.SecondendingmeasureContext; import abc.parser.MusicParser.StartrepeatmeasureContext; import abc.parser.MusicParser.TupletelementContext; import abc.parser.MusicParser.TupletspecContext; public class Parser { public static Header parseHeader(String input){ // try{ // Create a stream of characters from the string CharStream stream = new ANTLRInputStream(input); HeaderLexer lexer = new HeaderLexer(stream); TokenStream tokens = new CommonTokenStream(lexer); HeaderParser parser = new HeaderParser(tokens); lexer.reportErrorsAsExceptions(); parser.reportErrorsAsExceptions(); // Generate the parse tree using the starter rule. // root is the starter rule for this grammar. // Other grammars may have different names for the starter rule. ParseTree tree = parser.root(); // Future<JDialog> inspect = Trees.inspect(tree, parser); // try { // Utils.waitForClose(inspect.get()); // } catch (Exception e) { // e.printStackTrace(); MakeHeader headerMaker = new MakeHeader(); new ParseTreeWalker().walk(headerMaker, tree); return headerMaker.getHeader(); // catch(Exception e){ // System.out.println(e.getMessage()); //not used after debugging } static class MakeHeader implements HeaderListener { private final Stack<String> requiredStack = new Stack<>(); private final Stack<String> optionalStack = new Stack<>(); public Header getHeader(){ int index = -1; String title = ""; KeySignature keySignature= KeySignature.valueOf("NEGATIVE"); // parse/check existence of required fields index, header, keySignature while (!requiredStack.isEmpty()){ String context = requiredStack.pop(); // System.out.println(context); // if (context.contains("missing")){ //parse out index, header, and keySignature if (context.contains("X:")){ Pattern pattern = Pattern.compile("[0-9-]+"); Matcher matcher = pattern.matcher(context); if (matcher.find()){ index = Integer.valueOf( matcher.group()); } } else if (context.contains("T:")){ title = context.replace("T:", "").replace("\n", ""); } else if (context.contains("K:")){ String key = ""; context = context.replace("K:", ""); Pattern pattern = Pattern.compile("[A-G]"); Matcher matcher = pattern.matcher(context); if (matcher.find()){ key += matcher.group(); } if (context.contains("b")){ key+="_FLAT"; } else if (context.contains(" key+="_SHARP"; } if(context.contains("m")){ key+="_MINOR"; } else{ key+="_MAJOR"; } keySignature = KeySignature.valueOf(key); } } //missing one of index, header or keySig // if(index < 0 || title.equals("") || keySignature.equals(KeySignature.valueOf("NEGATIVE"))){ Header header = new Header(index, title, keySignature); //parse other fields while (!optionalStack.isEmpty()){ String context = optionalStack.pop(); // System.out.println(context); // if (context.contains("missing")|| !(context.contains(":"))){ if (context.contains("C:")){ String composer = context.replace("C:", "").replace("\n", ""); header.setComposer(composer); } if (context.contains("M:")){ // System.out.println(context); if(context.contains("C|")){ header.setMeter(new Fraction(2,2)); } else if(context.contains("C")){ header.setMeter(new Fraction(4, 4)); } else{ context = context.replace("M:", "").replace("\n", ""); Fraction meter = parseFraction(context); header.setMeter(meter); } } if (context.contains("L:")){ context = context.replace("L:", "").replace("\n", ""); Fraction noteLength = parseFraction(context); header.setNoteLength(noteLength);; } if (context.contains("Q:")){ Pattern pattern = Pattern.compile("=[0-9]+"); Matcher matcher = pattern.matcher(context); int tempo = -1; if (matcher.find()){ String group = matcher.group(); tempo = Integer.valueOf(group.replace("=", "")); context = context.replace(group, "").replace("\n", "").replace("Q:", ""); } else{ throw new IllegalArgumentException(); } Fraction given = parseFraction(context); Fraction headerLength = header.noteLength(); double tempoOffset = given.numerator()*headerLength.denominator()/(given.denominator()*headerLength.numerator()); header.setTempo((int)(tempo/tempoOffset)); } if (context.contains("V:")){ String voice = context.replace("V:", "").replace("\n", ""); header.addVoice(voice); } } return header; } private Fraction parseFraction(String context){ String[] nums = context.split("/"); // fraction doesn't have correct number of / // if (nums.length >2){ int numerator = Integer.valueOf(nums[0]); int denominator = Integer.valueOf(nums[1]); return new Fraction(numerator, denominator); } @Override public void exitRoot(HeaderParser.RootContext ctx) { } @Override public void exitHeader(HeaderParser.HeaderContext ctx) { } @Override public void exitIndex(HeaderParser.IndexContext ctx) { requiredStack.push(ctx.getText()); } @Override public void exitTitle(HeaderParser.TitleContext ctx) { requiredStack.push(ctx.getText()); } @Override public void exitOtherfields(HeaderParser.OtherfieldsContext ctx) { } @Override public void exitComposer(HeaderParser.ComposerContext ctx) { optionalStack.push(ctx.getText()); } @Override public void exitMeter(HeaderParser.MeterContext ctx) { System.out.println(ctx.getText()); optionalStack.push(ctx.getText()); } @Override public void exitLength(HeaderParser.LengthContext ctx) { optionalStack.push(ctx.getText()); } @Override public void exitTempo(HeaderParser.TempoContext ctx) { optionalStack.push(ctx.getText()); } @Override public void exitVoice(HeaderParser.VoiceContext ctx) { optionalStack.push(ctx.getText()); } @Override public void exitKey(HeaderParser.KeyContext ctx) { requiredStack.push(ctx.getText()); } @Override public void exitComment(HeaderParser.CommentContext ctx) { } @Override public void exitText(HeaderParser.TextContext ctx) { } @Override public void enterEveryRule(ParserRuleContext arg0) { } @Override public void exitEveryRule(ParserRuleContext arg0) { } @Override public void visitErrorNode(ErrorNode arg0) { } @Override public void visitTerminal(TerminalNode arg0) { } @Override public void enterRoot(RootContext ctx) { } @Override public void enterHeader(HeaderContext ctx) { } @Override public void enterIndex(IndexContext ctx) { } @Override public void enterTitle(TitleContext ctx) { } @Override public void enterOtherfields(OtherfieldsContext ctx) { } @Override public void enterComposer(ComposerContext ctx) { } @Override public void enterMeter(MeterContext ctx) { } @Override public void enterLength(LengthContext ctx) { } @Override public void enterTempo(TempoContext ctx) { } @Override public void enterVoice(VoiceContext ctx) { } @Override public void enterKey(KeyContext ctx) { } @Override public void enterComment(CommentContext ctx) { } @Override public void enterText(TextContext ctx) { } @Override public void enterEndline(EndlineContext ctx) { // TODO Auto-generated method stub } @Override public void exitEndline(EndlineContext ctx) { // TODO Auto-generated method stub } } public static Music parseMusic(String input, Fraction defaultNoteLength, KeySignature keySig){ // try{ // Create a stream of characters from the string CharStream stream = new ANTLRInputStream(input); MusicLexer lexer = new MusicLexer(stream); TokenStream tokens = new CommonTokenStream(lexer); MusicParser parser = new MusicParser(tokens); lexer.reportErrorsAsExceptions(); parser.reportErrorsAsExceptions(); // Generate the parse tree using the starter rule. // root is the starter rule for this grammar. // Other grammars may have different names for the starter rule. ParseTree tree = parser.root(); // Future<JDialog> inspect = Trees.inspect(tree, parser); // try { // Utils.waitForClose(inspect.get()); // } catch (Exception e) { // e.printStackTrace(); MakeMusic musicMaker = new MakeMusic(keySig, defaultNoteLength); new ParseTreeWalker().walk(musicMaker, tree); return musicMaker.getMusic(); // catch(RuntimeException e){ // System.out.println(e.getMessage()); //not used after debugging } static class MakeMusic implements MusicListener{ private final Map<NoteLetter, Accidental> keySig; private final Fraction defaultNoteLength; private final Map<Accidental, Integer> accidental = new HashMap<Accidental, Integer>(); private final Stack<Music> stack = new Stack<>(); private final Stack<List<Music>> listStack = new Stack<>(); // public MakeMusic(){ // KeySignatureMap map = new KeySignatureMap(); // this.keySig = KeySignatureMap.KEY_SIGNATURE_MAP.get(KeySignature.valueOf("C_MAJOR")); // accidental.put(Accidental.valueOf("DOUBLESHARP"), 2); // accidental.put(Accidental.valueOf("SHARP"), 1); // accidental.put(Accidental.valueOf("NATURAL"), 0); // accidental.put(Accidental.valueOf("FLAT"), -1); // accidental.put(Accidental.valueOf("DOUBLEFLAT"), -2); public MakeMusic(KeySignature keysig, Fraction defaultNoteLength){ KeySignatureMap map = new KeySignatureMap(); this.defaultNoteLength = defaultNoteLength; this.keySig = map.KEY_SIGNATURE_MAP.get(keysig); accidental.put(Accidental.valueOf("DOUBLESHARP"), 2); accidental.put(Accidental.valueOf("SHARP"), 1); accidental.put(Accidental.valueOf("NATURAL"), 0); accidental.put(Accidental.valueOf("FLAT"), -1); accidental.put(Accidental.valueOf("DOUBLEFLAT"), -2); } public Music getMusic(){ return stack.get(0); } @Override public void exitRoot(MusicParser.RootContext ctx) { } @Override public void exitMusic(MusicContext ctx) { } @Override public void exitMeasure(MeasureContext ctx) { } @Override public void exitFirstendingmeasure(FirstendingmeasureContext ctx) { int numNorm = ctx.normalmeasure().size(); List<Music> measures = new ArrayList<Music>(); for (int i = 0; i < numNorm; i++){ measures.add(stack.pop()); } Measure startFirstEnding = (Measure) stack.pop(); Measure replacedStartFirst = new Measure(startFirstEnding, true, false, false, false); measures.add(replacedStartFirst); Collections.reverse(measures); for (int i = 0; i < numNorm + 1; i++){ stack.push(measures.get(i)); } } @Override public void exitSecondendingmeasure(SecondendingmeasureContext ctx) { } @Override public void exitDoublebarmeasure(DoublebarmeasureContext ctx) { int numElements = ctx.element().size(); List<Music> elements = new ArrayList<Music>(); for (int i = 0; i < numElements; i++){ elements.add(stack.pop()); } Collections.reverse(elements); applyAccidentalsToMeasure(elements); Measure m = new Measure(elements, false, false, false, true); stack.push(m); } @Override public void exitStartrepeatmeasure(StartrepeatmeasureContext ctx) { int numElements = ctx.element().size(); List<Music> elements = new ArrayList<Music>(); for (int i = 0; i < numElements; i++){ elements.add(stack.pop()); } Collections.reverse(elements); applyAccidentalsToMeasure(elements); Measure m = new Measure(elements, true, false, false, false); stack.push(m); } @Override public void exitEndrepeatmeasure(EndrepeatmeasureContext ctx) { int numElements = ctx.element().size(); List<Music> elements = new ArrayList<Music>(); for (int i = 0; i < numElements; i++){ elements.add(stack.pop()); } Collections.reverse(elements); applyAccidentalsToMeasure(elements); Measure m = new Measure(elements, false, true, false, false); stack.push(m); } @Override public void exitNormalmeasure(NormalmeasureContext ctx) { int numElements = ctx.element().size(); assert stack.size()>= numElements; List<Music> elements = new ArrayList<Music>(); for (int i = 0; i < numElements; i++){ elements.add(stack.pop()); } Collections.reverse(elements); applyAccidentalsToMeasure(elements); Measure m = new Measure(elements, false, false, false, false); stack.push(m); } /** * Checks from beginning to end if list of music elements has accidentals and applies these * to the rest of the list if found * @param elements list of music elements to apply accidentals to * @return modified list of elements */ private List<Music> applyAccidentalsToMeasure(List<Music> elements){ // make sure accidentals apply to the entire line boolean transpose = false; char note = 'y'; int octave = 0; int semitonesUp= 0; for (Music m : elements){ List<Note> notesToCheck = new ArrayList<Note>(); if(m instanceof Chord){ Chord chord = (Chord)m; notesToCheck = extractChordNotes(chord); } else if(m instanceof Tuplet){ Tuplet tuplet = (Tuplet)m; notesToCheck = extractTupletNotes(tuplet); } else if (m instanceof Note){ Note n = (Note)m; notesToCheck= Arrays.asList(n); } for (Note n: notesToCheck){ if (n.getTransposeTag()){ transpose = true; note = n.getNoteLetter(); octave = n.getOctave(); semitonesUp = n.getAccidental(); } if(transpose){ n.transposeKey(note, octave, semitonesUp); } } } return elements; } private List<Note> extractChordNotes(Chord chord){ List<Note> notes = new ArrayList<Note>(); for(Music music:chord.chordNotes()){ notes.add((Note)music); } return notes; } private List<Note> extractTupletNotes(Tuplet tuplet){ List<Note> notes = new ArrayList<Note>(); for(Music music: tuplet.tupletNotes()){ if (music instanceof Chord){ Chord chord = (Chord)music; notes.addAll(extractChordNotes(chord)); } else{ Note note = (Note)music; notes.add(note); } } return notes; } @Override public void exitElement(ElementContext ctx) { } @Override public void exitNoteelement(NoteelementContext ctx) { } @Override public void exitNote(NoteContext ctx) { } @Override public void exitPitch(PitchContext ctx) { System.out.println(ctx.NOTELETTER().getText()); Fraction noteLength = defaultNoteLength; int octave = 0; char noteLetter = 'y'; int numAccidental = 0; boolean transpose = false; if (ctx.NOTELETTER()!= null){ char note = ctx.NOTELETTER().getText().charAt(0); if (Character.isLowerCase(note)){ octave +=1; } noteLetter = Character.toUpperCase(note); Accidental acc = keySig.get(NoteLetter.valueOf(Character.toString(noteLetter))); numAccidental += accidental.get(acc); } if (ctx.OCTAVE()!= null){ String octaves = ctx.OCTAVE().getText(); if (octaves.contains(",")){ octave -= octaves.length(); } else if(octaves.contains("'")){ octave += octaves.length(); } } if (ctx.notelength()!= null){ String length = ctx.notelength().getText(); noteLength = parseNoteLength(length); } if (ctx.ACCIDENTAL()!= null){ String accidental = ctx.ACCIDENTAL().getText(); if (accidental.contains("_")){ numAccidental = -(accidental.length()); } if (accidental.contains("^")){ numAccidental = accidental.length(); } else{ numAccidental = 0; } transpose = true; } Note n = new Note(noteLength, noteLetter, octave, numAccidental, transpose); stack.push(n); } @Override public void exitRest(RestContext ctx) { Fraction noteLength = defaultNoteLength; if (ctx.notelength()!= null){ String length = ctx.notelength().getText(); noteLength = parseNoteLength(length); } Rest r = new Rest(noteLength); stack.push(r); } @Override public void exitNotelength(NotelengthContext ctx) { } @Override public void exitTupletelement(TupletelementContext ctx) { int tupletNum = Integer.valueOf(ctx.tupletspec().getText().replace("(", "")); int tupletSize = ctx.noteelement().size(); assert tupletSize >= tupletNum; assert tupletNum > 1 && tupletNum < 5; List<Music> tupletNotes = new ArrayList<Music>(); for (int i = 0; i < tupletSize; i++){ tupletNotes.add(stack.pop()); } Collections.reverse(tupletNotes); Tuplet t = new Tuplet(tupletNum, tupletNotes); stack.push(t); } @Override public void exitTupletspec(TupletspecContext ctx) { } @Override public void exitChord(ChordContext ctx) { List<NoteContext> notes = ctx.note(); assert stack.size() >= notes.size(); assert notes.size()>= 1; List<Music> chordNotes = new ArrayList<Music>(); for (int i = 0; i < notes.size(); i++){ chordNotes.add(stack.pop()); } Collections.reverse(chordNotes); Music m = new Chord(chordNotes); stack.push(m); } private Fraction parseNoteLength(String length){ int numerator; int denominator; if(!length.contains("/")){ numerator = Integer.valueOf(length); denominator = 1; } else{ String[] nums = length.split("/"); if (nums.length == 0){ numerator = 1; denominator = 2; } else if (nums.length == 1){ numerator = Integer.valueOf(nums[0]); denominator = 2; } else{ numerator = (nums[0].equals("")) ? 1 : Integer.valueOf(nums[0]); denominator = Integer.valueOf(nums[1]); } } return new Fraction(numerator * defaultNoteLength.numerator(), denominator * defaultNoteLength.denominator()).simplify(); } @Override public void exitComment(MusicParser.CommentContext ctx) { } @Override public void exitText(MusicParser.TextContext ctx) { } @Override public void enterEveryRule(ParserRuleContext arg0) { } @Override public void exitEveryRule(ParserRuleContext arg0) { } @Override public void visitErrorNode(ErrorNode arg0) { } @Override public void visitTerminal(TerminalNode arg0) { } @Override public void enterRoot(abc.parser.MusicParser.RootContext ctx) {} @Override public void enterMusic(MusicContext ctx) {} @Override public void enterNote(NoteContext ctx) { } @Override public void enterRest(RestContext ctx) {} @Override public void enterNotelength(NotelengthContext ctx) {} @Override public void enterTupletspec(TupletspecContext ctx) {} @Override public void enterComment(abc.parser.MusicParser.CommentContext ctx) { } @Override public void enterText(abc.parser.MusicParser.TextContext ctx) { } @Override public void enterChord(ChordContext ctx) { } @Override public void enterNoteelement(NoteelementContext ctx) { } @Override public void enterMeasure(MeasureContext ctx) { } @Override public void enterTupletelement(TupletelementContext ctx) { } @Override public void enterFirstendingmeasure(FirstendingmeasureContext ctx) { } @Override public void enterSecondendingmeasure(SecondendingmeasureContext ctx) { } @Override public void enterDoublebarmeasure(DoublebarmeasureContext ctx) { } @Override public void enterStartrepeatmeasure(StartrepeatmeasureContext ctx) { } @Override public void enterEndrepeatmeasure(EndrepeatmeasureContext ctx) { } @Override public void enterNormalmeasure(NormalmeasureContext ctx) { } @Override public void enterElement(ElementContext ctx) { } @Override public void enterPitch(PitchContext ctx) { } } }
package algo; import java.util.ArrayList; import java.util.Set; import org.jgrapht.graph.SimpleWeightedGraph; import schedulable.Transportation; import search.DFS; import search.TreeSearch; import state.MatchingState; import time.TimeBlock; import activities.ActivitySpanningTree; import activities.Location; /** * Automatically matches each AST with a TB * * @author chiao-yutuan * */ public class ASTTBMatcher { /** * Matches each AST with a TB in its availableTBs list, then pass to * scheduler. If scheduler failed, try to find the next possible match * config * * @param graph * The graph to pass on to the scheduler * @param asts * Set of asts to match with. Their data structure contains the * availableTBs * @return Result of the scheduler as an arraylist of timeblocks */ public static ArrayList<TimeBlock> matching( SimpleWeightedGraph<Location, Transportation> graph, Set<ActivitySpanningTree> asts) { // construct the initial state MatchingState root = new MatchingState(asts); TreeSearch searcher = new TreeSearch(new DFS(), root); // for each goal state, pass to next module and wait for response MatchingState goal; while ((goal = (MatchingState) searcher.nextGoal()) != null) { ArrayList<TimeBlock> schedule = Scheduler.autoScheduleAll(graph, goal.getMatches()); if (schedule != null) { return schedule; } } return null; } }
package gcm.util; public class GlobalConstants { public static final String KREP_STRING = "Kr"; public static final String KACT_STRING = "Ka"; public static final String KBIO_STRING = "Kbio"; public static final String PROMOTER_COUNT_STRING = "ng"; public static final String KASSOCIATION_STRING = "Kassociation"; // Dimerization value public static final String KBASAL_STRING = "kb"; public static final String OCR_STRING = "ko"; public static final String KDECAY_STRING = "kd"; public static final String RNAP_STRING = "nr"; public static final String RNAP_BINDING_STRING = "Ko"; public static final String ACTIVATED_RNAP_BINDING_STRING = "Kao"; public static final String STOICHIOMETRY_STRING = "np"; public static final String COOPERATIVITY_STRING = "nc"; public static final String ACTIVED_STRING = "ka"; public static final String KCOMPLEX_STRING = "Kc"; public static final String COMPLEX = "complex"; public static final String GENE_PRODUCT = "gene product"; public static final String TRANSCRIPTION_FACTOR = "transcription factor"; public static final String DIFFUSIBLE = "diffusible"; public static final String MEMDIFF_STRING = "kmdiff"; public static final String FORWARD_MEMDIFF_STRING = "kfmdiff"; public static final String REVERSE_MEMDIFF_STRING = "krmdiff"; // public static final String KREP_VALUE = ".5"; // public static final String KACT_VALUE = ".0033"; // public static final String KBIO_VALUE = ".05"; // public static final String PROMOTER_COUNT_VALUE = "2"; // public static final String KASSOCIATION_VALUE = ".05"; // public static final String KBASAL_VALUE = ".0001"; // public static final String OCR_VALUE = ".05"; // public static final String KDECAY_VALUE = ".0075"; // public static final String RNAP_VALUE = "30"; // public static final String RNAP_BINDING_VALUE = ".033"; // public static final String STOICHIOMETRY_VALUE = "10"; // public static final String COOPERATIVITY_VALUE = "2"; // public static final String ACTIVED_VALUE = ".25"; public static final String ID = "ID"; public static final String COMPONENT = "Component"; public static final String SPECIES = "Species"; public static final String INFLUENCE = "Influence"; public static final String COMPONENT_CONNECTION = "Component Connection"; public static final String PRODUCTION = "Production"; public static final String REACTION = "Reaction"; public static final String MODIFIER = "Modifier"; public static final String REACTION_EDGE = "Reaction_Edge"; public static final String PORTMAP = "Port Map"; public static final String NAME = "Name"; public static final String CONSTANT = "boundary"; public static final String SPASTIC = "constitutive"; public static final String NORMAL = "normal"; public static final String INPUT = "input"; public static final String OUTPUT = "output"; public static final String INTERNAL = "internal"; public static final String TYPE = "Type"; public static final String MAX_DIMER_STRING = "N-mer as trascription factor"; public static final String INITIAL_STRING = "ns"; public static final String PROMOTER = "Promoter"; public static final String EXPLICIT_PROMOTER = "ExplicitPromoter"; public static final String SBMLFILE = "SBML file"; public static final String BIOABS = "Biochemical abstraction"; public static final String DIMABS = "Dimerization abstraction"; public static final String BIO = "biochem"; public static final String ACTIVATION = "activation"; public static final String REPRESSION = "repression"; public static final String NOINFLUENCE = "no influence"; public static final String TRUE = "true"; public static final String FALSE = "false"; public static final String NONE = "none"; public static final String OK = "Ok"; public static final String CANCEL = "Cancel"; // public static final String MAX_DIMER_VALUE = "1"; // public static final String INITIAL_VALUE = "0"; // public static final String DIMER_COUNT_STRING = "label"; // public static final String TYPE_STRING = "label"; public static final int DEFAULT_SPECIES_WIDTH = 100; public static final int DEFAULT_SPECIES_HEIGHT = 30; public static final int DEFAULT_REACTION_WIDTH = 30; public static final int DEFAULT_REACTION_HEIGHT = 30; public static final int DEFAULT_COMPONENT_WIDTH = 80; public static final int DEFAULT_COMPONENT_HEIGHT = 40; }
package rv.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JRadioButtonMenuItem; import rv.Configuration; import rv.Viewer; public class MenuBar extends JMenuBar { private final Viewer viewer; private final JMenu server; private final Configuration.Networking config; private final List<String> serverHosts; public MenuBar(Viewer viewer) { this.viewer = viewer; server = new JMenu("Server"); config = viewer.getConfig().networking; serverHosts = new ArrayList<>(config.serverHosts); String overriddenHost = config.overriddenServerHost; if (overriddenHost != null) { serverHosts.remove(overriddenHost); serverHosts.add(0, overriddenHost); } for (String host : serverHosts) { final JRadioButtonMenuItem item = new JRadioButtonMenuItem(host, server.getItemCount() == 0); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectServer(item); } }); server.add(item); } add(server); } private void selectServer(JRadioButtonMenuItem item) { int selectedIndex = -1; for (int i = 0; i < server.getItemCount(); i++) { JRadioButtonMenuItem currentItem = (JRadioButtonMenuItem) server.getItem(i); currentItem.setSelected(false); if (currentItem == item) { selectedIndex = i; } } item.setSelected(true); String host = serverHosts.get(selectedIndex); if (host.equals(config.getServerHost())) return; config.overrideServerHost(host); viewer.getDrawings().clearAllShapeSets(); viewer.getNetManager().getServer().changeConnection(host, config.serverPort); } }
import java.lang.reflect.*; import java.io.*; import java.net.*; import java.util.*; import org.xbill.DNS.*; import org.xbill.DNS.utils.*; /** @author Brian Wellington &lt;bwelling@xbill.org&gt; */ public class jnamed { Hashtable caches; Hashtable znames; Hashtable TSIGs; public jnamed(String conffile) throws IOException { FileInputStream fs; boolean started = false; try { fs = new FileInputStream(conffile); } catch (Exception e) { System.out.println("Cannot open " + conffile); return; } caches = new Hashtable(); znames = new Hashtable(); TSIGs = new Hashtable(); BufferedReader br = new BufferedReader(new InputStreamReader(fs)); String line = null; while ((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); if (!st.hasMoreTokens()) continue; String keyword = st.nextToken(); if (!st.hasMoreTokens()) { System.out.println("Invalid line: " + line); continue; } if (keyword.charAt(0) == ' continue; if (keyword.equals("primary")) addPrimaryZone(st.nextToken(), st.nextToken()); if (keyword.equals("secondary")) addSecondaryZone(st.nextToken(), st.nextToken()); else if (keyword.equals("cache")) { Cache cache = new Cache(st.nextToken()); caches.put(new Short(DClass.IN), cache); } else if (keyword.equals("key")) addTSIG(st.nextToken(), st.nextToken()); else if (keyword.equals("port")) { short port = Short.parseShort(st.nextToken()); addUDP(port); addTCP(port); started = true; } } if (!started) { addUDP((short) 53); addTCP((short) 53); } System.out.println("running"); } public void addPrimaryZone(String zname, String zonefile) throws IOException { Name origin = null; Cache cache = getCache(DClass.IN); if (zname != null) origin = new Name(zname, Name.root); Zone newzone = new Zone(zonefile, cache, origin); znames.put(newzone.getOrigin(), newzone); /*System.out.println("Adding zone named <" + newzone.getOrigin() + ">");*/ } public void addSecondaryZone(String zone, String remote) throws IOException { Cache cache = getCache(DClass.IN); Name zname = new Name(zone); Zone newzone = new Zone(zname, DClass.IN, remote, cache); znames.put(zname, newzone); /*System.out.println("Adding zone named <" + zname + ">");*/ } public void addTSIG(String name, String key) { TSIGs.put(new Name(name), base64.fromString(key)); } public Cache getCache(short dclass) { Cache c = (Cache) caches.get(new Short(dclass)); if (c == null) { c = new Cache(dclass); caches.put(new Short(dclass), c); } return c; } public Zone findBestZone(Name name) { Zone foundzone = null; foundzone = (Zone) znames.get(name); if (foundzone != null) return foundzone; int labels = name.labels(); for (int i = 1; i < labels; i++) { Name tname = new Name(name, i); foundzone = (Zone) znames.get(tname); if (foundzone != null) return foundzone; } return null; } public RRset findExactMatch(Name name, short type, short dclass, boolean glue) { Zone zone = findBestZone(name); if (zone != null) return zone.findExactMatch(name, type); else { RRset [] rrsets; Cache cache = getCache(dclass); if (glue) rrsets = cache.findAnyRecords(name, type); else rrsets = cache.findRecords(name, type); if (rrsets == null) return null; else return rrsets[0]; /* not quite right */ } } void addRRset(Name name, Message response, RRset rrset, byte section, boolean sigonly) { Enumeration e; for (byte s = 1; s <= section; s++) if (response.findRRset(name, rrset.getType(), s)) return; if (!sigonly) { e = rrset.rrs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); if (!name.isWild() && r.getName().isWild()) r = r.withName(name); response.addRecord(r, section); } } e = rrset.sigs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); if (!name.isWild() && r.getName().isWild()) r = r.withName(name); response.addRecord(r, section); } } private void addSOA(Message response, Zone zone) { response.addRecord(zone.getSOA(), Section.AUTHORITY); } private void addNS(Message response, Zone zone) { RRset nsRecords = zone.getNS(); addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, false); } private void addCacheNS(Message response, Cache cache, Name name) { SetResponse sr = cache.lookupRecords(name, Type.NS, Credibility.HINT); if (!sr.isDelegation()) return; RRset nsRecords = sr.getNS(); Enumeration e = nsRecords.rrs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); response.addRecord(r, Section.AUTHORITY); } } private void addGlue(Message response, Name name) { RRset a = findExactMatch(name, Type.A, DClass.IN, true); if (a == null) return; if (response.findRRset(name, Type.A)) return; Enumeration e = a.rrs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); response.addRecord(r, Section.ADDITIONAL); } e = a.sigs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); response.addRecord(r, Section.ADDITIONAL); } } private void addAdditional2(Message response, int section) { Enumeration e = response.getSection(section); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); Name glueName = null; switch (r.getType()) { case Type.MX: glueName = ((MXRecord)r).getTarget(); break; case Type.NS: glueName = ((NSRecord)r).getTarget(); break; case Type.KX: glueName = ((KXRecord)r).getTarget(); break; case Type.NAPTR: glueName = ((NAPTRRecord)r).getReplacement(); break; case Type.SRV: glueName = ((SRVRecord)r).getTarget(); break; default: break; } if (glueName != null) addGlue(response, glueName); } } void addAdditional(Message response) { addAdditional2(response, Section.ANSWER); addAdditional2(response, Section.AUTHORITY); } byte addAnswer(Message response, Name name, short type, short dclass, int iterations) { SetResponse sr; boolean sigonly; byte rcode = Rcode.NOERROR; if (iterations > 6) return Rcode.NOERROR; if (type == Type.SIG) { type = Type.ANY; sigonly = true; } else sigonly = false; Zone zone = findBestZone(name); if (zone != null) sr = zone.findRecords(name, type); else { Cache cache = getCache(dclass); sr = cache.lookupRecords(name, type, Credibility.NONAUTH_ANSWER); } if (sr.isUnknown()) { addCacheNS(response, getCache(dclass), name); } if (sr.isNXDOMAIN()) { response.getHeader().setRcode(Rcode.NXDOMAIN); if (zone != null) { addSOA(response, zone); if (iterations == 0) response.getHeader().setFlag(Flags.AA); } rcode = Rcode.NXDOMAIN; } else if (sr.isNXRRSET()) { if (zone != null) { addSOA(response, zone); if (iterations == 0) response.getHeader().setFlag(Flags.AA); } } else if (sr.isDelegation()) { RRset nsRecords = sr.getNS(); addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, false); } else if (sr.isCNAME()) { RRset rrset = new RRset(); CNAMERecord cname = sr.getCNAME(); rrset.addRR(cname); addRRset(name, response, rrset, Section.ANSWER, false); if (zone != null && iterations == 0) response.getHeader().setFlag(Flags.AA); rcode = addAnswer(response, cname.getTarget(), type, dclass, iterations + 1); } else if (sr.isDNAME()) { RRset rrset = new RRset(); DNAMERecord dname = sr.getDNAME(); rrset.addRR(dname); addRRset(name, response, rrset, Section.ANSWER, false); Name newname = name.fromDNAME(dname); if (newname == null) return Rcode.SERVFAIL; try { rrset = new RRset(); rrset.addRR(new CNAMERecord(name, dclass, 0, newname)); addRRset(name, response, rrset, Section.ANSWER, false); } catch (IOException e) {} if (zone != null && iterations == 0) response.getHeader().setFlag(Flags.AA); rcode = addAnswer(response, newname, type, dclass, iterations + 1); } else if (sr.isSuccessful()) { RRset [] rrsets = sr.answers(); for (int i = 0; i < rrsets.length; i++) addRRset(name, response, rrsets[i], Section.ANSWER, sigonly); if (zone != null) { addNS(response, zone); if (iterations == 0) response.getHeader().setFlag(Flags.AA); } else addCacheNS(response, getCache(dclass), name); } return rcode; } TSIG findTSIG(Name name) { byte [] key = (byte []) TSIGs.get(name); if (key != null) return new TSIG(name, key); else return null; } Message doAXFR(Name name, Message query, Socket s) { Zone zone = (Zone) znames.get(name); if (zone == null) { /* System.out.println("no zone " + name + " to AXFR");*/ return errorMessage(query, Rcode.REFUSED); } Enumeration e = zone.AXFR(); try { DataOutputStream dataOut; dataOut = new DataOutputStream(s.getOutputStream()); while (e.hasMoreElements()) { RRset rrset = (RRset) e.nextElement(); Message response = new Message(); addRRset(rrset.getName(), response, rrset, Section.ANSWER, false); byte [] out = response.toWire(); dataOut.writeShort(out.length); dataOut.write(out); } } catch (IOException ex) { System.out.println("AXFR failed"); } try { s.close(); } catch (IOException ex) { } return null; } /* * Note: a null return value means that the caller doesn't need to do * anything. Currently this only happens if this is an AXFR request over * TCP. */ Message generateReply(Message query, byte [] in, Socket s) { boolean badversion; int maxLength; boolean sigonly; SetResponse sr; if (query.getHeader().getOpcode() != Opcode.QUERY) return errorMessage(query, Rcode.NOTIMPL); Record queryRecord = query.getQuestion(); TSIGRecord queryTSIG = query.getTSIG(); TSIG tsig = null; if (queryTSIG != null) { tsig = findTSIG(queryTSIG.getName()); if (!tsig.verify(query, in, null)) return formerrMessage(in); } OPTRecord queryOPT = query.getOPT(); if (queryOPT != null && queryOPT.getVersion() > 0) badversion = true; if (s != null) maxLength = 65535; else if (queryOPT != null) maxLength = queryOPT.getPayloadSize(); else maxLength = 512; Message response = new Message(); response.getHeader().setID(query.getHeader().getID()); response.getHeader().setFlag(Flags.QR); if (query.getHeader().getFlag(Flags.RD)); response.getHeader().setFlag(Flags.RD); response.addRecord(queryRecord, Section.QUESTION); Name name = queryRecord.getName(); short type = queryRecord.getType(); short dclass = queryRecord.getDClass(); if (type == Type.AXFR && s != null) return doAXFR(name, query, s); if (!Type.isRR(type) && type != Type.ANY) return errorMessage(query, Rcode.NOTIMPL); byte rcode = addAnswer(response, name, type, dclass, 0); if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) return errorMessage(query, rcode); addAdditional(response); if (queryTSIG != null) { try { if (tsig != null) tsig.apply(response, queryTSIG); } catch (IOException e) { } } try { response.freeze(); byte [] out = response.toWire(); if (out.length > maxLength) { response.thaw(); truncate(response, out.length, maxLength); if (tsig != null) tsig.apply(response, queryTSIG); } } catch (IOException e) { } return response; } public int truncateSection(Message in, int maxLength, int length, int section) { int removed = 0; Record [] records = in.getSectionArray(section); for (int i = records.length - 1; i >= 0; i Record r = records[i]; removed += r.getWireLength(); length -= r.getWireLength(); in.removeRecord(r, section); if (length > maxLength) continue; else { for (int j = i - 1; j >= 0; j Record r2 = records[j]; if (!r.getName().equals(r2.getName()) || r.getType() != r2.getType() || r.getDClass() != r2.getDClass()) break; removed += r2.getWireLength(); length -= r2.getWireLength(); in.removeRecord(r2, section); } return removed; } } return removed; } public void truncate(Message in, int length, int maxLength) { TSIGRecord tsig = in.getTSIG(); if (tsig != null) maxLength -= tsig.getWireLength(); length -= truncateSection(in, maxLength, length, Section.ADDITIONAL); if (length < maxLength) return; in.getHeader().setFlag(Flags.TC); if (tsig != null) { in.removeAllRecords(Section.ANSWER); in.removeAllRecords(Section.AUTHORITY); return; } length -= truncateSection(in, maxLength, length, Section.AUTHORITY); if (length < maxLength) return; length -= truncateSection(in, maxLength, length, Section.ANSWER); } public Message formerrMessage(byte [] in) { Header header; try { header = new Header(new DataByteInputStream(in)); } catch (IOException e) { header = new Header(0); } Message response = new Message(); response.setHeader(header); for (int i = 0; i < 4; i++) response.removeAllRecords(i); header.setRcode(Rcode.FORMERR); return response; } public Message errorMessage(Message query, short rcode) { Header header = query.getHeader(); Message response = new Message(); response.setHeader(header); for (int i = 0; i < 4; i++) response.removeAllRecords(i); if (rcode == Rcode.SERVFAIL) response.addRecord(query.getQuestion(), Section.QUESTION); header.setRcode(rcode); return response; } public void serveTCP(short port) { try { ServerSocket sock = new ServerSocket(port); while (true) { Socket s = sock.accept(); int inLength; DataInputStream dataIn; DataOutputStream dataOut; byte [] in; try { InputStream is = s.getInputStream(); dataIn = new DataInputStream(is); inLength = dataIn.readUnsignedShort(); in = new byte[inLength]; dataIn.readFully(in); } catch (InterruptedIOException e) { s.close(); continue; } Message query, response; try { query = new Message(in); response = generateReply(query, in, s); if (response == null) continue; } catch (IOException e) { response = formerrMessage(in); } byte [] out = response.toWire(); dataOut = new DataOutputStream(s.getOutputStream()); dataOut.writeShort(out.length); dataOut.write(out); s.close(); } } catch (IOException e) { System.out.println("serveTCP: " + e); } } public void serveUDP(short port) { try { DatagramSocket sock = new DatagramSocket(port); while (true) { short udpLength = 512; byte [] in = new byte[udpLength]; DatagramPacket dp = new DatagramPacket(in, in.length); try { sock.receive(dp); } catch (InterruptedIOException e) { continue; } Message query, response; try { query = new Message(in); response = generateReply(query, in, null); if (response == null) continue; } catch (IOException e) { response = formerrMessage(in); } byte [] out = response.toWire(); dp = new DatagramPacket(out, out.length, dp.getAddress(), dp.getPort()); sock.send(dp); } } catch (IOException e) { System.out.println("serveUDP: " + e); } } public void addTCP(final short port) { Thread t; t = new Thread(new Runnable() {public void run() {serveTCP(port);}}); t.start(); } public void addUDP(final short port) { Thread t; t = new Thread(new Runnable() {public void run() {serveUDP(port);}}); t.start(); } public static void main(String [] args) { if (args.length > 1) { System.out.println("usage: jnamed [conf]"); System.exit(0); } jnamed s; try { String conf; if (args.length == 1) conf = args[0]; else conf = "jnamed.conf"; s = new jnamed(conf); } catch (IOException e) { System.out.println(e); } } }
package sys.malta; import sys.util.Logger; import sys.util.Symbols; /** * PIIX4 style 82C59 interrupt controller * TODO this really needs to intercept calls to addException... * device.addexception() -> ? */ public class PIC implements Device { /** Address 0: Init Command Word 1, Operational Command Word 2 and 3 */ public static final int M_CMD = 0; /** Address 1: Init Command Word 2, 3 and 4, Operational Command Word 1 */ public static final int M_DATA = 1; /** init icw1 */ private static final int CMD_ICW1 = 0x10; /** init ocw3 or ocw2 */ private static final int CMD_OCW3 = 0x8; /** icw4 needed */ private static final int ICW1_ICW4NEEDED = 0x1; /** single/cascade */ private static final int ICW1_SINGLE = 0x2; /** address interval 4/8 */ private static final int ICW1_ADI4 = 0x4; /** level triggered mode */ private static final int ICW1_LTM = 0x8; /** a5-a7 of interrupt vector address (MCS mode) */ private static final int ICW1_IVA5 = 0xe0; /** 8086/MCS mode */ private static final int ICW4_8086MODE = 0x1; /** auto eoi/normal eoi */ private static final int ICW4_AUTOEOI = 0x2; /** buffered mode */ private static final int ICW4_BUFFER = 0xc; /** fully nested mode */ private static final int ICW4_NESTED = 0x10; public static void main (String[] args) { // write command words, init words // test interrupt masking/mapping/cascading... PIC dev = new PIC(0, true); //dev.systemWrite(); } private final Logger log; private final int baseAddr; private final boolean master; /** * Address 0 */ private int icw1; /** * Address 1 * 0-7: a8-a15 of interrupt vector address (MCS mode) * 3-7: t3-t7 of interrupt vector address (8086 mode) */ private int icw2; /** * Address 1 * 0-7: has slave (master) * 0-3: slave id (slave) */ private int icw3; /** * Address 1 */ private int icw4; /** * the interrupt mask register * Address 1 * 0-7: interrupt mask set */ private int ocw1; /** * Address 0 * 0-3: interrupt request level * 5-7: end of interrupt mode */ private int ocw2; /** * Address 0 * 0,1: read register cmd * 2: poll command * 5,6: special mask mode */ private int ocw3; /** data mode: 0 = imr, 2 = icw2, 3 = icw3, 4 = icw4 */ private int init; public PIC(final int baseAddr, boolean master) { this.baseAddr = baseAddr; this.master = master; this.log = new Logger("PIC" + (master ? 1 : 2)); } @Override public void init (final Symbols sym) { sym.init(getClass(), "M_", "M_PIC" + (master ? 1 : 2), baseAddr, 1); } @Override public boolean isMapped (final int addr) { final int offset = addr - baseAddr; return offset >= 0 && offset < 2; } @Override public int systemRead (final int addr, final int size) { final int offset = addr - baseAddr; switch (offset) { case M_CMD: log.println("read command"); throw new RuntimeException(); case M_DATA: //log.println("read ocw1 %x", ocw1); // read the imr return ocw1; default: throw new RuntimeException(); } } @Override public void systemWrite (final int addr, final int size, final int valueInt) { final int offset = addr - baseAddr; final int value = valueInt & 0xff; switch (offset) { case M_CMD: writeCommand(value); return; case M_DATA: writeData(value); return; default: throw new RuntimeException(); } } /** write address 0 */ private void writeCommand (final int value) { //log.println("write command %x", value); if ((value & CMD_ICW1) != 0) { log.println("write ICW1 %x (was %x)", value, icw1); icw1 = value; // clear imr ocw1 = 0; // IR7 input assigned priority 7? // XXX ocw2 = 0x7? // slave mode address set to 7 // XXX icw3 = 0x7? // special mask mode cleared ocw3 &= ~0x60; // status read set to IRR? // IC4 cleared if 0 if ((value & 0x1) != 0) { icw4 = 0; } // expect ICW2... init = 2; return; } else if ((value & CMD_OCW3) == 0) { if (value != 0x60) { log.println("write OCW2 (IRL/EOI) %x (was %x)", value, ocw2); //throw new RuntimeException("worrying OCW2 " + Integer.toHexString(value)); } ocw2 = value; } else { log.println("write OCW3 (command) %x (was %x)", value, ocw3); ocw3 = value; } } private void writeData (final int value) { //log.println("write data %x", value); switch (init) { case 0: if (value < 0xe0) { log.println("write OCW1 (IMR) %x (was %x)", value, ocw1); //throw new RuntimeException("worrying OCW1 " + Integer.toHexString(value)); } // interrupt mask ocw1 = value; return; case 2: log.println("write ICW2 (IVA) %x (was %x)", value, icw2); icw2 = value; init = !isSingle() ? 3 : isIcw4Needed() ? 4 : 0; return; case 3: log.println("write ICW3 (HS/SID) %x (was %x)", value, icw3); icw3 = value; init = isIcw4Needed() ? 4 : 0; return; case 4: log.println("write ICW4 (mode) %x (was %x)", value, icw4); icw4 = value; init = 0; return; default: throw new RuntimeException("unknown init " + init); } } private boolean isIcw4Needed () { return (icw1 & ICW1_ICW4NEEDED) != 0; } private boolean isSingle () { return (icw1 & ICW1_SINGLE) != 0; } }
package tests; import modele.*; import java.awt.Point; import static org.junit.Assert.*; import org.junit.Test; /** * Classe de test pour le Bec * * @author Groupe N5 */ public class BecTest { /** * Verifie la reponse de GetPointeX */ @Test public void testGetPointeX() { Bec testBec = new Bec(new Point(10,10),new Point(10,15)); assertEquals(10.00, testBec.getPointe().getX(),00.00); } /** * Verifie la reponse de GetPointY */ @Test public void testGetPointeY() { Bec testBec = new Bec(new Point(10,10),new Point(10,15)); assertEquals(15.00, testBec.getPointe().getY(),00.00); } /** * Verifie si SetPointe fonctionne */ @Test public void testSetPointe() { Bec testBec = new Bec(new Point(10,10),new Point(10,15)); testBec.setPointe(new Point(15,20)); assertEquals(15.00, testBec.getPointe().getX(),00.00); assertEquals(20.00, testBec.getPointe().getY(),00.00); } }
package tracer; import ease.Easing; import ease.Easing.Linear; import paths.IPath; /** * A Point that moves along a Path at some rate of speed. * * @author James Morrow [jamesmorrowdesign.com] * */ public class Tracer { protected Point pt; //The Tracer's location in 2D space, accessible via the location() method protected float u; //The Tracer's location in 1D space, relative to the Tracer's easing curve. protected float du; //The Tracer's speed in 1D space, relative to the Tracer's easing curve. protected IPath path; //The Path to which the Tracer is attached protected Easing easing; //The easing curve determining how the Tracer moves in time. protected boolean upToDate = false; //Flag that indicates whether or not the location stored in pt is up to date. public Tracer(IPath path, float startx, float dx) { this(path, startx, dx, new Linear()); } public Tracer(IPath path, float startu, float du, Easing easing) { this.u = startu % 1; this.du = du; this.path = path; this.pt = new Point(0, 0); this.easing = easing; location(); } public void step() { u = (u + du) % 1; upToDate = false; } public Point location() { if (!upToDate) { float y = easing.val(u); path.trace(pt, y); upToDate = true; } return pt; } public float getU() { return u; } public void setU(float u) { this.u = u; upToDate = false; } public float getDu() { return du; } public void setDu(float du) { this.du = du; } public IPath getPath() { return path; } public void setPath(IPath path) { this.path = path; upToDate = false; } public Easing getEasing() { return easing; } public void setEasing(Easing easing) { this.easing = easing; upToDate = false; } }
package ui; import java.util.Observable; import java.util.Observer; import model.Turtle; import javafx.scene.canvas.Canvas; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.paint.Color; public class TurtleView implements Observer { private ImageView myImageView; private Canvas myCanvas; private Color myColor; private double myHeading; // in degrees, 0 is north private double myWidthOffset; private double myHeightOffset; public TurtleView(Image imageIn, Canvas canvasIn, Color colorIn, double xIn, double yIn) { myImageView = new ImageView(); myCanvas = canvasIn; myImageView.setImage(imageIn); myImageView.setX(xIn); myImageView.setY(yIn); myColor = colorIn; myWidthOffset = myCanvas.getWidth()/2; myHeightOffset = myCanvas.getHeight()/2; myHeading = 50; myImageView.setPreserveRatio(true); myImageView.setSmooth(true); } public ImageView getImageView() { return myImageView; } public void draw() { // myCanvas.getGraphicsContext2D().rotate(myHeading); myCanvas.getGraphicsContext2D().drawImage(myImageView.getImage(), getCenterX(), getCenterY(), myCanvas.getHeight() / 10, myCanvas.getWidth() / 10); } private void drawLine(double x1, double y1, double x2, double y2) { myCanvas.getGraphicsContext2D().setFill(myColor); myCanvas.getGraphicsContext2D().setLineWidth(5); myCanvas.getGraphicsContext2D().strokeLine(x1, y1, x2, y2); } @Override public void update(Observable o, Object arg) { Turtle tModel = (Turtle) o; double newX = tModel.getX(); double newY = tModel.getY(); double newHeading = tModel.getHeading(); if (myHeading != newHeading) { myHeading = newHeading; myCanvas.getGraphicsContext2D().save(); myCanvas.getGraphicsContext2D().rotate(myHeading); } myHeading = newHeading; if (newX != getCenterX() || newY != getCenterY()) { drawLine(getCenterX(), getCenterY(), newX, newY); // draw(); myImageView.setX(newX); myImageView.setY(newY); } } private double getCenterX() { return (myImageView.getX() - (myCanvas.getWidth() / 20)) - myWidthOffset; } private double getCenterY() { return (myImageView.getY() - (myCanvas.getHeight() / 20)) - myHeightOffset; } }
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Action */ @WebServlet("/Action") public class Action extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Action() { super(); } /** * @see HttpServlet#servce(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/index.jsp").forward(request, response); System.out.println("Content Length: " + request.getContentLength()); System.out.println("Content Type: " + request.getContentType()); System.out.println("Content Path: " + request.getContextPath()); System.out.println("Local Address: " + request.getLocalAddr()); System.out.println("Local Name: " + request.getLocalName()); System.out.println("Local Port: " + request.getLocalPort()); System.out.println("Locale: " + request.getLocale()); System.out.println("Method: " + request.getMethod()); System.out.println("Protocol: " + request.getProtocol()); System.out.println("Parameter Map: " + request.getParameterMap()); System.out.println("Remote Address: " + request.getRemoteAddr()); System.out.println("Remote Host: " + request.getRemoteHost()); System.out.println("Remote Port: " + request.getRemotePort()); System.out.println("Remote User: " + request.getRemoteUser()); System.out.println("Session Id: " + request.getRequestedSessionId()); System.out.println("URI: " + request.getRequestURI()); System.out.println("URL: " + request.getRequestURL()); System.out.println("Scheme: " + request.getScheme()); System.out.println("Server Name: " + request.getServerName()); System.out.println("Server Port: " + request.getServerPort()); System.out.println("Servlet Path: " + request.getServletPath()); System.out.println("Servlet Context: " + request.getServletContext()); System.out.println("Session: " + request.getSession()); System.out.println("User Principal: " + request.getUserPrincipal()); } }
package org.mockserver.validator.jsonschema; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.github.fge.jsonschema.core.report.ProcessingMessage; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchemaFactory; import com.github.fge.jsonschema.main.JsonValidator; import com.google.common.base.Joiner; import org.mockserver.file.FileReader; import org.mockserver.log.model.LogEntry; import org.mockserver.logging.MockServerLogger; import org.mockserver.model.ObjectWithReflectiveEqualsHashCodeToString; import org.mockserver.serialization.ObjectMapperFactory; import org.mockserver.validator.Validator; import org.slf4j.event.Level; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.mockserver.character.Character.NEW_LINE; /** * @author jamesdbloom */ public class JsonSchemaValidator extends ObjectWithReflectiveEqualsHashCodeToString implements Validator<String> { private static final Map<String, String> schemaCache = new ConcurrentHashMap<>(); private final MockServerLogger mockServerLogger; private final String schema; private final JsonValidator validator = JsonSchemaFactory.byDefault().getValidator(); private ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper(); public JsonSchemaValidator(MockServerLogger mockServerLogger, String schema) { this.mockServerLogger = mockServerLogger; if (schema.trim().endsWith(".json")) { this.schema = FileReader.readFileFromClassPathOrPath(schema); } else if (schema.trim().endsWith("}")) { this.schema = schema; } else { throw new IllegalArgumentException("Schema must either be a path reference to a *.json file or a json string"); } } public JsonSchemaValidator(MockServerLogger mockServerLogger, String routePath, String mainSchemeFile, String... referenceFiles) { this.mockServerLogger = mockServerLogger; if (!schemaCache.containsKey(mainSchemeFile)) { schemaCache.put(mainSchemeFile, addReferencesIntoSchema(routePath, mainSchemeFile, referenceFiles)); } this.schema = schemaCache.get(mainSchemeFile); } public String getSchema() { return schema; } private String addReferencesIntoSchema(String routePath, String mainSchemeFile, String... referenceFiles) { String combinedSchema = ""; try { ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper(); JsonNode jsonSchema = objectMapper.readTree(FileReader.readFileFromClassPathOrPath(routePath + mainSchemeFile + ".json")); JsonNode definitions = jsonSchema.get("definitions"); if (definitions instanceof ObjectNode) { for (String definitionName : referenceFiles) { ((ObjectNode) definitions).set( definitionName, objectMapper.readTree(FileReader.readFileFromClassPathOrPath(routePath + definitionName + ".json")) ); } } combinedSchema = ObjectMapperFactory .createObjectMapper() .writerWithDefaultPrettyPrinter() .writeValueAsString(jsonSchema); } catch (Exception e) { mockServerLogger.logEvent( new LogEntry() .setType(LogEntry.LogMessageType.EXCEPTION) .setLogLevel(Level.ERROR) .setMessageFormat("Exception loading JSON Schema for Exceptions") .setThrowable(e) ); } return combinedSchema; } @Override public String isValid(String json) { String validationResult = ""; if (isNotBlank(json)) { try { ProcessingReport processingReport = validator .validate( objectMapper.readTree(schema), objectMapper.readTree(json), true ); if (!processingReport.isSuccess()) { validationResult = formatProcessingReport(processingReport); } } catch (Exception e) { mockServerLogger.logEvent( new LogEntry() .setType(LogEntry.LogMessageType.EXCEPTION) .setLogLevel(Level.ERROR) .setMessageFormat("Exception validating JSON") .setThrowable(e) ); return e.getClass().getSimpleName() + " - " + e.getMessage(); } } return validationResult; } private String formatProcessingReport(ProcessingReport validate) { List<String> validationErrors = new ArrayList<>(); for (ProcessingMessage processingMessage : validate) { String fieldPointer = ""; if (processingMessage.asJson().get("instance") != null && processingMessage.asJson().get("instance").get("pointer") != null) { fieldPointer = String.valueOf(processingMessage.asJson().get("instance").get("pointer")).replaceAll("\"", ""); } String schemaPointer = ""; if (processingMessage.asJson().get("schema") != null && processingMessage.asJson().get("schema").get("pointer") != null) { schemaPointer = String.valueOf(processingMessage.asJson().get("schema").get("pointer")); } if (fieldPointer.endsWith("/headers")) { validationErrors.add("for field \"" + fieldPointer + "\" only one of the following example formats is allowed: " + NEW_LINE + NEW_LINE + " \"" + fieldPointer + "\" : {" + NEW_LINE + " \"exampleHeaderName\" : [ \"exampleHeaderValue\" ]" + NEW_LINE + " \"exampleMultiValuedHeaderName\" : [ \"exampleHeaderValueOne\", \"exampleHeaderValueTwo\" ]" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " or:" + NEW_LINE + NEW_LINE + " \"" + fieldPointer + "\" : [" + NEW_LINE + " {" + NEW_LINE + " \"name\" : \"exampleHeaderName\"," + NEW_LINE + " \"values\" : [ \"exampleHeaderValue\" ]" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"name\" : \"exampleMultiValuedHeaderName\"," + NEW_LINE + " \"values\" : [ \"exampleHeaderValueOne\", \"exampleHeaderValueTwo\" ]" + NEW_LINE + " }" + NEW_LINE + " ]"); } else if (fieldPointer.endsWith("/queryStringParameters")) { validationErrors.add("for field \"" + fieldPointer + "\" only one of the following example formats is allowed: " + NEW_LINE + NEW_LINE + " \"" + fieldPointer + "\" : {" + NEW_LINE + " \"exampleParameterName\" : [ \"exampleParameterValue\" ]" + NEW_LINE + " \"exampleMultiValuedParameterName\" : [ \"exampleParameterValueOne\", \"exampleParameterValueTwo\" ]" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " or:" + NEW_LINE + NEW_LINE + " \"" + fieldPointer + "\" : [" + NEW_LINE + " {" + NEW_LINE + " \"name\" : \"exampleParameterName\"," + NEW_LINE + " \"values\" : [ \"exampleParameterValue\" ]" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"name\" : \"exampleMultiValuedParameterName\"," + NEW_LINE + " \"values\" : [ \"exampleParameterValueOne\", \"exampleParameterValueTwo\" ]" + NEW_LINE + " }" + NEW_LINE + " ]"); } else if (fieldPointer.endsWith("/cookies")) { validationErrors.add("for field \"" + fieldPointer + "\" only one of the following example formats is allowed: " + NEW_LINE + NEW_LINE + " \"" + fieldPointer + "\" : {" + NEW_LINE + " \"exampleCookieNameOne\" : \"exampleCookieValueOne\"" + NEW_LINE + " \"exampleCookieNameTwo\" : \"exampleCookieValueTwo\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " or:" + NEW_LINE + NEW_LINE + " \"" + fieldPointer + "\" : [" + NEW_LINE + " {" + NEW_LINE + " \"name\" : \"exampleCookieNameOne\"," + NEW_LINE + " \"values\" : \"exampleCookieValueOne\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"name\" : \"exampleCookieNameTwo\"," + NEW_LINE + " \"values\" : \"exampleCookieValueTwo\"" + NEW_LINE + " }" + NEW_LINE + " ]"); } else if (fieldPointer.endsWith("/body") && !schemaPointer.contains("bodyWithContentType")) { validationErrors.add("for field \"" + fieldPointer + "\" a plain string, JSON object or one of the following example bodies must be specified " + NEW_LINE + " {" + NEW_LINE + " \"not\": false," + NEW_LINE + " \"type\": \"BINARY\"," + NEW_LINE + " \"base64Bytes\": \"\"," + NEW_LINE + " \"contentType\": \"\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"not\": false," + NEW_LINE + " \"type\": \"JSON\"," + NEW_LINE + " \"json\": \"\"," + NEW_LINE + " \"contentType\": \"\"," + NEW_LINE + " \"matchType\": \"ONLY_MATCHING_FIELDS\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"not\": false," + NEW_LINE + " \"type\": \"JSON_SCHEMA\"," + NEW_LINE + " \"jsonSchema\": \"\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"not\": false," + NEW_LINE + " \"type\": \"JSON_PATH\"," + NEW_LINE + " \"jsonPath\": \"\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"not\": false," + NEW_LINE + " \"type\": \"PARAMETERS\"," + NEW_LINE + " \"parameters\": {\"name\": \"value\"}" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"not\": false," + NEW_LINE + " \"type\": \"REGEX\"," + NEW_LINE + " \"regex\": \"\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"not\": false," + NEW_LINE + " \"type\": \"STRING\"," + NEW_LINE + " \"string\": \"\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"not\": false," + NEW_LINE + " \"type\": \"XML\"," + NEW_LINE + " \"xml\": \"\"," + NEW_LINE + " \"contentType\": \"\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"not\": false," + NEW_LINE + " \"type\": \"XML_SCHEMA\"," + NEW_LINE + " \"xmlSchema\": \"\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"not\": false," + NEW_LINE + " \"type\": \"XPATH\"," + NEW_LINE + " \"xpath\": \"\"" + NEW_LINE + " }"); } else if (fieldPointer.endsWith("/body") && schemaPointer.contains("bodyWithContentType")) { validationErrors.add("for field \"" + fieldPointer + "\" a plain string, JSON object or one of the following example bodies must be specified " + NEW_LINE + " {" + NEW_LINE + " \"type\": \"BINARY\"," + NEW_LINE + " \"base64Bytes\": \"\"," + NEW_LINE + " \"contentType\": \"\"" + NEW_LINE + " }, " + NEW_LINE + " {" + NEW_LINE + " \"type\": \"JSON\"," + NEW_LINE + " \"json\": \"\"," + NEW_LINE + " \"contentType\": \"\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"type\": \"PARAMETERS\"," + NEW_LINE + " \"parameters\": {\"name\": \"value\"}" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"type\": \"STRING\"," + NEW_LINE + " \"string\": \"\"" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"type\": \"XML\"," + NEW_LINE + " \"xml\": \"\"," + NEW_LINE + " \"contentType\": \"\"" + NEW_LINE + " }"); } else if (String.valueOf(processingMessage.asJson().get("keyword")).equals("\"oneOf\"")) { StringBuilder oneOfErrorMessage = new StringBuilder("oneOf of the following must be specified "); if (fieldPointer.isEmpty()) { oneOfErrorMessage.append(Arrays.asList( "\"httpResponse\"", "\"httpResponseTemplate\"", "\"httpResponseObjectCallback\"", "\"httpResponseClassCallback\"", "\"httpForward\"", "\"httpForwardTemplate\"", "\"httpForwardObjectCallback\"", "\"httpForwardClassCallback\"", "\"httpOverrideForwardedRequest\"", "\"httpError\"" )); } else { for (JsonNode jsonNode : processingMessage.asJson().get("reports")) { if (jsonNode.get(0) != null && jsonNode.get(0).get("required") != null && jsonNode.get(0).get("required").get(0) != null) { oneOfErrorMessage.append(jsonNode.get(0).get("required").get(0)).append(" "); } } } oneOfErrorMessage.append(" but ").append(processingMessage.asJson().get("matched")).append(" found"); validationErrors.add(oneOfErrorMessage.toString() + (fieldPointer.isEmpty() ? "" : " for field \"" + fieldPointer + "\"")); } else if (fieldPointer.endsWith("/times") && processingMessage.toString().contains("has properties which are not allowed by the schema") && String.valueOf(processingMessage.asJson().get("schema")).contains("verificationTimes")) { validationErrors.add(processingMessage.getMessage() + " for field \"" + fieldPointer + "\", allowed fields are [\"atLeast\", \"atMost\"]"); } else { validationErrors.add(processingMessage.getMessage() + (fieldPointer.isEmpty() ? "" : " for field \"" + fieldPointer + "\"")); } } return validationErrors.size() + " error" + (validationErrors.size() > 1 ? "s" : "") + ":" + NEW_LINE + " - " + Joiner.on(NEW_LINE + " - ").join(validationErrors); } }
package com.intellij.ide.util.treeView; import com.intellij.ide.IdeBundle; import com.intellij.ide.UiActivity; import com.intellij.ide.UiActivityMonitor; import com.intellij.ide.util.treeView.TreeRunnable.TreeConsumer; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.*; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.registry.RegistryValue; import com.intellij.ui.LoadingNode; import com.intellij.ui.treeStructure.AlwaysExpandedTree; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.*; import com.intellij.util.concurrency.LockToken; import com.intellij.util.concurrency.QueueProcessor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.util.ui.update.Activatable; import com.intellij.util.ui.update.UiNotifyConnector; import consulo.annotations.RequiredReadAction; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.concurrency.AsyncPromise; import org.jetbrains.concurrency.Promise; import org.jetbrains.concurrency.Promises; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.util.List; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; public class AbstractTreeUi { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.util.treeView.AbstractTreeBuilder"); protected JTree myTree;// protected for TestNG private DefaultTreeModel myTreeModel; private AbstractTreeStructure myTreeStructure; private AbstractTreeUpdater myUpdater; private Comparator<? super NodeDescriptor> myNodeDescriptorComparator; private final Comparator<TreeNode> myNodeComparator = new Comparator<TreeNode>() { @Override public int compare(TreeNode n1, TreeNode n2) { if (isLoadingNode(n1) && isLoadingNode(n2)) return 0; if (isLoadingNode(n1)) return -1; if (isLoadingNode(n2)) return 1; NodeDescriptor nodeDescriptor1 = getDescriptorFrom(n1); NodeDescriptor nodeDescriptor2 = getDescriptorFrom(n2); if (nodeDescriptor1 == null && nodeDescriptor2 == null) return 0; if (nodeDescriptor1 == null) return -1; if (nodeDescriptor2 == null) return 1; return myNodeDescriptorComparator != null ? myNodeDescriptorComparator.compare(nodeDescriptor1, nodeDescriptor2) : nodeDescriptor1.getIndex() - nodeDescriptor2.getIndex(); } }; long myOwnComparatorStamp; private long myLastComparatorStamp; private DefaultMutableTreeNode myRootNode; private final Map<Object, Object> myElementToNodeMap = new HashMap<>(); private final Set<DefaultMutableTreeNode> myUnbuiltNodes = new HashSet<>(); private TreeExpansionListener myExpansionListener; private MySelectionListener mySelectionListener; private final QueueProcessor<Runnable> myWorker = new QueueProcessor<>(runnable -> { runnable.run(); TimeoutUtil.sleep(1); }); private final Set<Runnable> myActiveWorkerTasks = new HashSet<>(); private ProgressIndicator myProgress; private AbstractTreeNode<Object> TREE_NODE_WRAPPER; private boolean myRootNodeWasQueuedToInitialize; private boolean myRootNodeInitialized; private final Map<Object, List<NodeAction>> myNodeActions = new HashMap<>(); private boolean myUpdateFromRootRequested; private boolean myWasEverShown; private boolean myUpdateIfInactive; private final Map<Object, UpdateInfo> myLoadedInBackground = new HashMap<>(); private final Map<Object, List<NodeAction>> myNodeChildrenActions = new HashMap<>(); private long myClearOnHideDelay = -1; private volatile long ourUi2Countdown; private final Set<Runnable> myDeferredSelections = new HashSet<>(); private final Set<Runnable> myDeferredExpansions = new HashSet<>(); private boolean myCanProcessDeferredSelections; private UpdaterTreeState myUpdaterState; private AbstractTreeBuilder myBuilder; private final Set<DefaultMutableTreeNode> myUpdatingChildren = new THashSet<>(); private boolean myCanYield; private final List<TreeUpdatePass> myYieldingPasses = new ArrayList<>(); private boolean myYieldingNow; private final Set<DefaultMutableTreeNode> myPendingNodeActions = new HashSet<>(); private final Set<Runnable> myYieldingDoneRunnables = new HashSet<>(); private final Alarm myBusyAlarm = new Alarm(); private final Runnable myWaiterForReady = new TreeRunnable("AbstractTreeUi.myWaiterForReady") { @Override public void perform() { maybeSetBusyAndScheduleWaiterForReady(false, null); } }; private final RegistryValue myYieldingUpdate = Registry.get("ide.tree.yieldingUiUpdate"); private final RegistryValue myShowBusyIndicator = Registry.get("ide.tree.showBusyIndicator"); private final RegistryValue myWaitForReadyTime = Registry.get("ide.tree.waitForReadyTimeout"); private boolean myWasEverIndexNotReady; private boolean myShowing; private final FocusAdapter myFocusListener = new FocusAdapter() { @Override public void focusGained(FocusEvent e) { maybeReady(); } }; private final Set<DefaultMutableTreeNode> myNotForSmartExpand = new HashSet<>(); private TreePath myRequestedExpand; private TreePath mySilentExpand; private TreePath mySilentSelect; private final ActionCallback myInitialized = new ActionCallback(); private final BusyObject.Impl myBusyObject = new BusyObject.Impl() { @Override public boolean isReady() { return AbstractTreeUi.this.isReady(true); } @Override protected void onReadyWasSent() { removeActivity(); } }; private boolean myPassThroughMode; private final Set<Object> myAutoExpandRoots = new HashSet<>(); private final RegistryValue myAutoExpandDepth = Registry.get("ide.tree.autoExpandMaxDepth"); private final Set<DefaultMutableTreeNode> myWillBeExpanded = new HashSet<>(); private SimpleTimerTask myCleanupTask; private final AtomicBoolean myCancelRequest = new AtomicBoolean(); private final ReentrantLock myStateLock = new ReentrantLock(); private final AtomicBoolean myResettingToReadyNow = new AtomicBoolean(); private final Map<Progressive, ProgressIndicator> myBatchIndicators = new HashMap<>(); private final Map<Progressive, ActionCallback> myBatchCallbacks = new HashMap<>(); private final Map<DefaultMutableTreeNode, DefaultMutableTreeNode> myCancelledBuild = new WeakHashMap<>(); private boolean mySelectionIsAdjusted; private boolean myReleaseRequested; private boolean mySelectionIsBeingAdjusted; private final Set<Object> myRevalidatedObjects = new HashSet<>(); private final Set<Runnable> myUserRunnables = new HashSet<>(); private UiActivityMonitor myActivityMonitor; @NonNls private UiActivity myActivityId; @Override public String toString() { return "AbstractTreeUi: builder = " + myBuilder; } protected void init(@Nonnull AbstractTreeBuilder builder, @Nonnull JTree tree, @Nonnull DefaultTreeModel treeModel, AbstractTreeStructure treeStructure, @Nullable Comparator<? super NodeDescriptor> comparator, boolean updateIfInactive) { myBuilder = builder; myTree = tree; myTreeModel = treeModel; myActivityMonitor = UiActivityMonitor.getInstance(); myActivityId = new UiActivity.AsyncBgOperation("TreeUi " + this); addModelListenerToDiagnoseAccessOutsideEdt(); TREE_NODE_WRAPPER = AbstractTreeBuilder.createSearchingTreeNodeWrapper(); myTree.setModel(myTreeModel); setRootNode((DefaultMutableTreeNode)treeModel.getRoot()); myTreeStructure = treeStructure; myNodeDescriptorComparator = comparator; myUpdateIfInactive = updateIfInactive; UIUtil.invokeLaterIfNeeded(new TreeRunnable("AbstractTreeUi.init") { @Override public void perform() { if (!wasRootNodeInitialized()) { if (myRootNode.getChildCount() == 0) { insertLoadingNode(myRootNode, true); } } } }); myExpansionListener = new MyExpansionListener(); myTree.addTreeExpansionListener(myExpansionListener); mySelectionListener = new MySelectionListener(); myTree.addTreeSelectionListener(mySelectionListener); setUpdater(getBuilder().createUpdater()); myProgress = getBuilder().createProgressIndicator(); Disposer.register(getBuilder(), getUpdater()); if (myProgress != null) { Disposer.register(getBuilder(), () -> myProgress.cancel()); } final UiNotifyConnector uiNotify = new UiNotifyConnector(tree, new Activatable() { @Override public void showNotify() { myShowing = true; myWasEverShown = true; if (canInitiateNewActivity()) { activate(true); } } @Override public void hideNotify() { myShowing = false; if (canInitiateNewActivity()) { deactivate(); } } }); Disposer.register(getBuilder(), uiNotify); myTree.addFocusListener(myFocusListener); } private boolean isNodeActionsPending() { return !myNodeActions.isEmpty() || !myNodeChildrenActions.isEmpty(); } private void clearNodeActions() { myNodeActions.clear(); myNodeChildrenActions.clear(); } private void maybeSetBusyAndScheduleWaiterForReady(boolean forcedBusy, @Nullable Object element) { if (!myShowBusyIndicator.asBoolean()) return; boolean canUpdateBusyState = false; if (forcedBusy) { if (canYield() || isToBuildChildrenInBackground(element)) { canUpdateBusyState = true; } } else { canUpdateBusyState = true; } if (!canUpdateBusyState) return; if (myTree instanceof Tree) { final Tree tree = (Tree)myTree; final boolean isBusy = !isReady(true) || forcedBusy; if (isBusy && tree.isShowing()) { tree.setPaintBusy(true); myBusyAlarm.cancelAllRequests(); myBusyAlarm.addRequest(myWaiterForReady, myWaitForReadyTime.asInteger()); } else { tree.setPaintBusy(false); } } } private void setHoldSize(boolean holdSize) { if (myTree instanceof Tree) { final Tree tree = (Tree)myTree; tree.setHoldSize(holdSize); } } private void cleanUpAll() { final long now = System.currentTimeMillis(); final long timeToCleanup = ourUi2Countdown; if (timeToCleanup != 0 && now >= timeToCleanup) { ourUi2Countdown = 0; Runnable runnable = new TreeRunnable("AbstractTreeUi.cleanUpAll") { @Override public void perform() { if (!canInitiateNewActivity()) return; myCleanupTask = null; getBuilder().cleanUp(); } }; if (isPassthroughMode()) { runnable.run(); } else { invokeLaterIfNeeded(false, runnable); } } } void doCleanUp() { Runnable cleanup = new TreeRunnable("AbstractTreeUi.doCleanUp") { @Override public void perform() { if (canInitiateNewActivity()) { cleanUpNow(); } } }; if (isPassthroughMode()) { cleanup.run(); } else { invokeLaterIfNeeded(false, cleanup); } } void invokeLaterIfNeeded(boolean forceEdt, @Nonnull final Runnable runnable) { Runnable actual = new TreeRunnable("AbstractTreeUi.invokeLaterIfNeeded") { @Override public void perform() { if (!isReleased()) { runnable.run(); } } }; if (isPassthroughMode() || !forceEdt && !isEdt() && !isTreeShowing() && !myWasEverShown) { actual.run(); } else { UIUtil.invokeLaterIfNeeded(actual); } } public void activate(boolean byShowing) { cancelCurrentCleanupTask(); myCanProcessDeferredSelections = true; ourUi2Countdown = 0; if (!myWasEverShown || myUpdateFromRootRequested || myUpdateIfInactive) { getBuilder().updateFromRoot(); } getUpdater().showNotify(); myWasEverShown |= byShowing; } private void cancelCurrentCleanupTask() { if (myCleanupTask != null) { myCleanupTask.cancel(); myCleanupTask = null; } } void deactivate() { getUpdater().hideNotify(); myBusyAlarm.cancelAllRequests(); if (!myWasEverShown) return; // ask for termination of background children calculation if (myProgress != null && myProgress.isRunning()) myProgress.cancel(); if (!isReady()) { cancelUpdate(); myUpdateFromRootRequested = true; } if (getClearOnHideDelay() >= 0) { ourUi2Countdown = System.currentTimeMillis() + getClearOnHideDelay(); scheduleCleanUpAll(); } } private void scheduleCleanUpAll() { cancelCurrentCleanupTask(); myCleanupTask = SimpleTimer.getInstance().setUp(new TreeRunnable("AbstractTreeUi.scheduleCleanUpAll") { @Override public void perform() { cleanUpAll(); } }, getClearOnHideDelay()); } void requestRelease() { myReleaseRequested = true; cancelUpdate().doWhenDone(new TreeRunnable("AbstractTreeUi.requestRelease: on done") { @Override public void perform() { releaseNow(); } }); } public ProgressIndicator getProgress() { return myProgress; } private void releaseNow() { try (LockToken ignored = acquireLock()) { myTree.removeTreeExpansionListener(myExpansionListener); myTree.removeTreeSelectionListener(mySelectionListener); myTree.removeFocusListener(myFocusListener); disposeNode(getRootNode()); myElementToNodeMap.clear(); getUpdater().cancelAllRequests(); myWorker.clear(); clearWorkerTasks(); TREE_NODE_WRAPPER.setValue(null); if (myProgress != null) { myProgress.cancel(); } cancelCurrentCleanupTask(); myTree = null; setUpdater(null); myTreeStructure = null; myBuilder.releaseUi(); myBuilder = null; clearNodeActions(); myDeferredSelections.clear(); myDeferredExpansions.clear(); myYieldingDoneRunnables.clear(); } } public boolean isReleased() { return myBuilder == null; } void doExpandNodeChildren(@Nonnull final DefaultMutableTreeNode node) { if (!myUnbuiltNodes.contains(node)) return; if (isLoadedInBackground(getElementFor(node))) return; AbstractTreeStructure structure = getTreeStructure(); structure.asyncCommit().doWhenDone(new TreeRunnable("AbstractTreeUi.doExpandNodeChildren") { @Override public void perform() { addSubtreeToUpdate(node); // at this point some tree updates may already have been run as a result of // in tests these updates may lead to the instance disposal, so getUpdater() at the next line may return null final AbstractTreeUpdater updater = getUpdater(); if (updater != null) { updater.performUpdate(); } } }); //if (structure.hasSomethingToCommit()) structure.commit(); } public final AbstractTreeStructure getTreeStructure() { return myTreeStructure; } public final JTree getTree() { return myTree; } @Nullable private static NodeDescriptor getDescriptorFrom(Object node) { if (node instanceof DefaultMutableTreeNode) { Object userObject = ((DefaultMutableTreeNode)node).getUserObject(); if (userObject instanceof NodeDescriptor) { return (NodeDescriptor)userObject; } } return null; } @Nullable public final DefaultMutableTreeNode getNodeForElement(@Nonnull Object element, final boolean validateAgainstStructure) { DefaultMutableTreeNode result = null; if (validateAgainstStructure) { int index = 0; while (true) { final DefaultMutableTreeNode node = findNode(element, index); if (node == null) break; if (isNodeValidForElement(element, node)) { result = node; break; } index++; } } else { result = getFirstNode(element); } if (result != null && !isNodeInStructure(result)) { disposeNode(result); result = null; } return result; } private boolean isNodeInStructure(@Nonnull DefaultMutableTreeNode node) { return TreeUtil.isAncestor(getRootNode(), node) && getRootNode() == myTreeModel.getRoot(); } private boolean isNodeValidForElement(@Nonnull final Object element, @Nonnull final DefaultMutableTreeNode node) { return isSameHierarchy(element, node) || isValidChildOfParent(element, node); } private boolean isValidChildOfParent(@Nonnull final Object element, @Nonnull final DefaultMutableTreeNode node) { final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent(); final Object parentElement = getElementFor(parent); if (!isInStructure(parentElement)) return false; if (parent instanceof ElementNode) { return ((ElementNode)parent).isValidChild(element); } for (int i = 0; i < parent.getChildCount(); i++) { final TreeNode child = parent.getChildAt(i); final Object eachElement = getElementFor(child); if (element.equals(eachElement)) return true; } return false; } private boolean isSameHierarchy(@Nonnull Object element, @Nonnull DefaultMutableTreeNode node) { Object eachParent = element; DefaultMutableTreeNode eachParentNode = node; boolean valid; while (true) { if (eachParent == null) { valid = eachParentNode == null; break; } if (!eachParent.equals(getElementFor(eachParentNode))) { valid = false; break; } eachParent = getTreeStructure().getParentElement(eachParent); eachParentNode = (DefaultMutableTreeNode)eachParentNode.getParent(); } return valid; } @Nullable public final DefaultMutableTreeNode getNodeForPath(@Nonnull Object[] path) { DefaultMutableTreeNode node = null; for (final Object pathElement : path) { node = node == null ? getFirstNode(pathElement) : findNodeForChildElement(node, pathElement); if (node == null) { break; } } return node; } final void buildNodeForElement(@Nonnull Object element) { getUpdater().performUpdate(); DefaultMutableTreeNode node = getNodeForElement(element, false); if (node == null) { final List<Object> elements = new ArrayList<>(); while (true) { element = getTreeStructure().getParentElement(element); if (element == null) { break; } elements.add(0, element); } for (final Object element1 : elements) { node = getNodeForElement(element1, false); if (node != null) { expand(node, true); } } } } public final void buildNodeForPath(@Nonnull Object[] path) { getUpdater().performUpdate(); DefaultMutableTreeNode node = null; for (final Object pathElement : path) { node = node == null ? getFirstNode(pathElement) : findNodeForChildElement(node, pathElement); if (node != null && node != path[path.length - 1]) { expand(node, true); } } } public final void setNodeDescriptorComparator(Comparator<? super NodeDescriptor> nodeDescriptorComparator) { myNodeDescriptorComparator = nodeDescriptorComparator; myLastComparatorStamp = -1; getBuilder().queueUpdateFrom(getTreeStructure().getRootElement(), true); } @Nonnull protected AbstractTreeBuilder getBuilder() { return myBuilder; } protected final void initRootNode() { if (myUpdateIfInactive) { activate(false); } else { myUpdateFromRootRequested = true; } } private boolean initRootNodeNowIfNeeded(@Nonnull final TreeUpdatePass pass) { boolean wasCleanedUp = false; if (myRootNodeWasQueuedToInitialize) { Object root = getTreeStructure().getRootElement(); assert root != null : "Root element cannot be null"; Object currentRoot = getElementFor(myRootNode); if (Comparing.equal(root, currentRoot)) return false; Object rootAgain = getTreeStructure().getRootElement(); if (root != rootAgain && !root.equals(rootAgain)) { assert false : "getRootElement() if called twice must return either root1 == root2 or root1.equals(root2)"; } cleanUpNow(); wasCleanedUp = true; } if (myRootNodeWasQueuedToInitialize) return true; myRootNodeWasQueuedToInitialize = true; final Object rootElement = getTreeStructure().getRootElement(); addNodeAction(rootElement, false, node -> processDeferredActions()); final Ref<NodeDescriptor> rootDescriptor = new Ref<>(null); final boolean bgLoading = isToBuildChildrenInBackground(rootElement); Runnable build = new TreeRunnable("AbstractTreeUi.initRootNodeNowIfNeeded: build") { @Override public void perform() { rootDescriptor.set(getTreeStructure().createDescriptor(rootElement, null)); getRootNode().setUserObject(rootDescriptor.get()); update(rootDescriptor.get(), true); pass.addToUpdated(rootDescriptor.get()); } }; Runnable update = new TreeRunnable("AbstractTreeUi.initRootNodeNowIfNeeded: update") { @Override public void perform() { Object fromDescriptor = getElementFromDescriptor(rootDescriptor.get()); if (!isNodeNull(fromDescriptor)) { createMapping(fromDescriptor, getRootNode()); } insertLoadingNode(getRootNode(), true); boolean willUpdate = false; if (!rootDescriptor.isNull() && isAutoExpand(rootDescriptor.get())) { willUpdate = myUnbuiltNodes.contains(getRootNode()); expand(getRootNode(), true); } ActionCallback callback; if (willUpdate) { callback = ActionCallback.DONE; } else { callback = updateNodeChildren(getRootNode(), pass, null, false, false, false, true, true); } callback.doWhenDone(new TreeRunnable("AbstractTreeUi.initRootNodeNowIfNeeded: on done updateNodeChildren") { @Override public void perform() { if (getRootNode().getChildCount() == 0) { myTreeModel.nodeChanged(getRootNode()); } } }); } }; if (bgLoading) { queueToBackground(build, update).onSuccess(new TreeConsumer<Void>("AbstractTreeUi.initRootNodeNowIfNeeded: on processed queueToBackground") { @Override public void perform() { invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.initRootNodeNowIfNeeded: on processed queueToBackground later") { @Override public void perform() { myRootNodeInitialized = true; processNodeActionsIfReady(myRootNode); } }); } }); } else { build.run(); update.run(); myRootNodeInitialized = true; processNodeActionsIfReady(myRootNode); } return wasCleanedUp; } private boolean isAutoExpand(@Nonnull NodeDescriptor descriptor) { return isAutoExpand(descriptor, true); } private boolean isAutoExpand(@Nonnull NodeDescriptor descriptor, boolean validate) { if (isAlwaysExpandedTree()) return false; boolean autoExpand = getBuilder().isAutoExpandNode(descriptor); Object element = getElementFromDescriptor(descriptor); if (validate && element != null) { autoExpand = validateAutoExpand(autoExpand, element); } if (!autoExpand && !myTree.isRootVisible()) { if (element != null && element.equals(getTreeStructure().getRootElement())) return true; } return autoExpand; } private boolean validateAutoExpand(boolean autoExpand, @Nonnull Object element) { if (autoExpand) { int distance = getDistanceToAutoExpandRoot(element); if (distance < 0) { myAutoExpandRoots.add(element); } else { if (distance >= myAutoExpandDepth.asInteger() - 1) { autoExpand = false; } } if (autoExpand) { DefaultMutableTreeNode node = getNodeForElement(element, false); autoExpand = node != null && isInVisibleAutoExpandChain(node); } } return autoExpand; } private boolean isInVisibleAutoExpandChain(@Nonnull DefaultMutableTreeNode child) { TreeNode eachParent = child; while (eachParent != null) { if (myRootNode == eachParent) return true; NodeDescriptor eachDescriptor = getDescriptorFrom(eachParent); if (eachDescriptor == null || !isAutoExpand(eachDescriptor, false)) { TreePath path = getPathFor(eachParent); return myWillBeExpanded.contains(path.getLastPathComponent()) || myTree.isExpanded(path) && myTree.isVisible(path); } eachParent = eachParent.getParent(); } return false; } private int getDistanceToAutoExpandRoot(@Nonnull Object element) { int distance = 0; Object eachParent = element; while (eachParent != null) { if (myAutoExpandRoots.contains(eachParent)) break; eachParent = getTreeStructure().getParentElement(eachParent); distance++; } return eachParent != null ? distance : -1; } private boolean isAutoExpand(@Nonnull DefaultMutableTreeNode node) { NodeDescriptor descriptor = getDescriptorFrom(node); return descriptor != null && isAutoExpand(descriptor); } private boolean isAlwaysExpandedTree() { return myTree instanceof AlwaysExpandedTree && ((AlwaysExpandedTree)myTree).isAlwaysExpanded(); } @Nonnull private Promise<Boolean> update(@Nonnull final NodeDescriptor nodeDescriptor, boolean now) { Promise<Boolean> promise; if (now || isPassthroughMode()) { promise = Promises.resolvedPromise(update(nodeDescriptor)); } else { final AsyncPromise<Boolean> result = new AsyncPromise<>(); promise = result; boolean bgLoading = isToBuildInBackground(nodeDescriptor); boolean edt = isEdt(); if (bgLoading) { if (edt) { final AtomicBoolean changes = new AtomicBoolean(); queueToBackground(new TreeRunnable("AbstractTreeUi.update: build") { @Override public void perform() { changes.set(update(nodeDescriptor)); } }, new TreeRunnable("AbstractTreeUi.update: post") { @Override public void perform() { result.setResult(changes.get()); } }); } else { result.setResult(update(nodeDescriptor)); } } else { if (edt || !myWasEverShown) { result.setResult(update(nodeDescriptor)); } else { invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.update: later") { @Override public void perform() { execute(new TreeRunnable("AbstractTreeUi.update: later execute") { @Override public void perform() { result.setResult(update(nodeDescriptor)); } }); } }); } } } promise.onSuccess(changes -> { if (!changes) { return; } invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.update: on done result") { @Override public void perform() { Object element = nodeDescriptor.getElement(); DefaultMutableTreeNode node = element == null ? null : getNodeForElement(element, false); if (node != null) { TreePath path = getPathFor(node); if (myTree.isVisible(path)) { updateNodeImageAndPosition(node); } } } }); }); return promise; } private boolean update(@Nonnull final NodeDescriptor nodeDescriptor) { while (true) { try (LockToken ignored = attemptLock()) { if (ignored == null) { // async children calculation is in progress under lock if (myProgress != null && myProgress.isRunning()) myProgress.cancel(); continue; } final AtomicBoolean update = new AtomicBoolean(); execute(new TreeRunnable("AbstractTreeUi.update") { @Override public void perform() { nodeDescriptor.setUpdateCount(nodeDescriptor.getUpdateCount() + 1); update.set(getBuilder().updateNodeDescriptor(nodeDescriptor)); } }); return update.get(); } catch (IndexNotReadyException e) { warnOnIndexNotReady(e); return false; } catch (InterruptedException e) { LOG.info(e); return false; } } } public void assertIsDispatchThread() { if (isPassthroughMode()) return; if ((isTreeShowing() || myWasEverShown) && !isEdt()) { LOG.error("Must be in event-dispatch thread"); } } private static boolean isEdt() { return SwingUtilities.isEventDispatchThread(); } private boolean isTreeShowing() { return myShowing; } private void assertNotDispatchThread() { if (isPassthroughMode()) return; if (isEdt()) { LOG.error("Must not be in event-dispatch thread"); } } private void processDeferredActions() { processDeferredActions(myDeferredSelections); processDeferredActions(myDeferredExpansions); } private static void processDeferredActions(@Nonnull Set<Runnable> actions) { final Runnable[] runnables = actions.toArray(new Runnable[0]); actions.clear(); for (Runnable runnable : runnables) { runnable.run(); } } //todo: to make real callback @Nonnull public ActionCallback queueUpdate(Object element) { return queueUpdate(element, true); } @Nonnull public ActionCallback queueUpdate(final Object fromElement, boolean updateStructure) { assertIsDispatchThread(); try { if (getUpdater() == null) { return ActionCallback.REJECTED; } final ActionCallback result = new ActionCallback(); DefaultMutableTreeNode nodeToUpdate = null; boolean updateElementStructure = updateStructure; for (Object element = fromElement; element != null; element = getTreeStructure().getParentElement(element)) { final DefaultMutableTreeNode node = getFirstNode(element); if (node != null) { nodeToUpdate = node; break; } updateElementStructure = true; // always update children if element does not exist } addSubtreeToUpdate(nodeToUpdate != null ? nodeToUpdate : getRootNode(), new TreeRunnable("AbstractTreeUi.queueUpdate") { @Override public void perform() { result.setDone(); } }, updateElementStructure); return result; } catch (ProcessCanceledException e) { return ActionCallback.REJECTED; } } public void doUpdateFromRoot() { updateSubtree(getRootNode(), false); } public final void updateSubtree(@Nonnull DefaultMutableTreeNode node, boolean canSmartExpand) { updateSubtree(new TreeUpdatePass(node), canSmartExpand); } private void updateSubtree(@Nonnull TreeUpdatePass pass, boolean canSmartExpand) { final AbstractTreeUpdater updater = getUpdater(); if (updater != null) { updater.addSubtreeToUpdate(pass); } else { updateSubtreeNow(pass, canSmartExpand); } } final void updateSubtreeNow(@Nonnull TreeUpdatePass pass, boolean canSmartExpand) { maybeSetBusyAndScheduleWaiterForReady(true, getElementFor(pass.getNode())); setHoldSize(true); boolean consumed = initRootNodeNowIfNeeded(pass); if (consumed) return; final DefaultMutableTreeNode node = pass.getNode(); NodeDescriptor descriptor = getDescriptorFrom(node); if (descriptor == null) return; if (pass.isUpdateStructure()) { setUpdaterState(new UpdaterTreeState(this)).beforeSubtreeUpdate(); boolean forceUpdate = true; TreePath path = getPathFor(node); boolean invisible = !myTree.isExpanded(path) && (path.getParentPath() == null || !myTree.isExpanded(path.getParentPath())); if (invisible && myUnbuiltNodes.contains(node)) { forceUpdate = false; } updateNodeChildren(node, pass, null, false, canSmartExpand, forceUpdate, false, pass.isUpdateChildren()); } else { updateRow(0, pass); } } private void updateRow(final int row, @Nonnull final TreeUpdatePass pass) { LOG.debug("updateRow: ", row, " - ", pass); invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.updateRow") { @Override public void perform() { if (row >= getTree().getRowCount()) return; TreePath path = getTree().getPathForRow(row); if (path != null) { final NodeDescriptor descriptor = getDescriptorFrom(path.getLastPathComponent()); if (descriptor != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); maybeYield(() -> update(descriptor, false).onSuccess(new TreeConsumer<Boolean>("AbstractTreeUi.updateRow: inner") { @Override public void perform() { updateRow(row + 1, pass); } }), pass, node); } } } }); } boolean isToBuildChildrenInBackground(Object element) { AbstractTreeStructure structure = getTreeStructure(); return element != null && structure.isToBuildChildrenInBackground(element); } private boolean isToBuildInBackground(NodeDescriptor descriptor) { return isToBuildChildrenInBackground(getElementFromDescriptor(descriptor)); } @Nonnull private UpdaterTreeState setUpdaterState(@Nonnull UpdaterTreeState state) { if (state.equals(myUpdaterState)) return state; final UpdaterTreeState oldState = myUpdaterState; if (oldState == null) { myUpdaterState = state; return state; } else { oldState.addAll(state); return oldState; } } void doUpdateNode(@Nonnull final DefaultMutableTreeNode node) { NodeDescriptor descriptor = getDescriptorFrom(node); if (descriptor == null) return; final Object prevElement = getElementFromDescriptor(descriptor); if (prevElement == null) return; update(descriptor, false).onSuccess(changes -> { if (!isValid(descriptor)) { if (isInStructure(prevElement)) { Object toUpdate = ObjectUtils.notNull(getTreeStructure().getParentElement(prevElement), getTreeStructure().getRootElement()); getUpdater().addSubtreeToUpdateByElement(toUpdate); return; } } if (changes) { updateNodeImageAndPosition(node); } }); } public Object getElementFromDescriptor(NodeDescriptor descriptor) { return getBuilder().getTreeStructureElement(descriptor); } @Nonnull private ActionCallback updateNodeChildren(@Nonnull final DefaultMutableTreeNode node, @Nonnull final TreeUpdatePass pass, @Nullable final LoadedChildren loadedChildren, final boolean forcedNow, final boolean toSmartExpand, final boolean forceUpdate, final boolean descriptorIsUpToDate, final boolean updateChildren) { AbstractTreeStructure treeStructure = getTreeStructure(); ActionCallback result = treeStructure.asyncCommit(); result.doWhenDone(new TreeRunnable("AbstractTreeUi.updateNodeChildren: on done") { @Override public void perform() { try { removeFromCancelled(node); execute(new TreeRunnable("AbstractTreeUi.updateNodeChildren: execute") { @Override public void perform() { doUpdateChildren(node, pass, loadedChildren, forcedNow, toSmartExpand, forceUpdate, descriptorIsUpToDate, updateChildren); } }); } catch (ProcessCanceledException e) { addToCancelled(node); throw e; } } }); return result; } private void doUpdateChildren(@Nonnull final DefaultMutableTreeNode node, @Nonnull final TreeUpdatePass pass, @Nullable final LoadedChildren loadedChildren, boolean forcedNow, final boolean toSmartExpand, boolean forceUpdate, boolean descriptorIsUpToDate, final boolean updateChildren) { try { final NodeDescriptor descriptor = getDescriptorFrom(node); if (descriptor == null) { removeFromUnbuilt(node); removeLoading(node, true); return; } boolean descriptorIsReady = descriptorIsUpToDate || pass.isUpdated(descriptor); final boolean wasExpanded = myTree.isExpanded(new TreePath(node.getPath())) || isAutoExpand(node); final boolean wasLeaf = node.getChildCount() == 0; boolean bgBuild = isToBuildInBackground(descriptor); boolean requiredToUpdateChildren = forcedNow || wasExpanded; if (!requiredToUpdateChildren && forceUpdate) { boolean alwaysPlus = getBuilder().isAlwaysShowPlus(descriptor); if (alwaysPlus && wasLeaf) { requiredToUpdateChildren = true; } else { requiredToUpdateChildren = !alwaysPlus; if (!requiredToUpdateChildren && !myUnbuiltNodes.contains(node)) { removeChildren(node); } } } final AtomicReference<LoadedChildren> preloaded = new AtomicReference<>(loadedChildren); if (!requiredToUpdateChildren) { if (myUnbuiltNodes.contains(node) && node.getChildCount() == 0) { insertLoadingNode(node, true); } if (!descriptorIsReady) { update(descriptor, false); } return; } if (!forcedNow && !bgBuild && myUnbuiltNodes.contains(node)) { if (!descriptorIsReady) { update(descriptor, true); descriptorIsReady = true; } if (processAlwaysLeaf(node) || !updateChildren) { return; } Pair<Boolean, LoadedChildren> unbuilt = processUnbuilt(node, descriptor, pass, wasExpanded, null); if (unbuilt.getFirst()) { return; } preloaded.set(unbuilt.getSecond()); } final boolean childForceUpdate = isChildNodeForceUpdate(node, forceUpdate, wasExpanded); if (!forcedNow && isToBuildInBackground(descriptor)) { boolean alwaysLeaf = processAlwaysLeaf(node); queueBackgroundUpdate(new UpdateInfo(descriptor, pass, canSmartExpand(node, toSmartExpand), wasExpanded, childForceUpdate, descriptorIsReady, !alwaysLeaf && updateChildren), node); } else { if (!descriptorIsReady) { update(descriptor, false).onSuccess(new TreeConsumer<Boolean>("AbstractTreeUi.doUpdateChildren") { @Override public void perform() { if (processAlwaysLeaf(node) || !updateChildren) return; updateNodeChildrenNow(node, pass, preloaded.get(), toSmartExpand, wasExpanded, childForceUpdate); } }); } else { if (processAlwaysLeaf(node) || !updateChildren) return; updateNodeChildrenNow(node, pass, preloaded.get(), toSmartExpand, wasExpanded, childForceUpdate); } } } finally { if (!isReleased()) { processNodeActionsIfReady(node); } } } private boolean processAlwaysLeaf(@Nonnull DefaultMutableTreeNode node) { Object element = getElementFor(node); NodeDescriptor desc = getDescriptorFrom(node); if (desc == null) return false; if (element != null && getTreeStructure().isAlwaysLeaf(element)) { removeFromUnbuilt(node); removeLoading(node, true); if (node.getChildCount() > 0) { final TreeNode[] children = new TreeNode[node.getChildCount()]; for (int i = 0; i < node.getChildCount(); i++) { children[i] = node.getChildAt(i); } if (isSelectionInside(node)) { addSelectionPath(getPathFor(node), true, Conditions.alwaysTrue(), null); } processInnerChange(new TreeRunnable("AbstractTreeUi.processAlwaysLeaf") { @Override public void perform() { for (TreeNode each : children) { removeNodeFromParent((MutableTreeNode)each, true); disposeNode((DefaultMutableTreeNode)each); } } }); } removeFromUnbuilt(node); desc.setWasDeclaredAlwaysLeaf(true); processNodeActionsIfReady(node); return true; } else { boolean wasLeaf = desc.isWasDeclaredAlwaysLeaf(); desc.setWasDeclaredAlwaysLeaf(false); if (wasLeaf) { insertLoadingNode(node, true); } return false; } } private boolean isChildNodeForceUpdate(@Nonnull DefaultMutableTreeNode node, boolean parentForceUpdate, boolean parentExpanded) { TreePath path = getPathFor(node); return parentForceUpdate && (parentExpanded || myTree.isExpanded(path)); } private void updateNodeChildrenNow(@Nonnull final DefaultMutableTreeNode node, @Nonnull final TreeUpdatePass pass, @Nullable final LoadedChildren preloadedChildren, final boolean toSmartExpand, final boolean wasExpanded, final boolean forceUpdate) { if (isUpdatingChildrenNow(node)) return; if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } final NodeDescriptor descriptor = getDescriptorFrom(node); final MutualMap<Object, Integer> elementToIndexMap = loadElementsFromStructure(descriptor, preloadedChildren); final LoadedChildren loadedChildren = preloadedChildren != null ? preloadedChildren : new LoadedChildren(elementToIndexMap.getKeys().toArray()); addToUpdatingChildren(node); pass.setCurrentNode(node); final boolean canSmartExpand = canSmartExpand(node, toSmartExpand); removeFromUnbuilt(node); //noinspection unchecked processExistingNodes(node, elementToIndexMap, pass, canSmartExpand(node, toSmartExpand), forceUpdate, wasExpanded, preloadedChildren) .onSuccess(new TreeConsumer("AbstractTreeUi.updateNodeChildrenNow: on done processExistingNodes") { @Override public void perform() { if (isDisposed(node)) { removeFromUpdatingChildren(node); return; } removeLoading(node, false); final boolean expanded = isExpanded(node, wasExpanded); if (expanded) { myWillBeExpanded.add(node); } else { myWillBeExpanded.remove(node); } collectNodesToInsert(descriptor, elementToIndexMap, node, expanded, loadedChildren).doWhenDone(nodesToInsert -> { insertNodesInto(nodesToInsert, node); ActionCallback callback = updateNodesToInsert(nodesToInsert, pass, canSmartExpand, isChildNodeForceUpdate(node, forceUpdate, expanded)); callback.doWhenDone(new TreeRunnable("AbstractTreeUi.updateNodeChildrenNow: on done updateNodesToInsert") { @Override public void perform() { removeLoading(node, false); removeFromUpdatingChildren(node); if (node.getChildCount() > 0) { if (expanded) { expand(node, canSmartExpand); } } if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } final Object element = getElementFor(node); addNodeAction(element, false, node1 -> removeLoading(node1, false)); processNodeActionsIfReady(node); } }); }).doWhenProcessed(new TreeRunnable("AbstractTreeUi.updateNodeChildrenNow: on processed collectNodesToInsert") { @Override public void perform() { myWillBeExpanded.remove(node); removeFromUpdatingChildren(node); processNodeActionsIfReady(node); } }); } }).onError(new TreeConsumer<Throwable>("AbstractTreeUi.updateNodeChildrenNow: on reject processExistingNodes") { @Override public void perform() { removeFromUpdatingChildren(node); processNodeActionsIfReady(node); } }); } private boolean isDisposed(@Nonnull DefaultMutableTreeNode node) { return !node.isNodeAncestor((DefaultMutableTreeNode)myTree.getModel().getRoot()); } private void expandSilently(TreePath path) { assertIsDispatchThread(); try { mySilentExpand = path; getTree().expandPath(path); } finally { mySilentExpand = null; } } private void addSelectionSilently(TreePath path) { assertIsDispatchThread(); try { mySilentSelect = path; getTree().getSelectionModel().addSelectionPath(path); } finally { mySilentSelect = null; } } private void expand(@Nonnull DefaultMutableTreeNode node, boolean canSmartExpand) { expand(new TreePath(node.getPath()), canSmartExpand); } private void expand(@Nonnull final TreePath path, boolean canSmartExpand) { final Object last = path.getLastPathComponent(); boolean isLeaf = myTree.getModel().isLeaf(path.getLastPathComponent()); final boolean isRoot = last == myTree.getModel().getRoot(); final TreePath parent = path.getParentPath(); if (isRoot && !myTree.isExpanded(path)) { if (myTree.isRootVisible() || myUnbuiltNodes.contains(last)) { insertLoadingNode((DefaultMutableTreeNode)last, false); } expandPath(path, canSmartExpand); } else if (myTree.isExpanded(path) || isLeaf && parent != null && myTree.isExpanded(parent) && !myUnbuiltNodes.contains(last) && !isCancelled(last)) { if (last instanceof DefaultMutableTreeNode) { processNodeActionsIfReady((DefaultMutableTreeNode)last); } } else { if (isLeaf && (myUnbuiltNodes.contains(last) || isCancelled(last))) { insertLoadingNode((DefaultMutableTreeNode)last, true); expandPath(path, canSmartExpand); } else if (isLeaf && parent != null) { final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)parent.getLastPathComponent(); if (parentNode != null) { addToUnbuilt(parentNode); } expandPath(parent, canSmartExpand); } else { expandPath(path, canSmartExpand); } } } private void addToUnbuilt(DefaultMutableTreeNode node) { myUnbuiltNodes.add(node); } private void removeFromUnbuilt(DefaultMutableTreeNode node) { myUnbuiltNodes.remove(node); } private Pair<Boolean, LoadedChildren> processUnbuilt(@Nonnull final DefaultMutableTreeNode node, final NodeDescriptor descriptor, @Nonnull final TreeUpdatePass pass, final boolean isExpanded, @Nullable final LoadedChildren loadedChildren) { final Ref<Pair<Boolean, LoadedChildren>> result = new Ref<>(); execute(new TreeRunnable("AbstractTreeUi.processUnbuilt") { @Override public void perform() { if (!isExpanded && getBuilder().isAlwaysShowPlus(descriptor)) { result.set(new Pair<>(true, null)); return; } final Object element = getElementFor(node); if (element == null) { trace("null element for node " + node); result.set(new Pair<>(true, null)); return; } addToUpdatingChildren(node); try { final LoadedChildren children = loadedChildren != null ? loadedChildren : new LoadedChildren(getChildrenFor(element)); boolean processed; if (children.getElements().isEmpty()) { removeFromUnbuilt(node); removeLoading(node, true); processed = true; } else { if (isAutoExpand(node)) { addNodeAction(getElementFor(node), false, node1 -> { final TreePath path = new TreePath(node1.getPath()); if (getTree().isExpanded(path) || children.getElements().isEmpty()) { removeLoading(node1, false); } else { maybeYield(() -> { expand(element, null); return Promises.resolvedPromise(); }, pass, node1); } }); } processed = false; } removeFromUpdatingChildren(node); processNodeActionsIfReady(node); result.set(new Pair<>(processed, children)); } finally { removeFromUpdatingChildren(node); } } }); return result.get(); } private boolean removeIfLoading(@Nonnull TreeNode node) { if (isLoadingNode(node)) { moveSelectionToParentIfNeeded(node); removeNodeFromParent((MutableTreeNode)node, false); return true; } return false; } private void moveSelectionToParentIfNeeded(@Nonnull TreeNode node) { TreePath path = getPathFor(node); if (myTree.getSelectionModel().isPathSelected(path)) { TreePath parentPath = path.getParentPath(); myTree.getSelectionModel().removeSelectionPath(path); if (parentPath != null) { myTree.getSelectionModel().addSelectionPath(parentPath); } } } //todo [kirillk] temporary consistency check private Object[] getChildrenFor(final Object element) { final Ref<Object[]> passOne = new Ref<>(); try (LockToken ignored = acquireLock()) { execute(new TreeRunnable("AbstractTreeUi.getChildrenFor") { @Override public void perform() { passOne.set(getTreeStructure().getChildElements(element)); } }); } catch (IndexNotReadyException e) { warnOnIndexNotReady(e); return ArrayUtil.EMPTY_OBJECT_ARRAY; } if (!Registry.is("ide.tree.checkStructure")) return passOne.get(); final Object[] passTwo = getTreeStructure().getChildElements(element); final HashSet<Object> two = new HashSet<>(Arrays.asList(passTwo)); if (passOne.get().length != passTwo.length) { LOG.error("AbstractTreeStructure.getChildren() must either provide same objects or new objects but with correct hashCode() and equals() methods. Wrong parent element=" + element); } else { for (Object eachInOne : passOne.get()) { if (!two.contains(eachInOne)) { LOG.error("AbstractTreeStructure.getChildren() must either provide same objects or new objects but with correct hashCode() and equals() methods. Wrong parent element=" + element); break; } } } return passOne.get(); } private void warnOnIndexNotReady(IndexNotReadyException e) { if (!myWasEverIndexNotReady) { myWasEverIndexNotReady = true; LOG.error("Tree is not dumb-mode-aware; treeBuilder=" + getBuilder() + " treeStructure=" + getTreeStructure(), e); } } @Nonnull private ActionCallback updateNodesToInsert(@Nonnull final List<? extends TreeNode> nodesToInsert, @Nonnull TreeUpdatePass pass, boolean canSmartExpand, boolean forceUpdate) { ActionCallback.Chunk chunk = new ActionCallback.Chunk(); for (TreeNode node : nodesToInsert) { DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)node; ActionCallback callback = updateNodeChildren(childNode, pass, null, false, canSmartExpand, forceUpdate, true, true); if (!callback.isDone()) { chunk.add(callback); } } return chunk.getWhenProcessed(); } @Nonnull private Promise<?> processExistingNodes(@Nonnull final DefaultMutableTreeNode node, @Nonnull final MutualMap<Object, Integer> elementToIndexMap, @Nonnull final TreeUpdatePass pass, final boolean canSmartExpand, final boolean forceUpdate, final boolean wasExpanded, @Nullable final LoadedChildren preloaded) { final List<TreeNode> childNodes = TreeUtil.listChildren(node); return maybeYield(() -> { if (pass.isExpired()) return Promises.<Void>rejectedPromise(); if (childNodes.isEmpty()) return Promises.resolvedPromise(); List<Promise<?>> promises = new SmartList<>(); for (TreeNode each : childNodes) { final DefaultMutableTreeNode eachChild = (DefaultMutableTreeNode)each; if (isLoadingNode(eachChild)) { continue; } final boolean childForceUpdate = isChildNodeForceUpdate(eachChild, forceUpdate, wasExpanded); promises.add(maybeYield(() -> { NodeDescriptor descriptor = preloaded != null ? preloaded.getDescriptor(getElementFor(eachChild)) : null; NodeDescriptor descriptorFromNode = getDescriptorFrom(eachChild); if (isValid(descriptor)) { eachChild.setUserObject(descriptor); if (descriptorFromNode != null) { descriptor.setChildrenSortingStamp(descriptorFromNode.getChildrenSortingStamp()); } } else { descriptor = descriptorFromNode; } return processExistingNode(eachChild, descriptor, node, elementToIndexMap, pass, canSmartExpand, childForceUpdate, preloaded); }, pass, node)); for (Promise<?> promise : promises) { if (promise.getState() == Promise.State.REJECTED) { return Promises.<Void>rejectedPromise(); } } } return Promises.all(promises); }, pass, node); } private boolean isRerunNeeded(@Nonnull TreeUpdatePass pass) { if (pass.isExpired() || !canInitiateNewActivity()) return false; final boolean rerunBecauseTreeIsHidden = !pass.isExpired() && !isTreeShowing() && getUpdater().isInPostponeMode(); return rerunBecauseTreeIsHidden || getUpdater().isRerunNeededFor(pass); } public static <T> T calculateYieldingToWriteAction(@RequiredReadAction @Nonnull Supplier<? extends T> producer) throws ProcessCanceledException { if (!Registry.is("ide.abstractTreeUi.BuildChildrenInBackgroundYieldingToWriteAction") || ApplicationManager.getApplication().isDispatchThread()) { return producer.get(); } ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); if (indicator != null && indicator.isRunning()) { return producer.get(); } Ref<T> result = new Ref<>(); boolean succeeded = ProgressManager.getInstance().runInReadActionWithWriteActionPriority(() -> result.set(producer.get()), indicator); if (!succeeded || indicator != null && indicator.isCanceled()) { throw new ProcessCanceledException(); } return result.get(); } @FunctionalInterface private interface AsyncRunnable { @Nonnull Promise<?> run(); } @Nonnull private Promise<?> maybeYield(@Nonnull final AsyncRunnable processRunnable, @Nonnull final TreeUpdatePass pass, final DefaultMutableTreeNode node) { if (isRerunNeeded(pass)) { getUpdater().requeue(pass); return Promises.<Void>rejectedPromise(); } if (canYield()) { final AsyncPromise<?> result = new AsyncPromise<Void>(); pass.setCurrentNode(node); boolean wasRun = yieldAndRun(new TreeRunnable("AbstractTreeUi.maybeYeild") { @Override public void perform() { if (pass.isExpired()) { result.setError("expired"); return; } if (isRerunNeeded(pass)) { runDone(new TreeRunnable("AbstractTreeUi.maybeYeild: rerun") { @Override public void perform() { if (!pass.isExpired()) { queueUpdate(getElementFor(node)); } } }); result.setError("requeue"); } else { try { //noinspection unchecked execute(processRunnable).processed((Promise)result); } catch (ProcessCanceledException e) { pass.expire(); cancelUpdate(); result.setError("rejected"); } } } }, pass); if (!wasRun) { result.setError("rejected"); } return result; } else { try { return execute(processRunnable); } catch (ProcessCanceledException e) { pass.expire(); cancelUpdate(); return Promises.<Void>rejectedPromise(); } } } @Nonnull private Promise<?> execute(@Nonnull AsyncRunnable runnable) throws ProcessCanceledException { try { if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } Promise<?> promise = runnable.run(); if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } return promise; } catch (ProcessCanceledException e) { if (!isReleased()) { setCancelRequested(true); resetToReady(); } throw e; } } private void execute(@Nonnull Runnable runnable) throws ProcessCanceledException { try { if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } runnable.run(); if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } } catch (ProcessCanceledException e) { if (!isReleased()) { setCancelRequested(true); resetToReady(); } throw e; } } private boolean canInitiateNewActivity() { return !isCancelProcessed() && !myReleaseRequested && !isReleased(); } private void resetToReady() { if (isReady()) { return; } if (myResettingToReadyNow.get()) { _getReady(); return; } myResettingToReadyNow.set(true); invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.resetToReady: later") { @Override public void perform() { if (!myResettingToReadyNow.get()) { return; } Progressive[] progressives = myBatchIndicators.keySet().toArray(new Progressive[0]); for (Progressive each : progressives) { myBatchIndicators.remove(each).cancel(); myBatchCallbacks.remove(each).setRejected(); } resetToReadyNow(); } }); } @Nonnull private ActionCallback resetToReadyNow() { if (isReleased()) return ActionCallback.REJECTED; assertIsDispatchThread(); DefaultMutableTreeNode[] uc; synchronized (myUpdatingChildren) { uc = myUpdatingChildren.toArray(new DefaultMutableTreeNode[0]); } for (DefaultMutableTreeNode each : uc) { resetIncompleteNode(each); } Object[] bg = ArrayUtil.toObjectArray(myLoadedInBackground.keySet()); for (Object each : bg) { final DefaultMutableTreeNode node = getNodeForElement(each, false); if (node != null) { resetIncompleteNode(node); } } myUpdaterState = null; getUpdater().reset(); myYieldingNow = false; myYieldingPasses.clear(); myYieldingDoneRunnables.clear(); myNodeActions.clear(); myNodeChildrenActions.clear(); synchronized (myUpdatingChildren) { myUpdatingChildren.clear(); } myLoadedInBackground.clear(); myDeferredExpansions.clear(); myDeferredSelections.clear(); ActionCallback result = _getReady(); result.doWhenDone(new TreeRunnable("AbstractTreeUi.resetToReadyNow: on done") { @Override public void perform() { myResettingToReadyNow.set(false); setCancelRequested(false); } }); maybeReady(); return result; } void addToCancelled(@Nonnull DefaultMutableTreeNode node) { myCancelledBuild.put(node, node); } private void removeFromCancelled(@Nonnull DefaultMutableTreeNode node) { myCancelledBuild.remove(node); } public boolean isCancelled(@Nonnull Object node) { return node instanceof DefaultMutableTreeNode && myCancelledBuild.containsKey(node); } private void resetIncompleteNode(@Nonnull DefaultMutableTreeNode node) { if (myReleaseRequested) return; addToCancelled(node); if (!isExpanded(node, false)) { node.removeAllChildren(); Object element = getElementFor(node); if (element != null && !getTreeStructure().isAlwaysLeaf(element)) { insertLoadingNode(node, true); } } else { removeFromUnbuilt(node); removeLoading(node, true); } } private boolean yieldAndRun(@Nonnull final Runnable runnable, @Nonnull final TreeUpdatePass pass) { myYieldingPasses.add(pass); myYieldingNow = true; yield(new TreeRunnable("AbstractTreeUi.yieldAndRun") { @Override public void perform() { if (isReleased()) return; runOnYieldingDone(new TreeRunnable("AbstractTreeUi.yieldAndRun: inner") { @Override public void perform() { if (isReleased()) return; executeYieldingRequest(runnable, pass); } }); } }); return true; } private boolean isYeildingNow() { return myYieldingNow; } private boolean hasScheduledUpdates() { return getUpdater().hasNodesToUpdate(); } public boolean isReady() { return isReady(false); } boolean isCancelledReady() { return isReady(false) && !myCancelledBuild.isEmpty(); } public boolean isReady(boolean attempt) { if (attempt && myStateLock.isLocked()) return false; Boolean ready = checkValue(() -> isIdle() && !hasPendingWork() && !isNodeActionsPending(), attempt); return ready != null && ready.booleanValue(); } @Nullable private Boolean checkValue(@Nonnull Computable<Boolean> computable, boolean attempt) { try (LockToken ignored = attempt ? attemptLock() : acquireLock()) { return computable.compute(); } catch (InterruptedException e) { LOG.info(e); return null; } } @Nonnull @NonNls public String getStatus() { return "isReady=" + isReady() + "\n" + " isIdle=" + isIdle() + "\n" + " isYeildingNow=" + isYeildingNow() + "\n" + " isWorkerBusy=" + isWorkerBusy() + "\n" + " hasUpdatingChildrenNow=" + hasUpdatingChildrenNow() + "\n" + " isLoadingInBackgroundNow=" + isLoadingInBackgroundNow() + "\n" + " hasPendingWork=" + hasPendingWork() + "\n" + " hasNodesToUpdate=" + hasNodesToUpdate() + "\n" + " updaterState=" + myUpdaterState + "\n" + " hasScheduledUpdates=" + hasScheduledUpdates() + "\n" + " isPostponedMode=" + getUpdater().isInPostponeMode() + "\n" + " nodeActions=" + myNodeActions.keySet() + "\n" + " nodeChildrenActions=" + myNodeChildrenActions.keySet() + "\n" + "isReleased=" + isReleased() + "\n" + " isReleaseRequested=" + isReleaseRequested() + "\n" + "isCancelProcessed=" + isCancelProcessed() + "\n" + " isCancelRequested=" + myCancelRequest + "\n" + " isResettingToReadyNow=" + myResettingToReadyNow + "\n" + "canInitiateNewActivity=" + canInitiateNewActivity() + "\n" + "batchIndicators=" + myBatchIndicators; } public boolean hasPendingWork() { return hasNodesToUpdate() || myUpdaterState != null && myUpdaterState.isProcessingNow() || hasScheduledUpdates() && !getUpdater().isInPostponeMode(); } public boolean isIdle() { return !isYeildingNow() && !isWorkerBusy() && !hasUpdatingChildrenNow() && !isLoadingInBackgroundNow(); } private void executeYieldingRequest(@Nonnull Runnable runnable, @Nonnull TreeUpdatePass pass) { try { try { myYieldingPasses.remove(pass); if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } runnable.run(); } finally { if (!isReleased()) { maybeYieldingFinished(); } } } catch (ProcessCanceledException e) { resetToReady(); } } private void maybeYieldingFinished() { if (myYieldingPasses.isEmpty()) { myYieldingNow = false; flushPendingNodeActions(); } } void maybeReady() { assertIsDispatchThread(); if (isReleased()) return; boolean ready = isReady(true); if (!ready) return; myRevalidatedObjects.clear(); setCancelRequested(false); myResettingToReadyNow.set(false); myInitialized.setDone(); if (canInitiateNewActivity()) { if (myUpdaterState != null && !myUpdaterState.isProcessingNow()) { UpdaterTreeState oldState = myUpdaterState; if (!myUpdaterState.restore(null)) { setUpdaterState(oldState); } if (!isReady(true)) return; } } setHoldSize(false); if (myTree.isShowing()) { if (getBuilder().isToEnsureSelectionOnFocusGained() && Registry.is("ide.tree.ensureSelectionOnFocusGained")) { TreeUtil.ensureSelection(myTree); } } if (myInitialized.isDone()) { if (isReleaseRequested() || isCancelProcessed()) { myBusyObject.onReady(this); } else { myBusyObject.onReady(); } } if (canInitiateNewActivity()) { TreePath[] selection = getTree().getSelectionPaths(); Rectangle visible = getTree().getVisibleRect(); if (selection != null) { for (TreePath each : selection) { Rectangle bounds = getTree().getPathBounds(each); if (bounds != null && (visible.contains(bounds) || visible.intersects(bounds))) { getTree().repaint(bounds); } } } } } private void flushPendingNodeActions() { final DefaultMutableTreeNode[] nodes = myPendingNodeActions.toArray(new DefaultMutableTreeNode[0]); myPendingNodeActions.clear(); for (DefaultMutableTreeNode each : nodes) { processNodeActionsIfReady(each); } final Runnable[] actions = myYieldingDoneRunnables.toArray(new Runnable[0]); for (Runnable each : actions) { if (!isYeildingNow()) { myYieldingDoneRunnables.remove(each); each.run(); } } maybeReady(); } protected void runOnYieldingDone(@Nonnull Runnable onDone) { getBuilder().runOnYieldingDone(onDone); } protected void yield(Runnable runnable) { getBuilder().yield(runnable); } @Nonnull private MutualMap<Object, Integer> loadElementsFromStructure(final NodeDescriptor descriptor, @Nullable LoadedChildren preloadedChildren) { MutualMap<Object, Integer> elementToIndexMap = new MutualMap<>(true); final Object element = getElementFromDescriptor(descriptor); if (!isValid(element)) return elementToIndexMap; List<Object> children = preloadedChildren != null ? preloadedChildren.getElements() : Arrays.asList(getChildrenFor(element)); int index = 0; for (Object child : children) { if (!isValid(child)) continue; elementToIndexMap.put(child, index); index++; } return elementToIndexMap; } public static boolean isLoadingNode(final Object node) { return node instanceof LoadingNode; } @Nonnull private AsyncResult<List<TreeNode>> collectNodesToInsert(final NodeDescriptor descriptor, @Nonnull final MutualMap<Object, Integer> elementToIndexMap, final DefaultMutableTreeNode parent, final boolean addLoadingNode, @Nonnull final LoadedChildren loadedChildren) { final AsyncResult<List<TreeNode>> result = new AsyncResult<>(); final List<TreeNode> nodesToInsert = new ArrayList<>(); Collection<Object> allElements = elementToIndexMap.getKeys(); ActionCallback processingDone = allElements.isEmpty() ? ActionCallback.DONE : new ActionCallback(allElements.size()); for (final Object child : allElements) { Integer index = elementToIndexMap.getValue(child); boolean needToUpdate = false; NodeDescriptor loadedDesc = loadedChildren.getDescriptor(child); final NodeDescriptor childDescr; if (!isValid(loadedDesc, descriptor)) { childDescr = getTreeStructure().createDescriptor(child, descriptor); needToUpdate = true; } else { childDescr = loadedDesc; } if (index == null) { index = Integer.MAX_VALUE; needToUpdate = true; } childDescr.setIndex(index.intValue()); final ActionCallback update = new ActionCallback(); if (needToUpdate) { update(childDescr, false).onSuccess(changes -> { loadedChildren.putDescriptor(child, childDescr, changes); update.setDone(); }); } else { update.setDone(); } update.doWhenDone(new TreeRunnable("AbstractTreeUi.collectNodesToInsert: on done update") { @Override public void perform() { Object element = getElementFromDescriptor(childDescr); if (!isNodeNull(element)) { DefaultMutableTreeNode node = getNodeForElement(element, false); if (node == null || node.getParent() != parent) { final DefaultMutableTreeNode childNode = createChildNode(childDescr); if (addLoadingNode || getBuilder().isAlwaysShowPlus(childDescr)) { insertLoadingNode(childNode, true); } else { addToUnbuilt(childNode); } nodesToInsert.add(childNode); createMapping(element, childNode); } } processingDone.setDone(); } }); } processingDone.doWhenDone(new TreeRunnable("AbstractTreeUi.collectNodesToInsert: on done processing") { @Override public void perform() { result.setDone(nodesToInsert); } }); return result; } @Nonnull protected DefaultMutableTreeNode createChildNode(final NodeDescriptor descriptor) { return new ElementNode(this, descriptor); } protected boolean canYield() { return myCanYield && myYieldingUpdate.asBoolean(); } private long getClearOnHideDelay() { return myClearOnHideDelay; } @Nonnull public ActionCallback getInitialized() { return myInitialized; } public ActionCallback getReady(@Nonnull Object requestor) { return myBusyObject.getReady(requestor); } private ActionCallback _getReady() { return getReady(this); } private void addToUpdatingChildren(@Nonnull DefaultMutableTreeNode node) { synchronized (myUpdatingChildren) { myUpdatingChildren.add(node); } } private void removeFromUpdatingChildren(@Nonnull DefaultMutableTreeNode node) { synchronized (myUpdatingChildren) { myUpdatingChildren.remove(node); } } boolean isUpdatingChildrenNow(DefaultMutableTreeNode node) { synchronized (myUpdatingChildren) { return myUpdatingChildren.contains(node); } } boolean isParentUpdatingChildrenNow(@Nonnull DefaultMutableTreeNode node) { synchronized (myUpdatingChildren) { DefaultMutableTreeNode eachParent = (DefaultMutableTreeNode)node.getParent(); while (eachParent != null) { if (myUpdatingChildren.contains(eachParent)) return true; eachParent = (DefaultMutableTreeNode)eachParent.getParent(); } return false; } } private boolean hasUpdatingChildrenNow() { synchronized (myUpdatingChildren) { return !myUpdatingChildren.isEmpty(); } } @Nonnull Map<Object, List<NodeAction>> getNodeActions() { return myNodeActions; } @Nonnull List<Object> getLoadedChildrenFor(@Nonnull Object element) { List<Object> result = new ArrayList<>(); DefaultMutableTreeNode node = getNodeForElement(element, false); if (node != null) { for (int i = 0; i < node.getChildCount(); i++) { TreeNode each = node.getChildAt(i); if (isLoadingNode(each)) continue; result.add(getElementFor(each)); } } return result; } boolean hasNodesToUpdate() { return getUpdater().hasNodesToUpdate(); } @Nonnull public List<Object> getExpandedElements() { final List<Object> result = new ArrayList<>(); if (isReleased()) return result; final Enumeration<TreePath> enumeration = myTree.getExpandedDescendants(getPathFor(getRootNode())); if (enumeration != null) { while (enumeration.hasMoreElements()) { TreePath each = enumeration.nextElement(); Object eachElement = getElementFor(each.getLastPathComponent()); if (eachElement != null) { result.add(eachElement); } } } return result; } @Nonnull public ActionCallback cancelUpdate() { if (isReleased()) return ActionCallback.REJECTED; setCancelRequested(true); final ActionCallback done = new ActionCallback(); invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.cancelUpdate") { @Override public void perform() { if (isReleased()) { done.setRejected(); return; } if (myResettingToReadyNow.get()) { _getReady().notify(done); } else if (isReady()) { resetToReadyNow(); done.setDone(); } else { if (isIdle() && hasPendingWork()) { resetToReadyNow(); done.setDone(); } else { _getReady().notify(done); } } maybeReady(); } }); if (isEdt() || isPassthroughMode()) { maybeReady(); } return done; } private void setCancelRequested(boolean requested) { try (LockToken ignored = isUnitTestingMode() ? acquireLock() : attemptLock()) { myCancelRequest.set(requested); } catch (InterruptedException ignored) { } } @Nullable private LockToken attemptLock() throws InterruptedException { return LockToken.attemptLock(myStateLock, Registry.intValue("ide.tree.uiLockAttempt")); } @Nonnull private LockToken acquireLock() { return LockToken.acquireLock(myStateLock); } @Nonnull public ActionCallback batch(@Nonnull final Progressive progressive) { assertIsDispatchThread(); EmptyProgressIndicator indicator = new EmptyProgressIndicator(); final ActionCallback callback = new ActionCallback(); myBatchIndicators.put(progressive, indicator); myBatchCallbacks.put(progressive, callback); try { progressive.run(indicator); } catch (ProcessCanceledException e) { resetToReadyNow().doWhenProcessed(new TreeRunnable("AbstractTreeUi.batch: catch") { @Override public void perform() { callback.setRejected(); } }); return callback; } finally { if (isReleased()) return ActionCallback.REJECTED; _getReady().doWhenDone(new TreeRunnable("AbstractTreeUi.batch: finally") { @Override public void perform() { if (myBatchIndicators.containsKey(progressive)) { ProgressIndicator indicator = myBatchIndicators.remove(progressive); myBatchCallbacks.remove(progressive); if (indicator.isCanceled()) { callback.setRejected(); } else { callback.setDone(); } } else { callback.setRejected(); } } }); maybeReady(); } return callback; } boolean isCancelProcessed() { return myCancelRequest.get() || myResettingToReadyNow.get(); } boolean isToPaintSelection() { return isReady(true) || !mySelectionIsAdjusted; } boolean isReleaseRequested() { return myReleaseRequested; } public void executeUserRunnable(@Nonnull Runnable runnable) { try { myUserRunnables.add(runnable); runnable.run(); } finally { myUserRunnables.remove(runnable); } } static class ElementNode extends DefaultMutableTreeNode { Set<Object> myElements = new HashSet<>(); AbstractTreeUi myUi; ElementNode(AbstractTreeUi ui, NodeDescriptor descriptor) { super(descriptor); myUi = ui; } @Override public void insert(final MutableTreeNode newChild, final int childIndex) { super.insert(newChild, childIndex); final Object element = myUi.getElementFor(newChild); if (element != null) { myElements.add(element); } } @Override public void remove(final int childIndex) { final TreeNode node = getChildAt(childIndex); super.remove(childIndex); final Object element = myUi.getElementFor(node); if (element != null) { myElements.remove(element); } } boolean isValidChild(Object childElement) { return myElements.contains(childElement); } @Override public String toString() { return String.valueOf(getUserObject()); } } private boolean isUpdatingParent(DefaultMutableTreeNode kid) { return getUpdatingParent(kid) != null; } @Nullable private DefaultMutableTreeNode getUpdatingParent(DefaultMutableTreeNode kid) { DefaultMutableTreeNode eachParent = kid; while (eachParent != null) { if (isUpdatingChildrenNow(eachParent)) return eachParent; eachParent = (DefaultMutableTreeNode)eachParent.getParent(); } return null; } private boolean isLoadedInBackground(Object element) { return getLoadedInBackground(element) != null; } private UpdateInfo getLoadedInBackground(Object element) { synchronized (myLoadedInBackground) { return isNodeNull(element) ? null : myLoadedInBackground.get(element); } } private void addToLoadedInBackground(Object element, UpdateInfo info) { if (isNodeNull(element)) return; synchronized (myLoadedInBackground) { warnMap("put into myLoadedInBackground: ", myLoadedInBackground); myLoadedInBackground.put(element, info); } } private void removeFromLoadedInBackground(final Object element) { if (isNodeNull(element)) return; synchronized (myLoadedInBackground) { warnMap("remove from myLoadedInBackground: ", myLoadedInBackground); myLoadedInBackground.remove(element); } } private boolean isLoadingInBackgroundNow() { synchronized (myLoadedInBackground) { return !myLoadedInBackground.isEmpty(); } } private void queueBackgroundUpdate(@Nonnull final UpdateInfo updateInfo, @Nonnull final DefaultMutableTreeNode node) { assertIsDispatchThread(); final Object oldElementFromDescriptor = getElementFromDescriptor(updateInfo.getDescriptor()); if (isNodeNull(oldElementFromDescriptor)) return; UpdateInfo loaded = getLoadedInBackground(oldElementFromDescriptor); if (loaded != null) { loaded.apply(updateInfo); return; } addToLoadedInBackground(oldElementFromDescriptor, updateInfo); maybeSetBusyAndScheduleWaiterForReady(true, oldElementFromDescriptor); if (!isNodeBeingBuilt(node)) { LoadingNode loadingNode = new LoadingNode(getLoadingNodeText()); myTreeModel.insertNodeInto(loadingNode, node, node.getChildCount()); } removeFromUnbuilt(node); final Ref<LoadedChildren> children = new Ref<>(); final Ref<Object> elementFromDescriptor = new Ref<>(); final DefaultMutableTreeNode[] nodeToProcessActions = new DefaultMutableTreeNode[1]; final TreeConsumer<Void> finalizeRunnable = new TreeConsumer<Void>("AbstractTreeUi.queueBackgroundUpdate: finalize") { @Override public void perform() { invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.queueBackgroundUpdate: finalize later") { @Override public void perform() { if (isReleased()) return; removeLoading(node, false); removeFromLoadedInBackground(elementFromDescriptor.get()); removeFromLoadedInBackground(oldElementFromDescriptor); if (nodeToProcessActions[0] != null) { processNodeActionsIfReady(nodeToProcessActions[0]); } } }); } }; Runnable buildRunnable = new TreeRunnable("AbstractTreeUi.queueBackgroundUpdate: build") { @Override public void perform() { if (updateInfo.getPass().isExpired()) { finalizeRunnable.run(); return; } if (!updateInfo.isDescriptorIsUpToDate()) { update(updateInfo.getDescriptor(), true); } if (!updateInfo.isUpdateChildren()) { nodeToProcessActions[0] = node; return; } Object element = getElementFromDescriptor(updateInfo.getDescriptor()); if (element == null) { removeFromLoadedInBackground(oldElementFromDescriptor); finalizeRunnable.run(); return; } elementFromDescriptor.set(element); Object[] loadedElements = getChildrenFor(element); final LoadedChildren loaded = new LoadedChildren(loadedElements); for (final Object each : loadedElements) { NodeDescriptor existingDesc = getDescriptorFrom(getNodeForElement(each, true)); final NodeDescriptor eachChildDescriptor = isValid(existingDesc, updateInfo.getDescriptor()) ? existingDesc : getTreeStructure().createDescriptor(each, updateInfo.getDescriptor()); execute(new TreeRunnable("AbstractTreeUi.queueBackgroundUpdate") { @Override public void perform() { try { loaded.putDescriptor(each, eachChildDescriptor, update(eachChildDescriptor, true).blockingGet(0)); } catch (TimeoutException | ExecutionException e) { LOG.error(e); } } }); } children.set(loaded); } @Nonnull @NonNls @Override public String toString() { return "runnable=" + oldElementFromDescriptor; } }; Runnable updateRunnable = new TreeRunnable("AbstractTreeUi.queueBackgroundUpdate: update") { @Override public void perform() { if (updateInfo.getPass().isExpired()) { finalizeRunnable.run(); return; } if (children.get() == null) { finalizeRunnable.run(); return; } if (isRerunNeeded(updateInfo.getPass())) { removeFromLoadedInBackground(elementFromDescriptor.get()); getUpdater().requeue(updateInfo.getPass()); return; } removeFromLoadedInBackground(elementFromDescriptor.get()); if (myUnbuiltNodes.contains(node)) { Pair<Boolean, LoadedChildren> unbuilt = processUnbuilt(node, updateInfo.getDescriptor(), updateInfo.getPass(), isExpanded(node, updateInfo.isWasExpanded()), children.get()); if (unbuilt.getFirst()) { nodeToProcessActions[0] = node; return; } } ActionCallback callback = updateNodeChildren(node, updateInfo.getPass(), children.get(), true, updateInfo.isCanSmartExpand(), updateInfo.isForceUpdate(), true, true); callback.doWhenDone(new TreeRunnable("AbstractTreeUi.queueBackgroundUpdate: on done updateNodeChildren") { @Override public void perform() { if (isRerunNeeded(updateInfo.getPass())) { getUpdater().requeue(updateInfo.getPass()); return; } Object element = elementFromDescriptor.get(); if (element != null) { removeLoading(node, false); nodeToProcessActions[0] = node; } } }); } }; queueToBackground(buildRunnable, updateRunnable).onSuccess(finalizeRunnable).onError(new TreeConsumer<Throwable>("AbstractTreeUi.queueBackgroundUpdate: on rejected") { @Override public void perform() { updateInfo.getPass().expire(); } }); } private boolean isExpanded(@Nonnull DefaultMutableTreeNode node, boolean isExpanded) { return isExpanded || myTree.isExpanded(getPathFor(node)); } private void removeLoading(@Nonnull DefaultMutableTreeNode parent, boolean forced) { if (!forced && myUnbuiltNodes.contains(parent) && !myCancelledBuild.containsKey(parent)) { return; } boolean reallyRemoved = false; for (int i = 0; i < parent.getChildCount(); i++) { TreeNode child = parent.getChildAt(i); if (removeIfLoading(child)) { reallyRemoved = true; i } } maybeReady(); if (reallyRemoved) { nodeStructureChanged(parent); } } private void processNodeActionsIfReady(@Nonnull final DefaultMutableTreeNode node) { assertIsDispatchThread(); if (isNodeBeingBuilt(node)) return; NodeDescriptor descriptor = getDescriptorFrom(node); if (descriptor == null) return; if (isYeildingNow()) { myPendingNodeActions.add(node); return; } final Object element = getElementFromDescriptor(descriptor); boolean childrenReady = !isLoadedInBackground(element) && !isUpdatingChildrenNow(node); processActions(node, element, myNodeActions, childrenReady ? myNodeChildrenActions : null); if (childrenReady) { processActions(node, element, myNodeChildrenActions, null); } warnMap("myNodeActions: processNodeActionsIfReady: ", myNodeActions); warnMap("myNodeChildrenActions: processNodeActionsIfReady: ", myNodeChildrenActions); if (!isUpdatingParent(node) && !isWorkerBusy()) { final UpdaterTreeState state = myUpdaterState; if (myNodeActions.isEmpty() && state != null && !state.isProcessingNow()) { if (canInitiateNewActivity()) { if (!state.restore(childrenReady ? node : null)) { setUpdaterState(state); } } } } maybeReady(); } private static void processActions(@Nonnull DefaultMutableTreeNode node, Object element, @Nonnull final Map<Object, List<NodeAction>> nodeActions, @Nullable final Map<Object, List<NodeAction>> secondaryNodeAction) { final List<NodeAction> actions = nodeActions.get(element); if (actions != null) { nodeActions.remove(element); List<NodeAction> secondary = secondaryNodeAction != null ? secondaryNodeAction.get(element) : null; for (NodeAction each : actions) { if (secondary != null) { secondary.remove(each); } each.onReady(node); } } } private boolean canSmartExpand(DefaultMutableTreeNode node, boolean canSmartExpand) { if (!canInitiateNewActivity()) return false; if (!getBuilder().isSmartExpand()) return false; boolean smartExpand = canSmartExpand && !myNotForSmartExpand.contains(node); Object element = getElementFor(node); return smartExpand && element != null && validateAutoExpand(true, element); } private void processSmartExpand(@Nonnull final DefaultMutableTreeNode node, final boolean canSmartExpand, boolean forced) { if (!canInitiateNewActivity()) return; if (!getBuilder().isSmartExpand()) return; boolean can = canSmartExpand(node, canSmartExpand); if (!can && !forced) return; if (isNodeBeingBuilt(node) && !forced) { addNodeAction(getElementFor(node), true, node1 -> processSmartExpand(node1, canSmartExpand, true)); } else { TreeNode child = getChildForSmartExpand(node); if (child != null) { final TreePath childPath = new TreePath(node.getPath()).pathByAddingChild(child); processInnerChange(new TreeRunnable("AbstractTreeUi.processSmartExpand") { @Override public void perform() { myTree.expandPath(childPath); } }); } } } @Nullable private static TreeNode getChildForSmartExpand(@Nonnull DefaultMutableTreeNode node) { int realChildCount = 0; TreeNode nodeToExpand = null; for (int i = 0; i < node.getChildCount(); i++) { TreeNode eachChild = node.getChildAt(i); if (!isLoadingNode(eachChild)) { realChildCount++; if (nodeToExpand == null) { nodeToExpand = eachChild; } } if (realChildCount > 1) { nodeToExpand = null; break; } } return nodeToExpand; } public static boolean isLoadingChildrenFor(final Object nodeObject) { if (!(nodeObject instanceof DefaultMutableTreeNode)) return false; DefaultMutableTreeNode node = (DefaultMutableTreeNode)nodeObject; int loadingNodes = 0; for (int i = 0; i < Math.min(node.getChildCount(), 2); i++) { TreeNode child = node.getChildAt(i); if (isLoadingNode(child)) { loadingNodes++; } } return loadingNodes > 0 && loadingNodes == node.getChildCount(); } boolean isParentLoadingInBackground(@Nonnull Object nodeObject) { return getParentLoadingInBackground(nodeObject) != null; } @Nullable private DefaultMutableTreeNode getParentLoadingInBackground(@Nonnull Object nodeObject) { if (!(nodeObject instanceof DefaultMutableTreeNode)) return null; DefaultMutableTreeNode node = (DefaultMutableTreeNode)nodeObject; TreeNode eachParent = node.getParent(); while (eachParent != null) { eachParent = eachParent.getParent(); if (eachParent instanceof DefaultMutableTreeNode) { final Object eachElement = getElementFor(eachParent); if (isLoadedInBackground(eachElement)) return (DefaultMutableTreeNode)eachParent; } } return null; } private static String getLoadingNodeText() { return IdeBundle.message("progress.searching"); } @Nonnull private Promise<?> processExistingNode(@Nonnull final DefaultMutableTreeNode childNode, final NodeDescriptor childDescriptor, @Nonnull final DefaultMutableTreeNode parentNode, @Nonnull final MutualMap<Object, Integer> elementToIndexMap, @Nonnull final TreeUpdatePass pass, final boolean canSmartExpand, final boolean forceUpdate, @Nullable LoadedChildren parentPreloadedChildren) { if (pass.isExpired()) { return Promises.<Void>rejectedPromise(); } if (childDescriptor == null) { pass.expire(); return Promises.<Void>rejectedPromise(); } final Object oldElement = getElementFromDescriptor(childDescriptor); if (isNodeNull(oldElement)) { // if a tree node with removed element was not properly removed from a tree model // we must not ignore this situation and should remove a wrong node removeNodeFromParent(childNode, true); doUpdateNode(parentNode); return Promises.<Void>resolvedPromise(); } Promise<Boolean> update; if (parentPreloadedChildren != null && parentPreloadedChildren.getDescriptor(oldElement) == childDescriptor) { update = Promises.resolvedPromise(parentPreloadedChildren.isUpdated(oldElement)); } else { update = update(childDescriptor, false); } final AsyncPromise<Void> result = new AsyncPromise<>(); final Ref<NodeDescriptor> childDesc = new Ref<>(childDescriptor); update.onSuccess(isChanged -> { final AtomicBoolean changes = new AtomicBoolean(isChanged); final AtomicBoolean forceRemapping = new AtomicBoolean(); final Ref<Object> newElement = new Ref<>(getElementFromDescriptor(childDesc.get())); final Integer index = newElement.get() == null ? null : elementToIndexMap.getValue(getElementFromDescriptor(childDesc.get())); Promise<Boolean> promise; if (index == null) { promise = Promises.resolvedPromise(false); } else { final Object elementFromMap = elementToIndexMap.getKey(index); if (elementFromMap != newElement.get() && elementFromMap.equals(newElement.get())) { if (isInStructure(elementFromMap) && isInStructure(newElement.get())) { final AsyncPromise<Boolean> updateIndexDone = new AsyncPromise<>(); promise = updateIndexDone; NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode); if (parentDescriptor != null) { childDesc.set(getTreeStructure().createDescriptor(elementFromMap, parentDescriptor)); NodeDescriptor oldDesc = getDescriptorFrom(childNode); if (isValid(oldDesc)) { childDesc.get().applyFrom(oldDesc); } childNode.setUserObject(childDesc.get()); newElement.set(elementFromMap); forceRemapping.set(true); update(childDesc.get(), false).onSuccess(isChanged1 -> { changes.set(isChanged1); updateIndexDone.setResult(isChanged1); }); } // todo why we don't process promise here? } else { promise = Promises.resolvedPromise(changes.get()); } } else { promise = Promises.resolvedPromise(changes.get()); } promise.onSuccess(new TreeConsumer<Boolean>("AbstractTreeUi.processExistingNode: on done index updating after update") { @Override public void perform() { if (childDesc.get().getIndex() != index.intValue()) { changes.set(true); } childDesc.get().setIndex(index.intValue()); } }); } promise.onSuccess(new TreeConsumer<Boolean>("AbstractTreeUi.processExistingNode: on done index updating") { @Override public void perform() { if (!oldElement.equals(newElement.get()) || forceRemapping.get()) { removeMapping(oldElement, childNode, newElement.get()); Object newE = newElement.get(); if (!isNodeNull(newE)) { createMapping(newE, childNode); } NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode); if (parentDescriptor != null) { parentDescriptor.setChildrenSortingStamp(-1); } } if (index == null) { int selectedIndex = -1; if (TreeBuilderUtil.isNodeOrChildSelected(myTree, childNode)) { selectedIndex = parentNode.getIndex(childNode); } if (childNode.getParent() instanceof DefaultMutableTreeNode) { final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)childNode.getParent(); if (myTree.isExpanded(new TreePath(parent.getPath()))) { if (parent.getChildCount() == 1 && parent.getChildAt(0) == childNode) { insertLoadingNode(parent, false); } } } Object disposedElement = getElementFor(childNode); removeNodeFromParent(childNode, selectedIndex >= 0); disposeNode(childNode); adjustSelectionOnChildRemove(parentNode, selectedIndex, disposedElement); result.setResult(null); } else { elementToIndexMap.remove(getElementFromDescriptor(childDesc.get())); updateNodeChildren(childNode, pass, null, false, canSmartExpand, forceUpdate, true, true).doWhenDone(() -> result.setResult(null)); } } }); }); return result; } private void adjustSelectionOnChildRemove(@Nonnull DefaultMutableTreeNode parentNode, int selectedIndex, Object disposedElement) { if (selectedIndex >= 0 && !getSelectedElements().isEmpty()) return; DefaultMutableTreeNode node = disposedElement == null ? null : getNodeForElement(disposedElement, false); if (node != null && isValidForSelectionAdjusting(node)) { Object newElement = getElementFor(node); addSelectionPath(getPathFor(node), true, getExpiredElementCondition(newElement), disposedElement); return; } if (selectedIndex >= 0) { if (parentNode.getChildCount() > 0) { if (parentNode.getChildCount() > selectedIndex) { TreeNode newChildNode = parentNode.getChildAt(selectedIndex); if (isValidForSelectionAdjusting(newChildNode)) { addSelectionPath(new TreePath(myTreeModel.getPathToRoot(newChildNode)), true, getExpiredElementCondition(disposedElement), disposedElement); } } else { TreeNode newChild = parentNode.getChildAt(parentNode.getChildCount() - 1); if (isValidForSelectionAdjusting(newChild)) { addSelectionPath(new TreePath(myTreeModel.getPathToRoot(newChild)), true, getExpiredElementCondition(disposedElement), disposedElement); } } } else { addSelectionPath(new TreePath(myTreeModel.getPathToRoot(parentNode)), true, getExpiredElementCondition(disposedElement), disposedElement); } } } private boolean isValidForSelectionAdjusting(@Nonnull TreeNode node) { if (!myTree.isRootVisible() && getRootNode() == node) return false; if (isLoadingNode(node)) return true; final Object elementInTree = getElementFor(node); if (elementInTree == null) return false; final TreeNode parentNode = node.getParent(); final Object parentElementInTree = getElementFor(parentNode); if (parentElementInTree == null) return false; final Object parentElement = getTreeStructure().getParentElement(elementInTree); return parentElementInTree.equals(parentElement); } @Nonnull private Condition getExpiredElementCondition(final Object element) { return o -> isInStructure(element); } private void addSelectionPath(@Nonnull final TreePath path, final boolean isAdjustedSelection, final Condition isExpiredAdjustment, @Nullable final Object adjustmentCause) { processInnerChange(new TreeRunnable("AbstractTreeUi.addSelectionPath") { @Override public void perform() { TreePath toSelect = null; if (isLoadingNode(path.getLastPathComponent())) { final TreePath parentPath = path.getParentPath(); if (parentPath != null && isValidForSelectionAdjusting((TreeNode)parentPath.getLastPathComponent())) { toSelect = parentPath; } } else { toSelect = path; } if (toSelect != null) { mySelectionIsAdjusted = isAdjustedSelection; myTree.addSelectionPath(toSelect); if (isAdjustedSelection && myUpdaterState != null) { final Object toSelectElement = getElementFor(toSelect.getLastPathComponent()); myUpdaterState.addAdjustedSelection(toSelectElement, isExpiredAdjustment, adjustmentCause); } } } }); } @Nonnull private static TreePath getPathFor(@Nonnull TreeNode node) { if (node instanceof DefaultMutableTreeNode) { return new TreePath(((DefaultMutableTreeNode)node).getPath()); } else { List<TreeNode> nodes = new ArrayList<>(); TreeNode eachParent = node; while (eachParent != null) { nodes.add(eachParent); eachParent = eachParent.getParent(); } return new TreePath(ArrayUtil.toObjectArray(nodes)); } } private void removeNodeFromParent(@Nonnull final MutableTreeNode node, final boolean willAdjustSelection) { processInnerChange(new TreeRunnable("AbstractTreeUi.removeNodeFromParent") { @Override public void perform() { if (willAdjustSelection) { final TreePath path = getPathFor(node); if (myTree.isPathSelected(path)) { myTree.removeSelectionPath(path); } } if (node.getParent() != null) { myTreeModel.removeNodeFromParent(node); } } }); } private void expandPath(@Nonnull final TreePath path, final boolean canSmartExpand) { processInnerChange(new TreeRunnable("AbstractTreeUi.expandPath") { @Override public void perform() { if (path.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); if (node.getChildCount() > 0 && !myTree.isExpanded(path)) { if (!canSmartExpand) { myNotForSmartExpand.add(node); } try { myRequestedExpand = path; myTree.expandPath(path); processSmartExpand(node, canSmartExpand, false); } finally { myNotForSmartExpand.remove(node); myRequestedExpand = null; } } else { processNodeActionsIfReady(node); } } } }); } private void processInnerChange(Runnable runnable) { if (myUpdaterState == null) { setUpdaterState(new UpdaterTreeState(this)); } myUpdaterState.process(runnable); } private boolean isInnerChange() { return myUpdaterState != null && myUpdaterState.isProcessingNow() && myUserRunnables.isEmpty(); } private void makeLoadingOrLeafIfNoChildren(@Nonnull final DefaultMutableTreeNode node) { TreePath path = getPathFor(node); insertLoadingNode(node, true); final NodeDescriptor descriptor = getDescriptorFrom(node); if (descriptor == null) return; descriptor.setChildrenSortingStamp(-1); if (getBuilder().isAlwaysShowPlus(descriptor)) return; TreePath parentPath = path.getParentPath(); if (myTree.isVisible(path) || parentPath != null && myTree.isExpanded(parentPath)) { if (myTree.isExpanded(path)) { addSubtreeToUpdate(node); } else { insertLoadingNode(node, false); } } } /** * Indicates whether the given {@code descriptor} is valid * and its parent is equal to the specified {@code parent}. * * @param descriptor a descriptor to test * @param parent an expected parent for the testing descriptor * @return {@code true} if the specified descriptor is valid */ private boolean isValid(NodeDescriptor descriptor, NodeDescriptor parent) { if (descriptor == null) return false; if (parent != null && parent != descriptor.getParentDescriptor()) return false; return isValid(getElementFromDescriptor(descriptor)); } private boolean isValid(@Nullable NodeDescriptor descriptor) { return descriptor != null && isValid(getElementFromDescriptor(descriptor)); } private boolean isValid(Object element) { if (isNodeNull(element)) return false; if (element instanceof ValidateableNode) { if (!((ValidateableNode)element).isValid()) return false; } return getBuilder().validateNode(element); } private void insertLoadingNode(final DefaultMutableTreeNode node, boolean addToUnbuilt) { if (!isLoadingChildrenFor(node)) { myTreeModel.insertNodeInto(new LoadingNode(), node, 0); } if (addToUnbuilt) { addToUnbuilt(node); } } @Nonnull private Promise<Void> queueToBackground(@Nonnull final Runnable bgBuildAction, @Nullable final Runnable edtPostRunnable) { if (!canInitiateNewActivity()) return Promises.rejectedPromise(); final AsyncPromise<Void> result = new AsyncPromise<>(); final AtomicReference<ProcessCanceledException> fail = new AtomicReference<>(); final Runnable finalizer = new TreeRunnable("AbstractTreeUi.queueToBackground: finalizer") { @Override public void perform() { ProcessCanceledException exception = fail.get(); if (exception == null) { result.setResult(null); } else { result.setError(exception); } } }; registerWorkerTask(bgBuildAction); final Runnable pooledThreadWithProgressRunnable = new TreeRunnable("AbstractTreeUi.queueToBackground: progress") { @Override public void perform() { try { final AbstractTreeBuilder builder = getBuilder(); if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } builder.runBackgroundLoading(new TreeRunnable("AbstractTreeUi.queueToBackground: background") { @Override public void perform() { assertNotDispatchThread(); try { if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } execute(bgBuildAction); if (edtPostRunnable != null) { builder.updateAfterLoadedInBackground(new TreeRunnable("AbstractTreeUi.queueToBackground: update after") { @Override public void perform() { try { assertIsDispatchThread(); if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } execute(edtPostRunnable); } catch (ProcessCanceledException e) { fail.set(e); cancelUpdate(); } finally { unregisterWorkerTask(bgBuildAction, finalizer); } } }); } else { unregisterWorkerTask(bgBuildAction, finalizer); } } catch (ProcessCanceledException e) { fail.set(e); unregisterWorkerTask(bgBuildAction, finalizer); cancelUpdate(); } catch (Throwable t) { unregisterWorkerTask(bgBuildAction, finalizer); throw new RuntimeException(t); } } }); } catch (ProcessCanceledException e) { unregisterWorkerTask(bgBuildAction, finalizer); cancelUpdate(); } } }; Runnable pooledThreadRunnable = new TreeRunnable("AbstractTreeUi.queueToBackground") { @Override public void perform() { try { if (myProgress != null) { ProgressManager.getInstance().runProcess(pooledThreadWithProgressRunnable, myProgress); } else { execute(pooledThreadWithProgressRunnable); } } catch (ProcessCanceledException e) { fail.set(e); unregisterWorkerTask(bgBuildAction, finalizer); cancelUpdate(); } } }; if (isPassthroughMode()) { execute(pooledThreadRunnable); } else { myWorker.addFirst(pooledThreadRunnable); } return result; } private void registerWorkerTask(@Nonnull Runnable runnable) { synchronized (myActiveWorkerTasks) { myActiveWorkerTasks.add(runnable); } } private void unregisterWorkerTask(@Nonnull Runnable runnable, @Nullable Runnable finalizeRunnable) { boolean wasRemoved; synchronized (myActiveWorkerTasks) { wasRemoved = myActiveWorkerTasks.remove(runnable); } if (wasRemoved && finalizeRunnable != null) { finalizeRunnable.run(); } invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.unregisterWorkerTask") { @Override public void perform() { maybeReady(); } }); } private boolean isWorkerBusy() { synchronized (myActiveWorkerTasks) { return !myActiveWorkerTasks.isEmpty(); } } private void clearWorkerTasks() { synchronized (myActiveWorkerTasks) { myActiveWorkerTasks.clear(); } } private void updateNodeImageAndPosition(@Nonnull final DefaultMutableTreeNode node) { NodeDescriptor descriptor = getDescriptorFrom(node); if (descriptor == null) return; if (getElementFromDescriptor(descriptor) == null) return; nodeChanged(node); } private void nodeChanged(final DefaultMutableTreeNode node) { invokeLaterIfNeeded(true, new TreeRunnable("AbstractTreeUi.nodeChanged") { @Override public void perform() { myTreeModel.nodeChanged(node); } }); } private void nodeStructureChanged(final DefaultMutableTreeNode node) { invokeLaterIfNeeded(true, new TreeRunnable("AbstractTreeUi.nodeStructureChanged") { @Override public void perform() { myTreeModel.nodeStructureChanged(node); } }); } public DefaultTreeModel getTreeModel() { return myTreeModel; } private void insertNodesInto(@Nonnull final List<TreeNode> toInsert, @Nonnull final DefaultMutableTreeNode parentNode) { sortChildren(parentNode, toInsert, false, true); final List<TreeNode> all = new ArrayList<>(toInsert.size() + parentNode.getChildCount()); all.addAll(toInsert); all.addAll(TreeUtil.listChildren(parentNode)); if (!toInsert.isEmpty()) { sortChildren(parentNode, all, true, true); int[] newNodeIndices = new int[toInsert.size()]; int eachNewNodeIndex = 0; TreeMap<Integer, TreeNode> insertSet = new TreeMap<>(); for (int i = 0; i < toInsert.size(); i++) { TreeNode eachNewNode = toInsert.get(i); while (all.get(eachNewNodeIndex) != eachNewNode) { eachNewNodeIndex++; } newNodeIndices[i] = eachNewNodeIndex; insertSet.put(eachNewNodeIndex, eachNewNode); } for (Map.Entry<Integer, TreeNode> entry : insertSet.entrySet()) { TreeNode eachNode = entry.getValue(); Integer index = entry.getKey(); parentNode.insert((MutableTreeNode)eachNode, index); } myTreeModel.nodesWereInserted(parentNode, newNodeIndices); } else { List<TreeNode> before = new ArrayList<>(all); sortChildren(parentNode, all, true, false); if (!before.equals(all)) { processInnerChange(new TreeRunnable("AbstractTreeUi.insertNodesInto") { @Override public void perform() { Enumeration<TreePath> expanded = getTree().getExpandedDescendants(getPathFor(parentNode)); TreePath[] selected = getTree().getSelectionModel().getSelectionPaths(); parentNode.removeAllChildren(); for (TreeNode each : all) { parentNode.add((MutableTreeNode)each); } nodeStructureChanged(parentNode); if (expanded != null) { while (expanded.hasMoreElements()) { expandSilently(expanded.nextElement()); } } if (selected != null) { for (TreePath each : selected) { if (!getTree().getSelectionModel().isPathSelected(each)) { addSelectionSilently(each); } } } } }); } } } private void sortChildren(@Nonnull DefaultMutableTreeNode node, @Nonnull List<TreeNode> children, boolean updateStamp, boolean forceSort) { NodeDescriptor descriptor = getDescriptorFrom(node); assert descriptor != null; if (descriptor.getChildrenSortingStamp() >= getComparatorStamp() && !forceSort) return; if (!children.isEmpty()) { try { getBuilder().sortChildren(myNodeComparator, node, children); } catch (IllegalArgumentException exception) { StringBuilder sb = new StringBuilder("cannot sort children in ").append(toString()); children.forEach(child -> sb.append('\n').append(child)); throw new IllegalArgumentException(sb.toString(), exception); } } if (updateStamp) { descriptor.setChildrenSortingStamp(getComparatorStamp()); } } private void disposeNode(@Nonnull DefaultMutableTreeNode node) { TreeNode parent = node.getParent(); if (parent instanceof DefaultMutableTreeNode) { addToUnbuilt((DefaultMutableTreeNode)parent); } if (node.getChildCount() > 0) { for (DefaultMutableTreeNode _node = (DefaultMutableTreeNode)node.getFirstChild(); _node != null; _node = _node.getNextSibling()) { disposeNode(_node); } } removeFromUpdatingChildren(node); removeFromUnbuilt(node); removeFromCancelled(node); if (isLoadingNode(node)) return; NodeDescriptor descriptor = getDescriptorFrom(node); if (descriptor == null) return; final Object element = getElementFromDescriptor(descriptor); if (!isNodeNull(element)) { removeMapping(element, node, null); } myAutoExpandRoots.remove(element); node.setUserObject(null); node.removeAllChildren(); } public boolean addSubtreeToUpdate(@Nonnull final DefaultMutableTreeNode root) { return addSubtreeToUpdate(root, true); } public boolean addSubtreeToUpdate(@Nonnull final DefaultMutableTreeNode root, boolean updateStructure) { return addSubtreeToUpdate(root, null, updateStructure); } public boolean addSubtreeToUpdate(@Nonnull final DefaultMutableTreeNode root, final Runnable runAfterUpdate) { return addSubtreeToUpdate(root, runAfterUpdate, true); } public boolean addSubtreeToUpdate(@Nonnull final DefaultMutableTreeNode root, @Nullable final Runnable runAfterUpdate, final boolean updateStructure) { final Object element = getElementFor(root); final boolean alwaysLeaf = element != null && getTreeStructure().isAlwaysLeaf(element); final TreeUpdatePass updatePass; if (alwaysLeaf) { removeFromUnbuilt(root); removeLoading(root, true); updatePass = new TreeUpdatePass(root).setUpdateChildren(false); } else { updatePass = new TreeUpdatePass(root).setUpdateStructure(updateStructure).setUpdateStamp(-1); } final AbstractTreeUpdater updater = getUpdater(); updater.runAfterUpdate(runAfterUpdate); updater.addSubtreeToUpdate(updatePass); return !alwaysLeaf; } boolean wasRootNodeInitialized() { return myRootNodeWasQueuedToInitialize && myRootNodeInitialized; } public void select(@Nonnull final Object[] elements, @Nullable final Runnable onDone) { select(elements, onDone, false); } public void select(@Nonnull final Object[] elements, @Nullable final Runnable onDone, boolean addToSelection) { select(elements, onDone, addToSelection, false); } public void select(@Nonnull final Object[] elements, @Nullable final Runnable onDone, boolean addToSelection, boolean deferred) { _select(elements, onDone, addToSelection, true, false, true, deferred, false, false); } void _select(@Nonnull final Object[] elements, final Runnable onDone, final boolean addToSelection, final boolean checkIfInStructure) { _select(elements, onDone, addToSelection, true, checkIfInStructure, true, false, false, false); } void _select(@Nonnull final Object[] elements, @Nonnull Runnable onDone) { _select(elements, onDone, false, true, true, false, false, false, false); } public void userSelect(@Nonnull final Object[] elements, final Runnable onDone, final boolean addToSelection, boolean scroll) { _select(elements, onDone, addToSelection, true, false, scroll, false, true, true); } void _select(@Nonnull final Object[] elements, final Runnable onDone, final boolean addToSelection, final boolean checkCurrentSelection, final boolean checkIfInStructure, final boolean scrollToVisible, final boolean deferred, final boolean canSmartExpand, final boolean mayQueue) { assertIsDispatchThread(); AbstractTreeUpdater updater = getUpdater(); if (mayQueue && updater != null) { updater.queueSelection(new SelectionRequest(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, scrollToVisible, deferred, canSmartExpand)); return; } boolean willAffectSelection = elements.length > 0 || addToSelection; if (!willAffectSelection) { runDone(onDone); maybeReady(); return; } final boolean oldCanProcessDeferredSelection = myCanProcessDeferredSelections; if (!deferred && wasRootNodeInitialized()) { _getReady().doWhenDone(new TreeRunnable("AbstractTreeUi._select: on done getReady") { @Override public void perform() { myCanProcessDeferredSelections = false; } }); } if (!checkDeferred(deferred, onDone)) return; if (!deferred && oldCanProcessDeferredSelection && !myCanProcessDeferredSelections) { if (!addToSelection) { getTree().clearSelection(); } } runDone(new TreeRunnable("AbstractTreeUi._select") { @Override public void perform() { try { if (!checkDeferred(deferred, onDone)) return; final Set<Object> currentElements = getSelectedElements(); if (checkCurrentSelection && !currentElements.isEmpty() && elements.length == currentElements.size()) { boolean runSelection = false; for (Object eachToSelect : elements) { if (!currentElements.contains(eachToSelect)) { runSelection = true; break; } } if (!runSelection) { selectVisible(elements[0], onDone, false, false, scrollToVisible); return; } } clearSelection(); Set<Object> toSelect = new THashSet<>(); ContainerUtil.addAllNotNull(toSelect, elements); if (addToSelection) { ContainerUtil.addAllNotNull(toSelect, currentElements); } if (checkIfInStructure) { toSelect.removeIf(each -> !isInStructure(each)); } final Object[] elementsToSelect = ArrayUtil.toObjectArray(toSelect); if (wasRootNodeInitialized()) { final int[] originalRows = myTree.getSelectionRows(); if (!addToSelection) { clearSelection(); } addNext(elementsToSelect, 0, new TreeRunnable("AbstractTreeUi._select: addNext") { @Override public void perform() { if (getTree().isSelectionEmpty()) { processInnerChange(new TreeRunnable("AbstractTreeUi._select: addNext: processInnerChange") { @Override public void perform() { restoreSelection(currentElements); } }); } runDone(onDone); } }, originalRows, deferred, scrollToVisible, canSmartExpand); } else { addToDeferred(elementsToSelect, onDone, addToSelection); } } finally { maybeReady(); } } }); } private void clearSelection() { mySelectionIsBeingAdjusted = true; try { myTree.clearSelection(); } finally { mySelectionIsBeingAdjusted = false; } } boolean isSelectionBeingAdjusted() { return mySelectionIsBeingAdjusted; } private void restoreSelection(@Nonnull Set<Object> selection) { for (Object each : selection) { DefaultMutableTreeNode node = getNodeForElement(each, false); if (node != null && isValidForSelectionAdjusting(node)) { addSelectionPath(getPathFor(node), false, null, null); } } } private void addToDeferred(@Nonnull final Object[] elementsToSelect, final Runnable onDone, final boolean addToSelection) { if (!addToSelection) { myDeferredSelections.clear(); } myDeferredSelections.add(new TreeRunnable("AbstractTreeUi.addToDeferred") { @Override public void perform() { select(elementsToSelect, onDone, addToSelection, true); } }); } private boolean checkDeferred(boolean isDeferred, @Nullable Runnable onDone) { if (!isDeferred || myCanProcessDeferredSelections || !wasRootNodeInitialized()) { return true; } else { runDone(onDone); return false; } } @Nonnull final Set<Object> getSelectedElements() { TreePath[] paths = myTree.getSelectionPaths(); Set<Object> result = ContainerUtil.newLinkedHashSet(); if (paths != null) { for (TreePath eachPath : paths) { if (eachPath.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode eachNode = (DefaultMutableTreeNode)eachPath.getLastPathComponent(); if (eachNode == myRootNode && !myTree.isRootVisible()) continue; Object eachElement = getElementFor(eachNode); if (eachElement != null) { result.add(eachElement); } } } } return result; } private void addNext(@Nonnull final Object[] elements, final int i, @Nullable final Runnable onDone, final int[] originalRows, final boolean deferred, final boolean scrollToVisible, final boolean canSmartExpand) { if (i >= elements.length) { if (myTree.isSelectionEmpty()) { myTree.setSelectionRows(originalRows); } runDone(onDone); } else { if (!checkDeferred(deferred, onDone)) { return; } doSelect(elements[i], new TreeRunnable("AbstractTreeUi.addNext") { @Override public void perform() { if (!checkDeferred(deferred, onDone)) return; addNext(elements, i + 1, onDone, originalRows, deferred, scrollToVisible, canSmartExpand); } }, deferred, i == 0, scrollToVisible, canSmartExpand); } } public void select(@Nullable Object element, @Nullable final Runnable onDone) { select(element, onDone, false); } public void select(@Nullable Object element, @Nullable final Runnable onDone, boolean addToSelection) { if (element == null) return; _select(new Object[]{element}, onDone, addToSelection, false); } private void doSelect(@Nonnull final Object element, final Runnable onDone, final boolean deferred, final boolean canBeCentered, final boolean scrollToVisible, final boolean canSmartExpand) { final Runnable _onDone = new TreeRunnable("AbstractTreeUi.doSelect") { @Override public void perform() { if (!checkDeferred(deferred, onDone)) return; checkPathAndMaybeRevalidate(element, new TreeRunnable("AbstractTreeUi.doSelect: checkPathAndMaybeRevalidate") { @Override public void perform() { selectVisible(element, onDone, true, canBeCentered, scrollToVisible); } }, true, canSmartExpand); } }; _expand(element, _onDone, true, false, canSmartExpand); } private void checkPathAndMaybeRevalidate(@Nonnull Object element, @Nonnull final Runnable onDone, final boolean parentsOnly, final boolean canSmartExpand) { boolean toRevalidate = isValid(element) && !myRevalidatedObjects.contains(element) && getNodeForElement(element, false) == null && isInStructure(element); if (!toRevalidate) { runDone(onDone); return; } myRevalidatedObjects.add(element); getBuilder().revalidateElement(element).onSuccess(o -> invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.checkPathAndMaybeRevalidate: on done revalidateElement") { @Override public void perform() { _expand(o, onDone, parentsOnly, false, canSmartExpand); } })).onError(throwable -> wrapDone(onDone, "AbstractTreeUi.checkPathAndMaybeRevalidate: on rejected revalidateElement").run()); } public void scrollSelectionToVisible(@Nullable final Runnable onDone, final boolean shouldBeCentered) { //noinspection SSBasedInspection SwingUtilities.invokeLater(new TreeRunnable("AbstractTreeUi.scrollSelectionToVisible") { @Override public void perform() { if (isReleased()) return; int[] rows = myTree.getSelectionRows(); if (rows == null || rows.length == 0) { runDone(onDone); return; } Object toSelect = null; for (int eachRow : rows) { TreePath path = myTree.getPathForRow(eachRow); toSelect = getElementFor(path.getLastPathComponent()); if (toSelect != null) break; } if (toSelect != null) { selectVisible(toSelect, onDone, true, shouldBeCentered, true); } } }); } private void selectVisible(@Nonnull Object element, final Runnable onDone, boolean addToSelection, boolean canBeCentered, final boolean scroll) { DefaultMutableTreeNode toSelect = getNodeToScroll(element); if (toSelect == null) { runDone(onDone); return; } if (myUpdaterState != null) { myUpdaterState.addSelection(element); } setHoldSize(false); runDone(wrapScrollTo(onDone, element, toSelect, addToSelection, canBeCentered, scroll)); } void userScrollTo(Object element, Runnable onDone) { DefaultMutableTreeNode node = getNodeToScroll(element); runDone(node == null ? onDone : wrapScrollTo(onDone, element, node, false, true, true)); } private DefaultMutableTreeNode getNodeToScroll(Object element) { if (element == null) return null; DefaultMutableTreeNode node = getNodeForElement(element, false); if (node == null) return null; return myTree.isRootVisible() || node != getRootNode() ? node : null; } @Nonnull private Runnable wrapDone(Runnable onDone, @Nonnull String name) { return new TreeRunnable(name) { @Override public void perform() { runDone(onDone); } }; } @Nonnull private Runnable wrapScrollTo(Runnable onDone, @Nonnull Object element, @Nonnull DefaultMutableTreeNode node, boolean addToSelection, boolean canBeCentered, boolean scroll) { return new TreeRunnable("AbstractTreeUi.wrapScrollTo") { @Override public void perform() { int row = getRowIfUnderSelection(element); if (row == -1) row = myTree.getRowForPath(new TreePath(node.getPath())); int top = row - 2; int bottom = row + 2; if (canBeCentered && Registry.is("ide.tree.autoscrollToVCenter")) { int count = TreeUtil.getVisibleRowCount(myTree) - 1; top = count > 0 ? row - count / 2 : row; bottom = count > 0 ? top + count : row; } TreeUtil.showAndSelect(myTree, top, bottom, row, -1, addToSelection, scroll).doWhenDone(wrapDone(onDone, "AbstractTreeUi.wrapScrollTo.onDone")); } }; } private int getRowIfUnderSelection(@Nonnull Object element) { final Set<Object> selection = getSelectedElements(); if (selection.contains(element)) { final TreePath[] paths = getTree().getSelectionPaths(); for (TreePath each : paths) { if (element.equals(getElementFor(each.getLastPathComponent()))) { return getTree().getRowForPath(each); } } return -1; } Object anchor = TreeAnchorizer.getService().createAnchor(element); Object o = isNodeNull(anchor) ? null : myElementToNodeMap.get(anchor); TreeAnchorizer.getService().freeAnchor(anchor); if (o instanceof List) { final TreePath[] paths = getTree().getSelectionPaths(); if (paths != null && paths.length > 0) { Set<DefaultMutableTreeNode> selectedNodes = new HashSet<>(); for (TreePath eachPAth : paths) { if (eachPAth.getLastPathComponent() instanceof DefaultMutableTreeNode) { selectedNodes.add((DefaultMutableTreeNode)eachPAth.getLastPathComponent()); } } //noinspection unchecked for (DefaultMutableTreeNode eachNode : (List<DefaultMutableTreeNode>)o) { while (eachNode != null) { if (selectedNodes.contains(eachNode)) { return getTree().getRowForPath(getPathFor(eachNode)); } eachNode = (DefaultMutableTreeNode)eachNode.getParent(); } } } } return -1; } public void expandAll(@Nullable final Runnable onDone) { final JTree tree = getTree(); if (tree.getRowCount() > 0) { final int expandRecursionDepth = Math.max(2, Registry.intValue("ide.tree.expandRecursionDepth")); new TreeRunnable("AbstractTreeUi.expandAll") { private int myCurrentRow; private int myInvocationCount; @Override public void perform() { if (++myInvocationCount > expandRecursionDepth) { myInvocationCount = 0; if (isPassthroughMode()) { run(); } else { // need this to prevent stack overflow if the tree is rather big and is "synchronous" //noinspection SSBasedInspection SwingUtilities.invokeLater(this); } } else { final int row = myCurrentRow++; if (row < tree.getRowCount()) { final TreePath path = tree.getPathForRow(row); final Object last = path.getLastPathComponent(); final Object elem = getElementFor(last); expand(elem, this); } else { runDone(onDone); } } } }.run(); } else { runDone(onDone); } } public void expand(final Object element, @Nullable final Runnable onDone) { expand(new Object[]{element}, onDone); } public void expand(@Nonnull final Object[] element, @Nullable final Runnable onDone) { expand(element, onDone, false); } void expand(@Nonnull final Object[] element, @Nullable final Runnable onDone, boolean checkIfInStructure) { _expand(element, onDone == null ? new EmptyRunnable() : onDone, checkIfInStructure); } private void _expand(@Nonnull final Object[] elements, @Nonnull final Runnable onDone, final boolean checkIfInStructure) { try { runDone(new TreeRunnable("AbstractTreeUi._expand") { @Override public void perform() { if (elements.length == 0) { runDone(onDone); return; } if (myUpdaterState != null) { myUpdaterState.clearExpansion(); } final ActionCallback done = new ActionCallback(elements.length); done.doWhenDone(wrapDone(onDone, "AbstractTreeUi._expand: on done expandNext")).doWhenRejected(wrapDone(onDone, "AbstractTreeUi._expand: on rejected expandNext")); expandNext(elements, 0, false, checkIfInStructure, false, done, 0); } }); } catch (ProcessCanceledException e) { try { runDone(onDone); } catch (ProcessCanceledException ignored) { //todo[kirillk] added by Nik to fix IDEA-58475. I'm not sure that it is correct solution } } } private void expandNext(@Nonnull final Object[] elements, final int index, final boolean parentsOnly, final boolean checkIfInStricture, final boolean canSmartExpand, @Nonnull final ActionCallback done, final int currentDepth) { if (elements.length <= 0) { done.setDone(); return; } if (index >= elements.length) { return; } final int[] actualDepth = {currentDepth}; boolean breakCallChain = false; if (actualDepth[0] > Registry.intValue("ide.tree.expandRecursionDepth")) { actualDepth[0] = 0; breakCallChain = true; } Runnable expandRunnable = new TreeRunnable("AbstractTreeUi.expandNext") { @Override public void perform() { _expand(elements[index], new TreeRunnable("AbstractTreeUi.expandNext: on done") { @Override public void perform() { done.setDone(); expandNext(elements, index + 1, parentsOnly, checkIfInStricture, canSmartExpand, done, actualDepth[0] + 1); } }, parentsOnly, checkIfInStricture, canSmartExpand); } }; if (breakCallChain && !isPassthroughMode()) { //noinspection SSBasedInspection SwingUtilities.invokeLater(expandRunnable); } else { expandRunnable.run(); } } public void collapseChildren(@Nonnull final Object element, @Nullable final Runnable onDone) { runDone(new TreeRunnable("AbstractTreeUi.collapseChildren") { @Override public void perform() { final DefaultMutableTreeNode node = getNodeForElement(element, false); if (node != null) { getTree().collapsePath(new TreePath(node.getPath())); runDone(onDone); } } }); } private void runDone(@Nullable Runnable done) { if (done == null) return; if (!canInitiateNewActivity()) { if (done instanceof AbstractTreeBuilder.UserRunnable) { return; } } if (isYeildingNow()) { myYieldingDoneRunnables.add(done); } else { try { execute(done); } catch (ProcessCanceledException ignored) { } } } private void _expand(final Object element, @Nonnull final Runnable onDone, final boolean parentsOnly, boolean checkIfInStructure, boolean canSmartExpand) { if (checkIfInStructure && !isInStructure(element)) { runDone(onDone); return; } if (wasRootNodeInitialized()) { List<Object> kidsToExpand = new ArrayList<>(); Object eachElement = element; DefaultMutableTreeNode firstVisible = null; while (true) { if (eachElement == null || !isValid(eachElement)) break; final int preselected = getRowIfUnderSelection(eachElement); if (preselected >= 0) { firstVisible = (DefaultMutableTreeNode)getTree().getPathForRow(preselected).getLastPathComponent(); } else { firstVisible = getNodeForElement(eachElement, true); } if (eachElement != element || !parentsOnly) { kidsToExpand.add(eachElement); } if (firstVisible != null) break; eachElement = getTreeStructure().getParentElement(eachElement); if (eachElement == null) break; int i = kidsToExpand.indexOf(eachElement); if (i != -1) { try { Object existing = kidsToExpand.get(i); LOG.error("Tree path contains equal elements at different levels:\n" + " element: '" + eachElement + "'; " + eachElement.getClass() + " (" + System.identityHashCode(eachElement) + ");\n" + "existing: '" + existing + "'; " + existing.getClass() + " (" + System.identityHashCode(existing) + "); " + "path='" + kidsToExpand + "'; tree structure=" + myTreeStructure); } catch (AssertionError ignored) { } runDone(onDone); throw new ProcessCanceledException(); } } if (firstVisible == null) { runDone(onDone); } else if (kidsToExpand.isEmpty()) { final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)firstVisible.getParent(); if (parentNode != null) { final TreePath parentPath = new TreePath(parentNode.getPath()); if (!myTree.isExpanded(parentPath)) { expand(parentPath, canSmartExpand); } } runDone(onDone); } else { processExpand(firstVisible, kidsToExpand, kidsToExpand.size() - 1, onDone, canSmartExpand); } } else { deferExpansion(element, onDone, parentsOnly, canSmartExpand); } } private void deferExpansion(final Object element, @Nonnull final Runnable onDone, final boolean parentsOnly, final boolean canSmartExpand) { myDeferredExpansions.add(new TreeRunnable("AbstractTreeUi.deferExpansion") { @Override public void perform() { _expand(element, onDone, parentsOnly, false, canSmartExpand); } }); } private void processExpand(final DefaultMutableTreeNode toExpand, @Nonnull final List<Object> kidsToExpand, final int expandIndex, @Nonnull final Runnable onDone, final boolean canSmartExpand) { final Object element = getElementFor(toExpand); if (element == null) { runDone(onDone); return; } addNodeAction(element, true, node -> { if (node.getChildCount() > 0 && !myTree.isExpanded(new TreePath(node.getPath()))) { if (!isAutoExpand(node)) { expand(node, canSmartExpand); } } if (expandIndex <= 0) { runDone(onDone); return; } checkPathAndMaybeRevalidate(kidsToExpand.get(expandIndex - 1), new TreeRunnable("AbstractTreeUi.processExpand") { @Override public void perform() { final DefaultMutableTreeNode nextNode = getNodeForElement(kidsToExpand.get(expandIndex - 1), false); processExpand(nextNode, kidsToExpand, expandIndex - 1, onDone, canSmartExpand); } }, false, canSmartExpand); }); boolean childrenToUpdate = areChildrenToBeUpdated(toExpand); boolean expanded = myTree.isExpanded(getPathFor(toExpand)); boolean unbuilt = myUnbuiltNodes.contains(toExpand); if (expanded) { if (unbuilt || childrenToUpdate) { addSubtreeToUpdate(toExpand); } } else { expand(toExpand, canSmartExpand); } if (!unbuilt && !childrenToUpdate) { processNodeActionsIfReady(toExpand); } } private boolean areChildrenToBeUpdated(DefaultMutableTreeNode node) { return getUpdater().isEnqueuedToUpdate(node) || isUpdatingParent(node) || myCancelledBuild.containsKey(node); } @Nullable public Object getElementFor(Object node) { NodeDescriptor descriptor = getDescriptorFrom(node); return descriptor == null ? null : getElementFromDescriptor(descriptor); } final boolean isNodeBeingBuilt(@Nonnull final TreePath path) { return isNodeBeingBuilt(path.getLastPathComponent()); } private boolean isNodeBeingBuilt(@Nonnull Object node) { return getParentBuiltNode(node) != null || myRootNode == node && !wasRootNodeInitialized(); } @Nullable private DefaultMutableTreeNode getParentBuiltNode(@Nonnull Object node) { DefaultMutableTreeNode parent = getParentLoadingInBackground(node); if (parent != null) return parent; if (isLoadingParentInBackground(node)) return (DefaultMutableTreeNode)node; DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node; final boolean childrenAreNoLoadedYet = myUnbuiltNodes.contains(treeNode) || isUpdatingChildrenNow(treeNode); if (childrenAreNoLoadedYet) { final TreePath nodePath = new TreePath(treeNode.getPath()); if (!myTree.isExpanded(nodePath)) return null; return (DefaultMutableTreeNode)node; } return null; } private boolean isLoadingParentInBackground(Object node) { return node instanceof DefaultMutableTreeNode && isLoadedInBackground(getElementFor(node)); } public void setTreeStructure(@Nonnull AbstractTreeStructure treeStructure) { myTreeStructure = treeStructure; clearUpdaterState(); } public AbstractTreeUpdater getUpdater() { return myUpdater; } public void setUpdater(@Nullable final AbstractTreeUpdater updater) { myUpdater = updater; if (updater != null && myUpdateIfInactive) { updater.showNotify(); } if (myUpdater != null) { myUpdater.setPassThroughMode(myPassThroughMode); } } public DefaultMutableTreeNode getRootNode() { return myRootNode; } public void setRootNode(@Nonnull final DefaultMutableTreeNode rootNode) { myRootNode = rootNode; } private void dropUpdaterStateIfExternalChange() { if (!isInnerChange()) { clearUpdaterState(); myAutoExpandRoots.clear(); mySelectionIsAdjusted = false; } } void clearUpdaterState() { myUpdaterState = null; } private void createMapping(@Nonnull Object element, DefaultMutableTreeNode node) { element = TreeAnchorizer.getService().createAnchor(element); warnMap("myElementToNodeMap: createMapping: ", myElementToNodeMap); if (!myElementToNodeMap.containsKey(element)) { myElementToNodeMap.put(element, node); } else { final Object value = myElementToNodeMap.get(element); final List<DefaultMutableTreeNode> nodes; if (value instanceof DefaultMutableTreeNode) { nodes = new ArrayList<>(); nodes.add((DefaultMutableTreeNode)value); myElementToNodeMap.put(element, nodes); } else { nodes = (List<DefaultMutableTreeNode>)value; } nodes.add(node); } } private void removeMapping(@Nonnull Object element, DefaultMutableTreeNode node, @Nullable Object elementToPutNodeActionsFor) { element = TreeAnchorizer.getService().createAnchor(element); warnMap("myElementToNodeMap: removeMapping: ", myElementToNodeMap); final Object value = myElementToNodeMap.get(element); if (value != null) { if (value instanceof DefaultMutableTreeNode) { if (value.equals(node)) { myElementToNodeMap.remove(element); } } else { List<DefaultMutableTreeNode> nodes = (List<DefaultMutableTreeNode>)value; final boolean reallyRemoved = nodes.remove(node); if (reallyRemoved) { if (nodes.isEmpty()) { myElementToNodeMap.remove(element); } } } } remapNodeActions(element, elementToPutNodeActionsFor); TreeAnchorizer.getService().freeAnchor(element); } private void remapNodeActions(Object element, Object elementToPutNodeActionsFor) { _remapNodeActions(element, elementToPutNodeActionsFor, myNodeActions); _remapNodeActions(element, elementToPutNodeActionsFor, myNodeChildrenActions); warnMap("myNodeActions: remapNodeActions: ", myNodeActions); warnMap("myNodeChildrenActions: remapNodeActions: ", myNodeChildrenActions); } private static void _remapNodeActions(Object element, @Nullable Object elementToPutNodeActionsFor, @Nonnull final Map<Object, List<NodeAction>> nodeActions) { final List<NodeAction> actions = nodeActions.get(element); nodeActions.remove(element); if (elementToPutNodeActionsFor != null && actions != null) { nodeActions.put(elementToPutNodeActionsFor, actions); } } @Nullable private DefaultMutableTreeNode getFirstNode(@Nonnull Object element) { return findNode(element, 0); } @Nullable private DefaultMutableTreeNode findNode(@Nonnull Object element, int startIndex) { final Object value = getBuilder().findNodeByElement(element); if (value == null) { return null; } if (value instanceof DefaultMutableTreeNode) { return startIndex == 0 ? (DefaultMutableTreeNode)value : null; } final List<DefaultMutableTreeNode> nodes = (List<DefaultMutableTreeNode>)value; return startIndex < nodes.size() ? nodes.get(startIndex) : null; } Object findNodeByElement(Object element) { element = TreeAnchorizer.getService().createAnchor(element); try { if (isNodeNull(element)) return null; if (myElementToNodeMap.containsKey(element)) { return myElementToNodeMap.get(element); } TREE_NODE_WRAPPER.setValue(element); return myElementToNodeMap.get(TREE_NODE_WRAPPER); } finally { TREE_NODE_WRAPPER.setValue(null); TreeAnchorizer.getService().freeAnchor(element); } } @Nullable private DefaultMutableTreeNode findNodeForChildElement(@Nonnull DefaultMutableTreeNode parentNode, Object element) { Object anchor = TreeAnchorizer.getService().createAnchor(element); final Object value = isNodeNull(anchor) ? null : myElementToNodeMap.get(anchor); TreeAnchorizer.getService().freeAnchor(anchor); if (value == null) { return null; } if (value instanceof DefaultMutableTreeNode) { final DefaultMutableTreeNode elementNode = (DefaultMutableTreeNode)value; return parentNode.equals(elementNode.getParent()) ? elementNode : null; } final List<DefaultMutableTreeNode> allNodesForElement = (List<DefaultMutableTreeNode>)value; for (final DefaultMutableTreeNode elementNode : allNodesForElement) { if (parentNode.equals(elementNode.getParent())) { return elementNode; } } return null; } private void addNodeAction(Object element, boolean shouldChildrenBeReady, @Nonnull NodeAction action) { _addNodeAction(element, action, myNodeActions); if (shouldChildrenBeReady) { _addNodeAction(element, action, myNodeChildrenActions); } warnMap("myNodeActions: addNodeAction: ", myNodeActions); warnMap("myNodeChildrenActions: addNodeAction: ", myNodeChildrenActions); } public void addActivity() { if (myActivityMonitor != null) { myActivityMonitor.addActivity(myActivityId, getUpdater().getModalityState()); } } private void removeActivity() { if (myActivityMonitor != null) { myActivityMonitor.removeActivity(myActivityId); } } private void _addNodeAction(Object element, NodeAction action, @Nonnull Map<Object, List<NodeAction>> map) { maybeSetBusyAndScheduleWaiterForReady(true, element); map.computeIfAbsent(element, k -> new ArrayList<>()).add(action); addActivity(); } private void cleanUpNow() { if (!canInitiateNewActivity()) return; final UpdaterTreeState state = new UpdaterTreeState(this); myTree.collapsePath(new TreePath(myTree.getModel().getRoot())); clearSelection(); getRootNode().removeAllChildren(); myRootNodeWasQueuedToInitialize = false; myRootNodeInitialized = false; clearNodeActions(); myElementToNodeMap.clear(); myDeferredSelections.clear(); myDeferredExpansions.clear(); myLoadedInBackground.clear(); myUnbuiltNodes.clear(); myUpdateFromRootRequested = true; myWorker.clear(); myTree.invalidate(); state.restore(null); } public void setClearOnHideDelay(final long clearOnHideDelay) { myClearOnHideDelay = clearOnHideDelay; } private class MySelectionListener implements TreeSelectionListener { @Override public void valueChanged(@Nonnull final TreeSelectionEvent e) { if (mySilentSelect != null && mySilentSelect.equals(e.getNewLeadSelectionPath())) return; dropUpdaterStateIfExternalChange(); } } private class MyExpansionListener implements TreeExpansionListener { @Override public void treeExpanded(@Nonnull TreeExpansionEvent event) { final TreePath path = event.getPath(); if (mySilentExpand != null && mySilentExpand.equals(path)) return; dropUpdaterStateIfExternalChange(); if (myRequestedExpand != null && !myRequestedExpand.equals(path)) { _getReady().doWhenDone(new TreeRunnable("AbstractTreeUi.MyExpansionListener.treeExpanded") { @Override public void perform() { Object element = getElementFor(path.getLastPathComponent()); expand(element, null); } }); return; } final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); if (!myUnbuiltNodes.contains(node)) { removeLoading(node, false); Set<DefaultMutableTreeNode> childrenToUpdate = new HashSet<>(); for (int i = 0; i < node.getChildCount(); i++) { DefaultMutableTreeNode each = (DefaultMutableTreeNode)node.getChildAt(i); if (myUnbuiltNodes.contains(each)) { makeLoadingOrLeafIfNoChildren(each); childrenToUpdate.add(each); } } if (!childrenToUpdate.isEmpty()) { for (DefaultMutableTreeNode each : childrenToUpdate) { maybeUpdateSubtreeToUpdate(each); } } } else { getBuilder().expandNodeChildren(node); } processSmartExpand(node, canSmartExpand(node, true), false); processNodeActionsIfReady(node); } @Override public void treeCollapsed(@Nonnull TreeExpansionEvent e) { dropUpdaterStateIfExternalChange(); final TreePath path = e.getPath(); final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); NodeDescriptor descriptor = getDescriptorFrom(node); if (descriptor == null) return; TreePath pathToSelect = null; if (isSelectionInside(node)) { pathToSelect = new TreePath(node.getPath()); } if (getBuilder().isDisposeOnCollapsing(descriptor)) { runDone(new TreeRunnable("AbstractTreeUi.MyExpansionListener.treeCollapsed") { @Override public void perform() { if (isDisposed(node)) return; TreePath nodePath = new TreePath(node.getPath()); if (myTree.isExpanded(nodePath)) return; removeChildren(node); makeLoadingOrLeafIfNoChildren(node); } }); if (node.equals(getRootNode())) { if (myTree.isRootVisible()) { //todo kirillk to investigate -- should be done by standard selction move //addSelectionPath(new TreePath(getRootNode().getPath()), true, Condition.FALSE); } } else { myTreeModel.reload(node); } } if (pathToSelect != null && myTree.isSelectionEmpty()) { addSelectionPath(pathToSelect, true, Conditions.alwaysFalse(), null); } } } private void removeChildren(@Nonnull DefaultMutableTreeNode node) { Enumeration children = node.children(); //noinspection unchecked List<DefaultMutableTreeNode> nodes = Collections.<DefaultMutableTreeNode>list(children); for (DefaultMutableTreeNode child : nodes) { disposeNode(child); } node.removeAllChildren(); nodeStructureChanged(node); } private void maybeUpdateSubtreeToUpdate(@Nonnull final DefaultMutableTreeNode subtreeRoot) { if (!myUnbuiltNodes.contains(subtreeRoot)) return; TreePath path = getPathFor(subtreeRoot); if (myTree.getRowForPath(path) == -1) return; DefaultMutableTreeNode parent = getParentBuiltNode(subtreeRoot); if (parent == null) { if (!getBuilder().isAlwaysShowPlus(getDescriptorFrom(subtreeRoot))) { addSubtreeToUpdate(subtreeRoot); } } else if (parent != subtreeRoot) { addNodeAction(getElementFor(subtreeRoot), true, parent1 -> maybeUpdateSubtreeToUpdate(subtreeRoot)); } } private boolean isSelectionInside(@Nonnull DefaultMutableTreeNode parent) { TreePath path = new TreePath(myTreeModel.getPathToRoot(parent)); TreePath[] paths = myTree.getSelectionPaths(); if (paths == null) return false; for (TreePath path1 : paths) { if (path.isDescendant(path1)) return true; } return false; } boolean isInStructure(@Nullable Object element) { if (isNodeNull(element)) return false; final AbstractTreeStructure structure = getTreeStructure(); if (structure == null) return false; final Object rootElement = structure.getRootElement(); Object eachParent = element; while (eachParent != null) { if (Comparing.equal(rootElement, eachParent)) return true; eachParent = structure.getParentElement(eachParent); } return false; } @FunctionalInterface interface NodeAction { void onReady(@Nonnull DefaultMutableTreeNode node); } void setCanYield(final boolean canYield) { myCanYield = canYield; } @Nonnull Collection<TreeUpdatePass> getYeildingPasses() { return myYieldingPasses; } private static class LoadedChildren { @Nonnull private final List<Object> myElements; private final Map<Object, NodeDescriptor> myDescriptors = new HashMap<>(); private final Map<NodeDescriptor, Boolean> myChanges = new HashMap<>(); LoadedChildren(@Nullable Object[] elements) { myElements = Arrays.asList(elements != null ? elements : ArrayUtil.EMPTY_OBJECT_ARRAY); } void putDescriptor(Object element, NodeDescriptor descriptor, boolean isChanged) { if (isUnitTestingMode()) { assert myElements.contains(element); } myDescriptors.put(element, descriptor); myChanges.put(descriptor, isChanged); } @Nonnull List<Object> getElements() { return myElements; } NodeDescriptor getDescriptor(Object element) { return myDescriptors.get(element); } @Nonnull @Override public String toString() { return myElements + "->" + myChanges; } public boolean isUpdated(Object element) { NodeDescriptor desc = getDescriptor(element); return myChanges.get(desc); } } private long getComparatorStamp() { if (myNodeDescriptorComparator instanceof NodeDescriptor.NodeComparator) { long currentComparatorStamp = ((NodeDescriptor.NodeComparator)myNodeDescriptorComparator).getStamp(); if (currentComparatorStamp > myLastComparatorStamp) { myOwnComparatorStamp = Math.max(myOwnComparatorStamp, currentComparatorStamp) + 1; } myLastComparatorStamp = currentComparatorStamp; return Math.max(currentComparatorStamp, myOwnComparatorStamp); } else { return myOwnComparatorStamp; } } void incComparatorStamp() { myOwnComparatorStamp = getComparatorStamp() + 1; } private static class UpdateInfo { NodeDescriptor myDescriptor; TreeUpdatePass myPass; boolean myCanSmartExpand; boolean myWasExpanded; boolean myForceUpdate; boolean myDescriptorIsUpToDate; boolean myUpdateChildren; UpdateInfo(NodeDescriptor descriptor, TreeUpdatePass pass, boolean canSmartExpand, boolean wasExpanded, boolean forceUpdate, boolean descriptorIsUpToDate, boolean updateChildren) { myDescriptor = descriptor; myPass = pass; myCanSmartExpand = canSmartExpand; myWasExpanded = wasExpanded; myForceUpdate = forceUpdate; myDescriptorIsUpToDate = descriptorIsUpToDate; myUpdateChildren = updateChildren; } synchronized NodeDescriptor getDescriptor() { return myDescriptor; } synchronized TreeUpdatePass getPass() { return myPass; } synchronized boolean isCanSmartExpand() { return myCanSmartExpand; } synchronized boolean isWasExpanded() { return myWasExpanded; } synchronized boolean isForceUpdate() { return myForceUpdate; } synchronized boolean isDescriptorIsUpToDate() { return myDescriptorIsUpToDate; } public synchronized void apply(@Nonnull UpdateInfo updateInfo) { myDescriptor = updateInfo.myDescriptor; myPass = updateInfo.myPass; myCanSmartExpand = updateInfo.myCanSmartExpand; myWasExpanded = updateInfo.myWasExpanded; myForceUpdate = updateInfo.myForceUpdate; myDescriptorIsUpToDate = updateInfo.myDescriptorIsUpToDate; } public synchronized boolean isUpdateChildren() { return myUpdateChildren; } @Override @Nonnull @NonNls public synchronized String toString() { return "UpdateInfo: desc=" + myDescriptor + " pass=" + myPass + " canSmartExpand=" + myCanSmartExpand + " wasExpanded=" + myWasExpanded + " forceUpdate=" + myForceUpdate + " descriptorUpToDate=" + myDescriptorIsUpToDate; } } void setPassthroughMode(boolean passthrough) { myPassThroughMode = passthrough; AbstractTreeUpdater updater = getUpdater(); if (updater != null) { updater.setPassThroughMode(myPassThroughMode); } if (!isUnitTestingMode() && passthrough) { // TODO: this assertion should be restored back as soon as possible [JamTreeTableView should be rewritten, etc] //LOG.error("Pass-through mode for TreeUi is allowed only for unit test mode"); } } boolean isPassthroughMode() { return myPassThroughMode; } private static boolean isUnitTestingMode() { Application app = ApplicationManager.getApplication(); return app != null && app.isUnitTestMode(); } private void addModelListenerToDiagnoseAccessOutsideEdt() { myTreeModel.addTreeModelListener(new TreeModelListener() { @Override public void treeNodesChanged(TreeModelEvent e) { assertIsDispatchThread(); } @Override public void treeNodesInserted(TreeModelEvent e) { assertIsDispatchThread(); } @Override public void treeNodesRemoved(TreeModelEvent e) { assertIsDispatchThread(); } @Override public void treeStructureChanged(TreeModelEvent e) { assertIsDispatchThread(); } }); } private <V> void warnMap(String prefix, Map<Object, V> map) { if (!LOG.isDebugEnabled()) return; if (!SwingUtilities.isEventDispatchThread() && !myPassThroughMode) { LOG.warn(prefix + "modified on wrong thread"); } long count = map.keySet().stream().filter(AbstractTreeUi::isNodeNull).count(); if (count > 0) LOG.warn(prefix + "null keys: " + count + " / " + map.size()); } /** * @param element an element in the tree structure * @return {@code true} if element is {@code null} or if it contains a {@code null} value */ private static boolean isNodeNull(Object element) { if (element instanceof AbstractTreeNode) { AbstractTreeNode node = (AbstractTreeNode)element; element = node.getValue(); } return element == null; } public final boolean isConsistent() { return myTree != null && myTreeModel != null && myTreeModel == myTree.getModel(); } }
package org.eclipse.persistence.jaxb; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Map.Entry; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.Source; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.internal.helper.ConversionManager; import org.eclipse.persistence.oxm.XMLContext; import org.eclipse.persistence.jaxb.compiler.*; import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelImpl; import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelInputImpl; import org.eclipse.persistence.jaxb.xmlmodel.JavaType; import org.eclipse.persistence.jaxb.xmlmodel.XmlBindings; import org.eclipse.persistence.jaxb.xmlmodel.XmlBindings.JavaTypes; import org.eclipse.persistence.internal.jaxb.JaxbClassLoader; import org.eclipse.persistence.internal.jaxb.SessionEventListener; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.exceptions.EclipseLinkException; import org.eclipse.persistence.exceptions.SessionLoaderException; import org.eclipse.persistence.exceptions.ValidationException; import org.eclipse.persistence.oxm.XMLLogin; import org.eclipse.persistence.oxm.platform.SAXPlatform; import org.eclipse.persistence.oxm.platform.XMLPlatform; import org.eclipse.persistence.sessions.Project; /** * INTERNAL: * <p> * <b>Purpose:</b>An EclipseLink specific JAXBContextFactory. This class can be specified in a * jaxb.properties file to make use of TopLink's JAXB 2.1 implementation. * <p> * <b>Responsibilities:</b> * <ul> * <li>Create a JAXBContext from an array of Classes and a Properties object</li> * <li>Create a JAXBContext from a context path and a classloader</li> * </ul> * <p> * This class is the entry point into in EclipseLink's JAXB 2.1 Runtime. It provides the required * factory methods and is invoked by javax.xml.bind.JAXBContext.newInstance() to create new * instances of JAXBContext. When creating a JAXBContext from a contextPath, the list of classes is * derived either from an ObjectFactory class (schema-to-java) or a jaxb.index file * (java-to-schema). * * @author mmacivor * @since Oracle TopLink 11.1.1.0.0 * @see javax.xml.bind.JAXBContext * @see org.eclipse.persistence.jaxb.JAXBContext * @see org.eclipse.persistence.jaxb.compiler.Generator */ public class JAXBContextFactory { public static final String ECLIPSELINK_OXM_XML_KEY = "eclipselink-oxm-xml"; public static final String DEFAULT_TARGET_NAMESPACE_KEY = "defaultTargetNamespace"; /** * Create a JAXBContext on the array of Class objects. The JAXBContext will * also be aware of classes reachable from the classes in the array. */ public static javax.xml.bind.JAXBContext createContext(Class[] classesToBeBound, Map properties) throws JAXBException { ClassLoader loader = null; if (classesToBeBound.length > 0) { loader = classesToBeBound[0].getClassLoader(); if(null == loader) { loader = getDefaultClassLoader(); } } return createContext(classesToBeBound, properties, loader); } /** * Create a JAXBContext on the array of Class objects. The JAXBContext will * also be aware of classes reachable from the classes in the array. */ public static javax.xml.bind.JAXBContext createContext(Class[] classesToBeBound, Map properties, ClassLoader classLoader) throws JAXBException { Type[] types = new Type[classesToBeBound.length]; System.arraycopy(classesToBeBound, 0, types, 0, classesToBeBound.length); return createContext(types, properties, classLoader); } /** * Create a JAXBContext on context path. The JAXBContext will * also be aware of classes reachable from the classes on the context path. */ public static javax.xml.bind.JAXBContext createContext(String contextPath, ClassLoader classLoader) throws JAXBException { return createContext(contextPath, classLoader, null); } /** * Create a JAXBContext on context path. The JAXBContext will * also be aware of classes reachable from the classes on the context path. */ public static javax.xml.bind.JAXBContext createContext(String contextPath, ClassLoader classLoader, Map properties) throws JAXBException { if(null == classLoader) { classLoader = getDefaultClassLoader(); } EclipseLinkException sessionLoadingException = null; try { XMLContext xmlContext = new XMLContext(contextPath, classLoader); return new org.eclipse.persistence.jaxb.JAXBContext(xmlContext); } catch (ValidationException vex) { if (vex.getErrorCode() != ValidationException.NO_SESSIONS_XML_FOUND) { sessionLoadingException = vex; } } catch (SessionLoaderException ex) { sessionLoadingException = ex; } catch (Exception ex) { throw new JAXBException(ex); } ArrayList<Class> classes = new ArrayList<Class>(); // Check properties map for eclipselink-oxm.xml entries Map<String, XmlBindings> xmlBindingMap = getXmlBindingsFromProperties(properties, classLoader); classes = getXmlBindingsClassesFromMap(xmlBindingMap, classLoader, classes); StringTokenizer tokenizer = new StringTokenizer(contextPath, ":"); while (tokenizer.hasMoreElements()) { String path = tokenizer.nextToken(); try { Class objectFactory = classLoader.loadClass(path + ".ObjectFactory"); if (isJAXB2ObjectFactory(objectFactory)) { classes.add(objectFactory); } } catch (Exception ex) { // if there's no object factory, don't worry about it. Check for jaxb.index next } try { // try to load package info just to be safe classLoader.loadClass(path + ".package-info"); } catch (Exception ex) { } // Next check for a jaxb.index file in case there's one available InputStream jaxbIndex = classLoader.getResourceAsStream(path.replace('.', '/') + "/jaxb.index"); if (jaxbIndex != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(jaxbIndex)); try { String line = reader.readLine(); while (line != null) { String className = path + "." + line.trim(); try { classes.add(classLoader.loadClass(className)); } catch (Exception ex) { // just ignore for now if the class isn't available. } line = reader.readLine(); } } catch (Exception ex) { } } } if (classes.size() == 0) { org.eclipse.persistence.exceptions.JAXBException jaxbException = org.eclipse.persistence.exceptions.JAXBException.noObjectFactoryOrJaxbIndexInPath(contextPath); if (sessionLoadingException != null) { jaxbException.setInternalException(sessionLoadingException); } throw new JAXBException(jaxbException); } Class[] classArray = new Class[classes.size()]; for (int i = 0; i < classes.size(); i++) { classArray[i] = (Class) classes.get(i); } return createContext(classArray, properties, classLoader, xmlBindingMap); } /** * Create a JAXBContext on the array of Type objects. The JAXBContext will * also be aware of classes reachable from the types in the array. The * preferred means of creating a Type aware JAXBContext is to create the * JAXBContext with an array of TypeMappingInfo objects. */ public static javax.xml.bind.JAXBContext createContext(Type[] typesToBeBound, Map properties, ClassLoader classLoader) throws JAXBException { Map<Type, TypeMappingInfo> typeToTypeMappingInfo = new HashMap<Type, TypeMappingInfo>(); TypeMappingInfo[] typeMappingInfo = new TypeMappingInfo[typesToBeBound.length]; for(int i = 0; i < typesToBeBound.length; i++) { TypeMappingInfo tmi = new TypeMappingInfo(); tmi.setType(typesToBeBound[i]); typeToTypeMappingInfo.put(typesToBeBound[i], tmi); typeMappingInfo[i] = tmi; } JAXBContext context = (JAXBContext)createContext(typeMappingInfo, properties, classLoader); context.setTypeToTypeMappingInfo(typeToTypeMappingInfo); return context; } /** * Create a JAXBContext on the array of TypeMappingInfo objects. The * JAXBContext will also be aware of classes reachable from the types in the * array. This is the preferred means of creating a Type aware JAXBContext. */ public static javax.xml.bind.JAXBContext createContext(TypeMappingInfo[] typesToBeBound, Map properties, ClassLoader classLoader) throws JAXBException { if(null == classLoader) { classLoader = getDefaultClassLoader(); } // Check properties map for eclipselink-oxm.xml entries Map<String, XmlBindings> xmlBindings = getXmlBindingsFromProperties(properties, classLoader); String defaultTargetNamespace = null; if(properties != null) { defaultTargetNamespace = (String)properties.get(DEFAULT_TARGET_NAMESPACE_KEY); } for (Entry<String, XmlBindings> entry : xmlBindings.entrySet()) { typesToBeBound = getXmlBindingsClasses(entry.getValue(), classLoader, typesToBeBound); } JaxbClassLoader loader = new JaxbClassLoader(classLoader, typesToBeBound); typesToBeBound = updateTypesWithObjectFactory(typesToBeBound, loader); JavaModelInputImpl inputImpl = new JavaModelInputImpl(typesToBeBound, new JavaModelImpl(loader)); try { Generator generator = new Generator(inputImpl, typesToBeBound, inputImpl.getJavaClasses(), null, xmlBindings, classLoader, defaultTargetNamespace); return createContext(generator, properties, classLoader, loader, typesToBeBound); } catch (Exception ex) { throw new JAXBException(ex.getMessage(), ex); } } /** * This means of creating a JAXBContext is aimed at creating a JAXBContext * based on method parameters. This method is useful when JAXB is used as * the binding layer for a Web Service provider. */ private static JAXBContext createContext(Class[] classesToBeBound, Map properties, ClassLoader classLoader, Map<String, XmlBindings> xmlBindings) throws JAXBException { JaxbClassLoader loader = new JaxbClassLoader(classLoader, classesToBeBound); String defaultTargetNamespace = null; if(properties != null) { defaultTargetNamespace = (String)properties.get(DEFAULT_TARGET_NAMESPACE_KEY); } try { Generator generator = new Generator(new JavaModelInputImpl(classesToBeBound, new JavaModelImpl(loader)), xmlBindings, loader, defaultTargetNamespace); return createContext(generator, properties, classLoader, loader, classesToBeBound); } catch (Exception ex) { throw new JAXBException(ex.getMessage(), ex); } } private static JAXBContext createContext(Generator generator, Map properties, ClassLoader classLoader, JaxbClassLoader loader, Type[] typesToBeBound) throws Exception { Project proj = generator.generateProject(); ConversionManager conversionManager = null; if (classLoader != null) { conversionManager = new ConversionManager(); conversionManager.setLoader(loader); } else { conversionManager = ConversionManager.getDefaultManager(); } proj.convertClassNamesToClasses(conversionManager.getLoader()); // need to make sure that the java class is set properly on each // descriptor when using java classname - req'd for JOT api implementation for (Iterator<ClassDescriptor> descriptorIt = proj.getOrderedDescriptors().iterator(); descriptorIt.hasNext();) { ClassDescriptor descriptor = descriptorIt.next(); if (descriptor.getJavaClass() == null) { descriptor.setJavaClass(conversionManager.convertClassNameToClass(descriptor.getJavaClassName())); } } // disable instantiation policy validation during descriptor initialization SessionEventListener eventListener = new SessionEventListener(); eventListener.setShouldValidateInstantiationPolicy(false); XMLPlatform platform = new SAXPlatform(); platform.getConversionManager().setLoader(loader); XMLContext xmlContext = new XMLContext(proj, loader, eventListener); if(generator.getAnnotationsProcessor().getPackageToNamespaceMappings().size() > 1){ ((XMLLogin)xmlContext.getSession(0).getDatasourceLogin()).setEqualNamespaceResolvers(false); } return new JAXBContext(xmlContext, generator, typesToBeBound); } private static JAXBContext createContext(Generator generator, Map properties, ClassLoader classLoader, JaxbClassLoader loader, TypeMappingInfo[] typesToBeBound) throws Exception { Project proj = generator.generateProject(); ConversionManager conversionManager = null; if (classLoader != null) { conversionManager = new ConversionManager(); conversionManager.setLoader(loader); } else { conversionManager = ConversionManager.getDefaultManager(); } proj.convertClassNamesToClasses(conversionManager.getLoader()); // need to make sure that the java class is set properly on each // descriptor when using java classname - req'd for JOT api implementation for (Iterator<ClassDescriptor> descriptorIt = proj.getOrderedDescriptors().iterator(); descriptorIt.hasNext();) { ClassDescriptor descriptor = descriptorIt.next(); if (descriptor.getJavaClass() == null) { descriptor.setJavaClass(conversionManager.convertClassNameToClass(descriptor.getJavaClassName())); } } // disable instantiation policy validation during descriptor initialization SessionEventListener eventListener = new SessionEventListener(); eventListener.setShouldValidateInstantiationPolicy(false); XMLPlatform platform = new SAXPlatform(); platform.getConversionManager().setLoader(loader); XMLContext xmlContext = new XMLContext(proj, loader, eventListener); if(generator.getAnnotationsProcessor().getPackageToNamespaceMappings().size() > 1){ ((XMLLogin)xmlContext.getSession(0).getDatasourceLogin()).setEqualNamespaceResolvers(false); } return new JAXBContext(xmlContext, generator, typesToBeBound); } private static boolean isJAXB2ObjectFactory(Class objectFactoryClass) { try { Class xmlRegistry = PrivilegedAccessHelper.getClassForName("javax.xml.bind.annotation.XmlRegistry"); if (objectFactoryClass.isAnnotationPresent(xmlRegistry)) { return true; } return false; } catch (Exception ex) { return false; } } /** * Convenience method for processing a properties map and creating a map of package names to * XmlBindings instances. * * It is assumed that the given map's key will be ECLIPSELINK_OXM_XML_KEY, and the value will be * Map<String, Source>, where String = package, Source = metadata file */ private static Map<String, XmlBindings> getXmlBindingsFromProperties(Map properties, ClassLoader classLoader) { Map<String, XmlBindings> bindings = new HashMap<String, XmlBindings>(); if (properties != null) { Map<String, Source> metadataFiles = null; try { metadataFiles = (Map<String, Source>) properties.get(ECLIPSELINK_OXM_XML_KEY); } catch (ClassCastException x) { throw org.eclipse.persistence.exceptions.JAXBException.incorrectValueParameterTypeForOxmXmlKey(); } if (metadataFiles != null) { for(Entry<String, Source> entry : metadataFiles.entrySet()) { String key = null; try { key = entry.getKey(); if (key == null) { throw org.eclipse.persistence.exceptions.JAXBException.nullMapKey(); } } catch (ClassCastException cce) { throw org.eclipse.persistence.exceptions.JAXBException.incorrectKeyParameterType(); } try { Source metadataSource = entry.getValue(); if (metadataSource == null) { throw org.eclipse.persistence.exceptions.JAXBException.nullMetadataSource(key); } XmlBindings binding = getXmlBindings(metadataSource, classLoader); if (binding != null) { bindings.put(key, binding); } } catch (ClassCastException cce) { throw org.eclipse.persistence.exceptions.JAXBException.incorrectValueParameterType(); } } } } return bindings; } /** * Convenience method for creating an XmlBindings object based on a given Source. The method * will load the eclipselink metadata model and unmarshal the Source. This assumes that the * Source represents the eclipselink-oxm.xml metadata file to be unmarshalled. */ private static XmlBindings getXmlBindings(Source metadataSource, ClassLoader classLoader) { XmlBindings xmlBindings = null; Unmarshaller unmarshaller; // only create the JAXBContext for our XmlModel once JAXBContext jaxbContext = CompilerHelper.getXmlBindingsModelContext(); try { unmarshaller = jaxbContext.createUnmarshaller(); xmlBindings = (XmlBindings) unmarshaller.unmarshal(metadataSource); } catch (JAXBException jaxbEx) { throw org.eclipse.persistence.exceptions.JAXBException.couldNotUnmarshalMetadata(jaxbEx); } return xmlBindings; } /** * Convenience method that returns an array of Types based on a given XmlBindings. The resulting * array will not contain duplicate entries. */ private static TypeMappingInfo[] getXmlBindingsClasses(XmlBindings xmlBindings, ClassLoader classLoader, TypeMappingInfo[] existingTypes) { JavaTypes jTypes = xmlBindings.getJavaTypes(); if (jTypes != null) { List<Class> existingClasses = new ArrayList<Class>(existingTypes.length); for (TypeMappingInfo typeMappingInfo : existingTypes) { Type type = typeMappingInfo.getType(); if(type == null){ throw org.eclipse.persistence.exceptions.JAXBException.nullTypeOnTypeMappingInfo(typeMappingInfo.getXmlTagName()); } // ignore ParameterizedTypes if (type instanceof Class) { Class cls = (Class) type; existingClasses.add(cls); } } List<TypeMappingInfo> additionalTypeMappingInfos = new ArrayList<TypeMappingInfo>(jTypes.getJavaType().size()); for (JavaType javaType : jTypes.getJavaType()) { try { Class nextClass = classLoader.loadClass(javaType.getName()); if(!(existingClasses.contains(nextClass))){ TypeMappingInfo typeMappingInfo = new TypeMappingInfo(); typeMappingInfo.setType(nextClass); additionalTypeMappingInfos.add(typeMappingInfo); existingClasses.add(nextClass); } } catch (ClassNotFoundException e) { throw org.eclipse.persistence.exceptions.JAXBException.couldNotLoadClassFromMetadata(javaType.getName()); } } TypeMappingInfo[] allTypeMappingInfos = new TypeMappingInfo[existingTypes.length + additionalTypeMappingInfos.size()]; System.arraycopy(existingTypes, 0, allTypeMappingInfos, 0, existingTypes.length); Object[] additionalTypes = additionalTypeMappingInfos.toArray(); System.arraycopy(additionalTypes, 0, allTypeMappingInfos, existingTypes.length, additionalTypes.length); return allTypeMappingInfos; }else{ return existingTypes; } } /** * Convenience method that returns a list of Classes based on a given XmlBindings and an array * of existing classes. The resulting array will not contain duplicate entries. */ private static ArrayList<Class> getXmlBindingsClasses(XmlBindings xmlBindings, ClassLoader classLoader, ArrayList<Class> existingClasses) { ArrayList<Class> additionalClasses = existingClasses; JavaTypes jTypes = xmlBindings.getJavaTypes(); if (jTypes != null) { for (JavaType javaType : jTypes.getJavaType()) { try { Class jClass = classLoader.loadClass(javaType.getName()); if (!additionalClasses.contains(jClass)) { additionalClasses.add(jClass); } } catch (ClassNotFoundException e) { throw org.eclipse.persistence.exceptions.JAXBException.couldNotLoadClassFromMetadata(javaType.getName()); } } } return additionalClasses; } /** * Convenience method that returns an array of Classes based on a map given XmlBindings and an * array of existing classes. The resulting array will not contain duplicate entries. */ private static ArrayList<Class> getXmlBindingsClassesFromMap(Map<String, XmlBindings> xmlBindingMap, ClassLoader classLoader, ArrayList<Class> existingClasses) { ArrayList<Class> additionalClasses = existingClasses; // for each xmlBindings for (Entry<String, XmlBindings> entry : xmlBindingMap.entrySet()) { additionalClasses = getXmlBindingsClasses(entry.getValue(), classLoader, additionalClasses); } return additionalClasses; } private static TypeMappingInfo[] updateTypesWithObjectFactory(TypeMappingInfo[] typeMappingInfos, ClassLoader loader) { ArrayList<TypeMappingInfo> updatedTypes = new ArrayList<TypeMappingInfo>(); for (TypeMappingInfo next : typeMappingInfos) { if (!(updatedTypes.contains(next))) { updatedTypes.add(next); } Type theType = next.getType(); if (theType instanceof Class) { if (((Class) theType).getPackage() != null) { String packageName = ((Class) theType).getPackage().getName(); try { Class objectFactoryClass = loader.loadClass(packageName + ".ObjectFactory"); if (!(updatedTypes.contains(objectFactoryClass))) { TypeMappingInfo objectFactoryTypeMappingInfo = new TypeMappingInfo(); objectFactoryTypeMappingInfo.setType(objectFactoryClass); updatedTypes.add(objectFactoryTypeMappingInfo); } } catch (Exception ex) { } } } } return updatedTypes.toArray(new TypeMappingInfo[updatedTypes.size()]); } private static ClassLoader getDefaultClassLoader() { return Thread.currentThread().getContextClassLoader(); } }
package name.abuchen.portfolio.ui.dialogs; import java.util.Collections; import java.util.Date; import java.util.List; import name.abuchen.portfolio.model.AccountTransaction; import name.abuchen.portfolio.model.Client; import name.abuchen.portfolio.model.Portfolio; import name.abuchen.portfolio.model.PortfolioTransaction; import name.abuchen.portfolio.model.PortfolioTransaction.Type; import name.abuchen.portfolio.model.Security; import name.abuchen.portfolio.model.Values; import name.abuchen.portfolio.snapshot.ClientSnapshot; import name.abuchen.portfolio.snapshot.PortfolioSnapshot; import name.abuchen.portfolio.snapshot.SecurityPosition; import name.abuchen.portfolio.ui.Messages; import name.abuchen.portfolio.ui.util.BindingHelper; import name.abuchen.portfolio.ui.util.CurrencyToStringConverter; import name.abuchen.portfolio.ui.util.StringToCurrencyConverter; import name.abuchen.portfolio.util.Dates; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.beans.BeansObservables; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; public class BuySellSecurityDialog extends AbstractDialog { static class Model extends BindingHelper.Model { private final PortfolioTransaction.Type type; private Portfolio portfolio; private Security security; private long shares; private long price; private long fees; private long total; private Date date = Dates.today(); public Model(Client client, Security security, Type type) { super(client); this.security = security; this.type = type; if (type == PortfolioTransaction.Type.SELL && security != null) { ClientSnapshot snapshot = ClientSnapshot.create(client, Dates.today()); for (PortfolioSnapshot portfolio : snapshot.getPortfolios()) { SecurityPosition position = portfolio.getPositionsBySecurity().get(security); if (position != null) { setShares(position.getShares()); setPortfolio(portfolio.getSource()); setTotal(position.calculateValue()); break; } } } else { if (!client.getPortfolios().isEmpty()) setPortfolio(client.getPortfolios().get(0)); if (security == null && !client.getSecurities().isEmpty()) setSecurity(client.getSecurities().get(0)); } } public long getPrice() { return price; } private long calculatePrice() { if (shares == 0) { return 0; } else { switch (type) { case BUY: return Math.max(0, (total - fees) * Values.Share.factor() / shares); case SELL: return Math.max(0, (total + fees) * Values.Share.factor() / shares); default: throw new RuntimeException("Unsupported transaction type for dialog " + type); //$NON-NLS-1$ } } } public Portfolio getPortfolio() { return portfolio; } public void setPortfolio(Portfolio portfolio) { firePropertyChange("portfolio", this.portfolio, this.portfolio = portfolio); //$NON-NLS-1$ } public Security getSecurity() { return security; } public void setSecurity(Security security) { firePropertyChange("security", this.security, this.security = security); //$NON-NLS-1$ } public long getShares() { return shares; } public void setShares(long shares) { firePropertyChange("shares", this.shares, this.shares = shares); //$NON-NLS-1$ firePropertyChange("price", this.price, this.price = calculatePrice()); //$NON-NLS-1$ } public long getFees() { return fees; } public void setFees(long fees) { firePropertyChange("fees", this.fees, this.fees = fees); //$NON-NLS-1$ firePropertyChange("price", this.price, this.price = calculatePrice()); //$NON-NLS-1$ } public long getTotal() { return total; } public void setTotal(long total) { firePropertyChange("total", this.total, this.total = total); //$NON-NLS-1$ firePropertyChange("price", this.price, this.price = calculatePrice()); //$NON-NLS-1$ } public Date getDate() { return date; } public void setDate(Date date) { firePropertyChange("date", this.date, this.date = date); //$NON-NLS-1$ } @Override public void applyChanges() { if (security == null) throw new UnsupportedOperationException(Messages.MsgMissingSecurity); AccountTransaction ta = null; if (portfolio.getReferenceAccount() != null) { ta = new AccountTransaction(); ta.setDate(date); ta.setSecurity(security); ta.setAmount(total); if (this.type == PortfolioTransaction.Type.BUY) ta.setType(AccountTransaction.Type.BUY); else if (this.type == PortfolioTransaction.Type.SELL) ta.setType(AccountTransaction.Type.SELL); else throw new UnsupportedOperationException("Unsupported type " + this.type); //$NON-NLS-1$ portfolio.getReferenceAccount().addTransaction(ta); } PortfolioTransaction tp = new PortfolioTransaction(); tp.setDate(date); tp.setSecurity(security); tp.setShares(shares); tp.setFees(fees); tp.setAmount(total); tp.setType(type); portfolio.addTransaction(tp); } } private boolean allowSelectionOfSecurity = false; public BuySellSecurityDialog(Shell parentShell, Client client, Security security, PortfolioTransaction.Type type) { super(parentShell, security != null ? type.name() + " " + security.getName() : type.name(), //$NON-NLS-1$ new Model(client, security, type)); if (!(type == PortfolioTransaction.Type.BUY || type == PortfolioTransaction.Type.SELL)) throw new UnsupportedOperationException("dialog supports only BUY or SELL operation"); //$NON-NLS-1$ this.allowSelectionOfSecurity = security == null; } @Override protected void createFormElements(Composite editArea) { // security selection if (!allowSelectionOfSecurity) { bindings().createLabel(editArea, ((Model) getModel()).getSecurity().getName()); } else { List<Security> securities = getModel().getClient().getSecurities(); Collections.sort(securities, new Security.ByName()); bindings().bindComboViewer(editArea, Messages.ColumnSecurity, "security", new LabelProvider() //$NON-NLS-1$ { @Override public String getText(Object element) { return ((Security) element).getName(); } }, securities.toArray()); } // portfolio selection bindings().bindComboViewer(editArea, Messages.ColumnPortfolio, "portfolio", new LabelProvider() //$NON-NLS-1$ { @Override public String getText(Object element) { return ((Portfolio) element).getName(); } }, getModel().getClient().getPortfolios().toArray()); // shares bindings().bindMandatorySharesInput(editArea, Messages.ColumnShares, "shares").setFocus(); //$NON-NLS-1$ // price Label label = new Label(editArea, SWT.NONE); label.setText(Messages.ColumnPrice); Label lblPrice = new Label(editArea, SWT.BORDER | SWT.READ_ONLY | SWT.NO_FOCUS); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, false).applyTo(lblPrice); getBindingContext().bindValue( SWTObservables.observeText(lblPrice), BeansObservables.observeValue(getModel(), "price"), //$NON-NLS-1$ new UpdateValueStrategy(false, UpdateValueStrategy.POLICY_UPDATE) .setConverter(new StringToCurrencyConverter(Values.Amount)), new UpdateValueStrategy(false, UpdateValueStrategy.POLICY_UPDATE) .setConverter(new CurrencyToStringConverter(Values.Amount))); // fee bindings().bindAmountInput(editArea, Messages.ColumnFees, "fees"); //$NON-NLS-1$ // total bindings().bindMandatoryAmountInput(editArea, Messages.ColumnTotal, "total"); //$NON-NLS-1$ // date bindings().bindDatePicker(editArea, Messages.ColumnDate, "date"); //$NON-NLS-1$ } }
package name.abuchen.portfolio.ui.views.dashboard; import java.text.MessageFormat; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.OptionalDouble; import java.util.function.BiFunction; import java.util.stream.LongStream; import name.abuchen.portfolio.math.Risk.Drawdown; import name.abuchen.portfolio.math.Risk.Volatility; import name.abuchen.portfolio.model.Dashboard; import name.abuchen.portfolio.money.Money; import name.abuchen.portfolio.money.Values; import name.abuchen.portfolio.snapshot.PerformanceIndex; import name.abuchen.portfolio.ui.Messages; import name.abuchen.portfolio.ui.views.dashboard.heatmap.EarningsHeatmapWidget; import name.abuchen.portfolio.ui.views.dashboard.heatmap.InvestmentHeatmapWidget; import name.abuchen.portfolio.ui.views.dashboard.heatmap.PerformanceHeatmapWidget; import name.abuchen.portfolio.ui.views.dashboard.heatmap.YearlyPerformanceHeatmapWidget; import name.abuchen.portfolio.ui.views.dataseries.DataSeries; public enum WidgetFactory { HEADING(Messages.LabelHeading, Messages.LabelCommon, HeadingWidget::new), TOTAL_SUM(Messages.LabelTotalSum, Messages.LabelStatementOfAssets, (widget, data) -> IndicatorWidget.<Long>create(widget, data) .with(Values.Amount) .with((ds, period) -> { PerformanceIndex index = data.calculate(ds, period); int length = index.getTotals().length; return index.getTotals()[length - 1]; }) .withBenchmarkDataSeries(false) .build()), TTWROR(Messages.LabelTTWROR, Messages.ClientEditorLabelPerformance, (widget, data) -> IndicatorWidget.<Double>create(widget, data) .with(Values.Percent2) .with((ds, period) -> { PerformanceIndex index = data.calculate(ds, period); return index.getFinalAccumulatedPercentage(); }).build()), IRR(Messages.LabelIRR, Messages.ClientEditorLabelPerformance, (widget, data) -> IndicatorWidget.<Double>create(widget, data) .with(Values.Percent2) .with((ds, period) -> data.calculate(ds, period).getPerformanceIRR()) .withBenchmarkDataSeries(false) .build()), ABSOLUTE_CHANGE(Messages.LabelAbsoluteChange, Messages.LabelStatementOfAssets, (widget, data) -> IndicatorWidget.<Long>create(widget, data) .with(Values.Amount) .with((ds, period) -> { PerformanceIndex index = data.calculate(ds, period); int length = index.getTotals().length; return index.getTotals()[length - 1] - index.getTotals()[0]; }) .withBenchmarkDataSeries(false) .build()), DELTA(Messages.LabelDelta, Messages.LabelStatementOfAssets, (widget, data) -> IndicatorWidget.<Long>create(widget, data) .with(Values.Amount) .with((ds, period) -> { long[] d = data.calculate(ds, period).calculateDelta(); return d.length > 0 ? d[d.length - 1] : 0L; }) .withBenchmarkDataSeries(false) .build()), ABSOLUTE_DELTA(Messages.LabelAbsoluteDelta, Messages.LabelStatementOfAssets, (widget, data) -> IndicatorWidget.<Long>create(widget, data) .with(Values.Amount) .with((ds, period) -> { long[] d = data.calculate(ds, period).calculateAbsoluteDelta(); return d.length > 0 ? d[d.length - 1] : 0L; }) .withBenchmarkDataSeries(false) .build()), INVESTED_CAPITAL(Messages.LabelInvestedCapital, Messages.LabelStatementOfAssets, (widget, data) -> IndicatorWidget.<Long>create(widget, data) .with(Values.Amount) .with((ds, period) -> { long[] d = data.calculate(ds, period).calculateInvestedCapital(); return d.length > 0 ? d[d.length - 1] : 0L; }) .withBenchmarkDataSeries(false) .build()), ABSOLUTE_INVESTED_CAPITAL(Messages.LabelAbsoluteInvestedCapital, Messages.LabelStatementOfAssets, (widget, data) -> IndicatorWidget.<Long>create(widget, data) .with(Values.Amount) .with((ds, period) -> { long[] d = data.calculate(ds, period).calculateAbsoluteInvestedCapital(); return d.length > 0 ? d[d.length - 1] : 0L; }) .withBenchmarkDataSeries(false) .build()), MAXDRAWDOWN(Messages.LabelMaxDrawdown, Messages.LabelRiskIndicators, (widget, data) -> IndicatorWidget.<Double>create(widget, data) .with(Values.Percent2) .with((ds, period) -> { PerformanceIndex index = data.calculate(ds, period); return index.getDrawdown().getMaxDrawdown(); }) .withTooltip((ds, period) -> { DateTimeFormatter formatter = DateTimeFormatter .ofLocalizedDate(FormatStyle.LONG) .withZone(ZoneId.systemDefault()); PerformanceIndex index = data.calculate(ds, period); Drawdown drawdown = index.getDrawdown(); return MessageFormat.format(Messages.TooltipMaxDrawdown, formatter.format( drawdown.getIntervalOfMaxDrawdown().getStart()), formatter.format(drawdown.getIntervalOfMaxDrawdown().getEnd())); }) .withColoredValues(false) .build()), MAXDRAWDOWNDURATION(Messages.LabelMaxDrawdownDuration, Messages.LabelRiskIndicators, MaxDrawdownDurationWidget::new), VOLATILITY(Messages.LabelVolatility, Messages.LabelRiskIndicators, (widget, data) -> IndicatorWidget.<Double>create(widget, data) .with(Values.Percent2) .with((ds, period) -> { PerformanceIndex index = data.calculate(ds, period); return index.getVolatility().getStandardDeviation(); }) .withTooltip((ds, period) -> Messages.TooltipVolatility) .withColoredValues(false) .build()), SEMIVOLATILITY(Messages.LabelSemiVolatility, Messages.LabelRiskIndicators, (widget, data) -> IndicatorWidget.<Double>create(widget, data) .with(Values.Percent2) .with((ds, period) -> { PerformanceIndex index = data.calculate(ds, period); return index.getVolatility().getSemiDeviation(); }) .withTooltip((ds, period) -> { PerformanceIndex index = data.calculate(ds, period); Volatility vola = index.getVolatility(); return MessageFormat.format(Messages.TooltipSemiVolatility, Values.Percent5.format(vola.getExpectedSemiDeviation()), vola.getNormalizedSemiDeviationComparison(), Values.Percent5.format(vola.getStandardDeviation()), Values.Percent5.format(vola.getSemiDeviation())); }) .withColoredValues(false) .build()), CALCULATION(Messages.LabelPerformanceCalculation, Messages.ClientEditorLabelPerformance, PerformanceCalculationWidget::new), CHART(Messages.LabelPerformanceChart, Messages.ClientEditorLabelPerformance, (widget, data) -> new ChartWidget(widget, data, DataSeries.UseCase.PERFORMANCE)), ASSET_CHART(Messages.LabelAssetChart, Messages.LabelStatementOfAssets, (widget, data) -> new ChartWidget(widget, data, DataSeries.UseCase.STATEMENT_OF_ASSETS)), HEATMAP(Messages.LabelHeatmap, Messages.ClientEditorLabelPerformance, PerformanceHeatmapWidget::new), HEATMAP_YEARLY(Messages.LabelYearlyHeatmap, Messages.ClientEditorLabelPerformance, YearlyPerformanceHeatmapWidget::new), HEATMAP_EARNINGS(Messages.LabelHeatmapEarnings, Messages.LabelEarnings, EarningsHeatmapWidget::new), TRADES_BASIC_STATISTICS(Messages.LabelTradesBasicStatistics, Messages.LabelTrades, TradesWidget::new), TRADES_PROFIT_LOSS(Messages.LabelTradesProfitLoss, Messages.LabelTrades, TradesProfitLossWidget::new), TRADES_AVERAGE_HOLDING_PERIOD(Messages.LabelAverageHoldingPeriod, Messages.LabelTrades, TradesAverageHoldingPeriodWidget::new), TRADES_TURNOVER_RATIO(Messages.LabelTradesTurnoverRate, Messages.LabelTrades, (widget, data) -> IndicatorWidget.<Double>create(widget, data) .with(Values.Percent2) .with((ds, period) -> { PerformanceIndex index = data.calculate(ds, period); OptionalDouble average = LongStream.of(index.getTotals()).average(); if (!average.isPresent() || average.getAsDouble() <= 0) return 0.0; long buy = LongStream.of(index.getBuys()).sum(); long sell = LongStream.of(index.getSells()).sum(); return Long.min(buy, sell) / average.getAsDouble(); }) .withTooltip((ds, period) -> { PerformanceIndex index = data.calculate(ds, period); String currency = data.getCurrencyConverter().getTermCurrency(); OptionalDouble average = LongStream.of(index.getTotals()).average(); long buy = LongStream.of(index.getBuys()).sum(); long sell = LongStream.of(index.getSells()).sum(); return MessageFormat.format(Messages.TooltipTurnoverRate, Values.Money.format(Money.of(currency, buy)), Values.Money.format(Money.of(currency, sell)), Values.Money.format(Money.of(currency, (long)average.orElse(0))), Values.Percent2.format(average.isPresent() && average.getAsDouble() > 0 ? Long.min(buy, sell) / average.getAsDouble() : 0)); }) .withColoredValues(false) .build()), HEATMAP_INVESTMENTS(Messages.LabelHeatmapInvestments, Messages.LabelTrades, InvestmentHeatmapWidget::new), CURRENT_DATE(Messages.LabelCurrentDate, Messages.LabelCommon, CurrentDateWidget::new), EXCHANGE_RATE(Messages.LabelExchangeRate, Messages.LabelCommon, ExchangeRateWidget::new), ACTIVITY_CHART(Messages.LabelTradingActivityChart, Messages.LabelCommon, ActivityWidget::new), // typo is API now!! VERTICAL_SPACEER(Messages.LabelVerticalSpacer, Messages.LabelCommon, VerticalSpacerWidget::new); private String label; private String group; private BiFunction<Dashboard.Widget, DashboardData, WidgetDelegate<?>> createFunction; private WidgetFactory(String label, String group, BiFunction<Dashboard.Widget, DashboardData, WidgetDelegate<?>> createFunction) { this.label = label; this.group = group; this.createFunction = createFunction; } public String getLabel() { return label; } public String getGroup() { return group; } public WidgetDelegate<?> create(Dashboard.Widget widget, DashboardData data) { return this.createFunction.apply(widget, data); } }
package org.navalplanner.web.labels; import static org.navalplanner.web.I18nHelper._; import java.util.List; import org.hibernate.validator.InvalidValue; import org.navalplanner.business.common.exceptions.ValidationException; import org.navalplanner.business.labels.entities.LabelType; import org.navalplanner.web.common.IMessagesForUser; import org.navalplanner.web.common.Level; import org.navalplanner.web.common.MessagesForUser; import org.navalplanner.web.common.OnlyOneVisible; import org.navalplanner.web.common.Util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.WrongValueException; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Grid; import org.zkoss.zul.Messagebox; import org.zkoss.zul.Window; /** * CRUD Controller for {@link LabelType} * * @author Diego Pino Garcia <dpino@igalia.com> */ public class LabelTypeCRUDController extends GenericForwardComposer { @Autowired ILabelTypeModel labelTypeModel; private Window listWindow; private Window editWindow; private OnlyOneVisible visibility; private IMessagesForUser messagesForUser; private Component messagesContainer; public LabelTypeCRUDController() { } @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); comp.setVariable("controller", this, true); messagesForUser = new MessagesForUser(messagesContainer); getVisibility().showOnly(listWindow); } public OnlyOneVisible getVisibility() { if (visibility == null) { visibility = new OnlyOneVisible(listWindow, editWindow); } return visibility; } @Transactional public List<LabelType> getLabelTypes() { return labelTypeModel.getLabelTypes(); } public LabelType getLabelType() { return labelTypeModel.getLabelType(); } /** * Pop up confirm remove dialog * * @param labelType */ public void confirmDelete(LabelType labelType) { try { if (Messagebox.show(_("Delete item. Are you sure?"), _("Confirm"), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK) { labelTypeModel.confirmDelete(labelType); Grid labelTypes = (Grid) listWindow .getFellowIfAny("labelTypes"); if (labelTypes != null) { Util.reloadBindings(labelTypes); } } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void goToCreateForm() { labelTypeModel.prepareForCreate(); editWindow.setTitle(_("Create label type")); getVisibility().showOnly(editWindow); Util.reloadBindings(editWindow); } public void save() { try { labelTypeModel.confirmSave(); goToList(); messagesForUser.showMessage(Level.INFO, _("Label type saved")); } catch (ValidationException e) { showInvalidValues(e); } } private void showInvalidValues(ValidationException e) { for (InvalidValue invalidValue : e.getInvalidValues()) { Object value = invalidValue.getBean(); if (value instanceof LabelType) { validateLabelType(invalidValue); } } } private void validateLabelType(InvalidValue invalidValue) { Component component = editWindow.getFellowIfAny(invalidValue .getPropertyName()); if (component != null) { throw new WrongValueException(component, invalidValue.getMessage()); } } private void goToList() { getVisibility().showOnly(listWindow); Util.reloadBindings(listWindow); } }
package net.beaconcontroller.core.internal; import java.io.IOException; import java.net.InetAddress; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectionKey; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import net.beaconcontroller.core.IBeaconProvider; import net.beaconcontroller.core.IOFInitializerListener; import net.beaconcontroller.core.IOFMessageListener; import net.beaconcontroller.core.IOFMessageListener.Command; import net.beaconcontroller.core.IOFSwitch; import net.beaconcontroller.core.IOFSwitchFilter; import net.beaconcontroller.core.IOFSwitchListener; import net.beaconcontroller.core.io.internal.OFStream; import net.beaconcontroller.core.io.internal.SelectListener; import net.beaconcontroller.core.io.internal.IOLoop; import net.beaconcontroller.packet.IPv4; import org.openflow.io.OFMessageInStream; import org.openflow.io.OFMessageOutStream; import org.openflow.protocol.OFEchoReply; import org.openflow.protocol.OFEchoRequest; import org.openflow.protocol.OFError; import org.openflow.protocol.OFError.OFBadActionCode; import org.openflow.protocol.OFError.OFBadRequestCode; import org.openflow.protocol.OFError.OFErrorType; import org.openflow.protocol.OFError.OFFlowModFailedCode; import org.openflow.protocol.OFError.OFHelloFailedCode; import org.openflow.protocol.OFError.OFPortModFailedCode; import org.openflow.protocol.OFError.OFQueueOpFailedCode; import org.openflow.protocol.OFFeaturesReply; import org.openflow.protocol.OFFlowMod; import org.openflow.protocol.OFGetConfigReply; import org.openflow.protocol.OFMatch; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPort; import org.openflow.protocol.OFSetConfig; import org.openflow.protocol.OFType; import org.openflow.protocol.factory.BasicFactory; import org.openflow.util.U16; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author David Erickson (daviderickson@cs.stanford.edu) - 04/04/10 * */ public class Controller implements IBeaconProvider, SelectListener { protected static Logger log = LoggerFactory.getLogger(Controller.class); protected static int LIVENESS_POLL_INTERVAL = 1000; protected static int LIVENESS_TIMEOUT = 5000; protected static String SWITCH_REQUIREMENTS_TIMER_KEY = "SW_REQ_TIMER"; protected ConcurrentHashMap<Long, IOFSwitchExt> activeSwitches; protected CopyOnWriteArraySet<IOFSwitchExt> allSwitches; protected Map<String,String> callbackOrdering; protected boolean deletePreExistingFlows = true; protected ExecutorService es; protected BasicFactory factory; protected boolean immediate = false; protected CopyOnWriteArrayList<IOFInitializerListener> initializerList; protected ConcurrentHashMap<IOFSwitchExt, CopyOnWriteArrayList<IOFInitializerListener>> initializerMap; protected String listenAddress; protected int listenPort = 6633; protected IOLoop listenerIOLoop; protected volatile boolean listenerStarted = false; protected ServerSocketChannel listenSock; protected Timer livenessTimer; protected ConcurrentMap<OFType, List<IOFMessageListener>> messageListeners; protected boolean noDelay = true; protected volatile boolean shuttingDown = false; protected Set<IOFSwitchListener> switchListeners; protected List<IOLoop> switchIOLoops; protected Integer threadCount; protected BlockingQueue<Update> updates; protected Thread updatesThread; protected class Update { public IOFSwitch sw; public boolean added; public Update(IOFSwitch sw, boolean added) { this.sw = sw; this.added = added; } } public Controller() { this.messageListeners = new ConcurrentHashMap<OFType, List<IOFMessageListener>>(); this.switchListeners = new CopyOnWriteArraySet<IOFSwitchListener>(); this.updates = new LinkedBlockingQueue<Update>(); } public void handleEvent(SelectionKey key, Object arg) throws IOException { if (arg instanceof ServerSocketChannel) handleListenEvent(key, (ServerSocketChannel)arg); else handleSwitchEvent(key, (IOFSwitchExt) arg); } protected void handleListenEvent(SelectionKey key, ServerSocketChannel ssc) throws IOException { SocketChannel sock = listenSock.accept(); log.info("Switch connected from {}", sock.toString()); sock.socket().setTcpNoDelay(this.noDelay); sock.configureBlocking(false); sock.socket().setSendBufferSize(1024*1024); OFSwitchImpl sw = new OFSwitchImpl(); // Try to even the # of switches per thread // TODO something more intelligent here based on load IOLoop sl = null; for (IOLoop loop : switchIOLoops) { if (sl == null || loop.getStreams().size() < sl.getStreams().size()) sl = loop; } // register initially with no ops because we need the key to init the stream SelectionKey switchKey = sl.registerBlocking(sock, 0, sw); OFStream stream = new OFStream(sock, factory, switchKey, sl); stream.setImmediate(this.immediate); sw.setInputStream(stream); sw.setOutputStream(stream); sw.setSocketChannel(sock); sw.setBeaconProvider(this); sw.transitionToState(SwitchState.HELLO_SENT); addSwitch(sw); // Send HELLO stream.write(factory.getMessage(OFType.HELLO)); // register for read switchKey.interestOps(SelectionKey.OP_READ); sl.addStream(stream); log.info("Added switch {} to IOLoop {}", sw, sl); sl.wakeup(); } protected void handleSwitchEvent(SelectionKey key, IOFSwitchExt sw) { OFStream out = ((OFStream)sw.getOutputStream()); OFStream in = (OFStream) sw.getInputStream(); try { /** * A key may not be valid here if it has been disconnected while * it was in a select operation. */ if (!key.isValid()) return; if (key.isReadable()) { List<OFMessage> msgs = in.read(); if (msgs == null) { // graceful disconnect disconnectSwitch(key, sw); return; } sw.setLastReceivedMessageTime(System.currentTimeMillis()); handleMessages(sw, msgs); } if (key.isWritable()) { out.clearSelect(); key.interestOps(SelectionKey.OP_READ); } if (out.getWriteFailure()) { disconnectSwitch(key, sw); return; } } catch (IOException e) { // if we have an exception, disconnect the switch disconnectSwitch(key, sw); } catch (CancelledKeyException e) { // if we have an exception, disconnect the switch disconnectSwitch(key, sw); } } /** * Disconnect the switch from Beacon */ protected void disconnectSwitch(SelectionKey key, IOFSwitchExt sw) { key.cancel(); OFStream stream = (OFStream) sw.getInputStream(); stream.getIOLoop().removeStream(stream); removeSwitch(sw); try { sw.getSocketChannel().socket().close(); } catch (IOException e1) { } log.info("Switch disconnected {}", sw); } /** * Handle replies to certain OFMessages, and pass others off to listeners * @param sw * @param msgs * @throws IOException */ @SuppressWarnings("unchecked") protected void handleMessages(IOFSwitchExt sw, List<OFMessage> msgs) throws IOException { for (OFMessage m : msgs) { // If we detect a write failure, break early so we can disconnect if (((OFStream)sw.getInputStream()).getWriteFailure()) { break; } // Always handle ECHO REQUESTS, regardless of state switch (m.getType()) { case ECHO_REQUEST: OFMessageInStream in = sw.getInputStream(); OFMessageOutStream out = sw.getOutputStream(); OFEchoReply reply = (OFEchoReply) in .getMessageFactory().getMessage( OFType.ECHO_REPLY); reply.setXid(m.getXid()); out.write(reply); break; case ECHO_REPLY: // *Note, ECHO REPLIES need no handling due to last message timestamp break; case ERROR: logError(sw, (OFError)m); // fall through intentionally so error can be listened for default: switch (sw.getState()) { case HELLO_SENT: if (m.getType() == OFType.HELLO) { log.debug("HELLO from {}", sw); sw.transitionToState(SwitchState.FEATURES_REQUEST_SENT); // Send initial Features Request sw.getOutputStream().write(factory.getMessage(OFType.FEATURES_REQUEST)); } break; case FEATURES_REQUEST_SENT: if (m.getType() == OFType.FEATURES_REPLY) { log.debug("Features Reply from {}", sw); sw.setFeaturesReply((OFFeaturesReply) m); sw.transitionToState(SwitchState.GET_CONFIG_REQUEST_SENT); // Set config and request to receive the config OFSetConfig config = (OFSetConfig) factory .getMessage(OFType.SET_CONFIG); config.setMissSendLength((short) 0xffff) .setLengthU(OFSetConfig.MINIMUM_LENGTH); sw.getOutputStream().write(config); sw.getOutputStream().write(factory.getMessage(OFType.BARRIER_REQUEST)); sw.getOutputStream().write(factory.getMessage(OFType.GET_CONFIG_REQUEST)); } break; case GET_CONFIG_REQUEST_SENT: if (m.getType() == OFType.GET_CONFIG_REPLY) { OFGetConfigReply cr = (OFGetConfigReply) m; if (cr.getMissSendLength() == (short)0xffff) { log.debug("Config Reply from {} confirms miss length set to 0xffff", sw); sw.transitionToState(SwitchState.INITIALIZING); // Add all existing initializers to the list this.initializerMap.put(sw, (CopyOnWriteArrayList<IOFInitializerListener>) initializerList.clone()); log.debug("Remaining initializers for switch {}: {}", sw, this.initializerMap.get(sw)); // Delete all pre-existing flows if (deletePreExistingFlows) { OFMatch match = new OFMatch().setWildcards(OFMatch.OFPFW_ALL); OFMessage fm = ((OFFlowMod) sw.getInputStream().getMessageFactory() .getMessage(OFType.FLOW_MOD)) .setMatch(match) .setCommand(OFFlowMod.OFPFC_DELETE) .setOutPort(OFPort.OFPP_NONE) .setLength(U16.t(OFFlowMod.MINIMUM_LENGTH)); sw.getOutputStream().write(fm); sw.getOutputStream().write(factory.getMessage(OFType.BARRIER_REQUEST)); } } else { log.error("Switch {} refused to set miss send length to 0xffff, disconnecting", sw); disconnectSwitch(((OFStream)sw.getInputStream()).getKey(), sw); return; } } break; case INITIALIZING: // Are there pending initializers for this switch? CopyOnWriteArrayList<IOFInitializerListener> initializers = initializerMap.get(sw); if (initializers != null) { Iterator<IOFInitializerListener> it = initializers.iterator(); if (it.hasNext()) { IOFInitializerListener listener = it.next(); try { listener.initializerReceive(sw, m); } catch (Exception e) { log.error( "Error calling initializer listener: {} on switch: {} for message: {}, removing listener", new Object[] { listener, sw, m }); initializers.remove(listener); } } if (initializers.size() == 0) { // no initializers remaining initializerMap.remove(sw); sw.transitionToState(SwitchState.ACTIVE); // Add switch to active list addActiveSwitch(sw); } } else { sw.transitionToState(SwitchState.ACTIVE); // Add switch to active list addActiveSwitch(sw); } break; case ACTIVE: List<IOFMessageListener> listeners = messageListeners .get(m.getType()); if (listeners != null) { for (IOFMessageListener listener : listeners) { try { if (listener instanceof IOFSwitchFilter) { if (!((IOFSwitchFilter)listener).isInterested(sw)) { continue; } } if (Command.STOP.equals(listener.receive(sw, m))) { break; } } catch (Exception e) { log.error("Failure calling listener ["+ listener.toString()+ "] with message ["+m.toString()+ "]", e); } } } else { log.warn("Unhandled OF Message: {} from {}", m, sw); } break; } // end switch(sw.getState()) } // end switch(m.getType()) } } protected void logError(IOFSwitch sw, OFError error) { // TODO Move this to OFJ with *much* better printing OFErrorType et = OFErrorType.values()[0xffff & error.getErrorType()]; switch (et) { case OFPET_HELLO_FAILED: OFHelloFailedCode hfc = OFHelloFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, hfc, sw}); break; case OFPET_BAD_REQUEST: OFBadRequestCode brc = OFBadRequestCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, brc, sw}); break; case OFPET_BAD_ACTION: OFBadActionCode bac = OFBadActionCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, bac, sw}); break; case OFPET_FLOW_MOD_FAILED: OFFlowModFailedCode fmfc = OFFlowModFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, fmfc, sw}); break; case OFPET_PORT_MOD_FAILED: OFPortModFailedCode pmfc = OFPortModFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, pmfc, sw}); break; case OFPET_QUEUE_OP_FAILED: OFQueueOpFailedCode qofc = OFQueueOpFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, qofc, sw}); break; default: break; } } public synchronized void addOFMessageListener(OFType type, IOFMessageListener listener) { List<IOFMessageListener> listeners = messageListeners.get(type); if (listeners == null) { // Set atomically if no list exists messageListeners.putIfAbsent(type, new CopyOnWriteArrayList<IOFMessageListener>()); // Get the list, the new one or any other, guaranteed not null listeners = messageListeners.get(type); } if (callbackOrdering != null && callbackOrdering.containsKey(type.toString()) && callbackOrdering.get(type.toString()).contains(listener.getName())) { String order = callbackOrdering.get(type.toString()); String[] orderArray = order.split(","); int myPos = 0; for (int i = 0; i < orderArray.length; ++i) { orderArray[i] = orderArray[i].trim(); if (orderArray[i].equals(listener.getName())) myPos = i; } List<String> beforeList = Arrays.asList(Arrays.copyOfRange(orderArray, 0, myPos)); boolean added = false; // only try and walk if there are already listeners if (listeners.size() > 0) { // Walk through and determine where to insert for (int i = 0; i < listeners.size(); ++i) { if (beforeList.contains(listeners.get(i).getName())) continue; listeners.add(i, listener); added = true; break; } } if (!added) { listeners.add(listener); } } else { listeners.add(listener); } } public synchronized void removeOFMessageListener(OFType type, IOFMessageListener listener) { List<IOFMessageListener> listeners = messageListeners.get(type); if (listeners != null) { listeners.remove(listener); } } public void startUp() throws IOException { initializerList = new CopyOnWriteArrayList<IOFInitializerListener>(); initializerMap = new ConcurrentHashMap<IOFSwitchExt, CopyOnWriteArrayList<IOFInitializerListener>>(); switchIOLoops = new ArrayList<IOLoop>(); activeSwitches = new ConcurrentHashMap<Long, IOFSwitchExt>(); allSwitches = new CopyOnWriteArraySet<IOFSwitchExt>(); if (threadCount == null) threadCount = 1; this.factory = new BasicFactory(); // Static number of threads equal to processor cores (+1 for listen loop) es = Executors.newFixedThreadPool(threadCount+1); // Launch one select loop per threadCount and start running for (int i = 0; i < threadCount; ++i) { final IOLoop sl = new IOLoop(this, 500, i); switchIOLoops.add(sl); es.execute(new Runnable() { public void run() { try { log.info("Started thread {} for IOLoop {}", Thread.currentThread(), sl); sl.doLoop(); } catch (Exception e) { log.error("Exception during worker loop, terminating thread", e); } }} ); } updatesThread = new Thread(new Runnable () { @Override public void run() { while (true) { try { Update update = updates.take(); if (switchListeners != null) { for (IOFSwitchListener listener : switchListeners) { try { if (update.added) listener.addedSwitch(update.sw); else listener.removedSwitch(update.sw); } catch (Exception e) { log.error("Error calling switch listener", e); } } } } catch (InterruptedException e) { log.warn("Controller updates thread interupted", e); if (shuttingDown) return; } } }}, "Controller Updates"); updatesThread.start(); livenessTimer = new Timer(); livenessTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { checkSwitchLiveness(); } }, LIVENESS_POLL_INTERVAL, LIVENESS_POLL_INTERVAL); log.info("Beacon Core Started"); } public synchronized void startListener() { if (listenerStarted) return; try { listenSock = ServerSocketChannel.open(); listenSock.socket().setReceiveBufferSize(512*1024); listenSock.configureBlocking(false); if (listenAddress != null) { listenSock.socket().bind( new java.net.InetSocketAddress(InetAddress .getByAddress(IPv4 .toIPv4AddressBytes(listenAddress)), listenPort)); } else { listenSock.socket().bind(new java.net.InetSocketAddress(listenPort)); } listenSock.socket().setReuseAddress(true); listenerIOLoop = new IOLoop(this, -1); // register this connection for accepting listenerIOLoop.register(listenSock, SelectionKey.OP_ACCEPT, listenSock); } catch (IOException e) { log.error("Failure opening listening socket", e); System.exit(-1); } log.info("Controller listening on {}:{}", listenAddress == null ? "*" : listenAddress, listenPort); es.execute(new Runnable() { public void run() { // Start the listen loop try { listenerIOLoop.doLoop(); } catch (Exception e) { log.error("Exception during accept loop, terminating thread", e); } }} ); listenerStarted = true; } public synchronized void stopListener() { if (!listenerStarted) return; // shutdown listening for new switches try { listenerIOLoop.shutdown(); listenSock.socket().close(); listenSock.close(); } catch (IOException e) { log.error("Failure shutting down listening socket", e); } finally { listenerStarted = false; } } public void shutDown() throws IOException { shuttingDown = true; livenessTimer.cancel(); stopListener(); // close the switch connections for (Iterator<Entry<Long, IOFSwitchExt>> it = activeSwitches.entrySet().iterator(); it.hasNext();) { Entry<Long, IOFSwitchExt> entry = it.next(); entry.getValue().getSocketChannel().socket().close(); it.remove(); } // shutdown the connected switch select loops for (IOLoop sl : switchIOLoops) { sl.shutdown(); } es.shutdown(); updatesThread.interrupt(); log.info("Beacon Core Shutdown"); } /** * Checks all the switches to ensure they are still connected by sending * an echo request and receiving a response. */ protected void checkSwitchLiveness() { long now = System.currentTimeMillis(); log.trace("Liveness timer running"); for (Iterator<IOFSwitchExt> it = allSwitches.iterator(); it.hasNext();) { IOFSwitchExt sw = it.next(); long last = sw.getLastReceivedMessageTime(); SelectionKey key = ((OFStream)sw.getInputStream()).getKey(); if (now - last >= (2*LIVENESS_TIMEOUT)) { log.info("Switch liveness timeout detected {}ms, disconnecting {}", now - last, sw); disconnectSwitch(key, sw); } else if (now - last >= LIVENESS_TIMEOUT) { // send echo OFEchoRequest echo = new OFEchoRequest(); try { sw.getOutputStream().write(echo); } catch (IOException e) { log.error("Failure sending liveness probe, disconnecting switch " + sw.toString(), e); disconnectSwitch(key, sw); } } } } /** * @param callbackOrdering the callbackOrdering to set */ public void setCallbackOrdering(Map<String, String> callbackOrdering) { this.callbackOrdering = callbackOrdering; } /** * @return the messageListeners */ protected ConcurrentMap<OFType, List<IOFMessageListener>> getMessageListeners() { return messageListeners; } /** * @param messageListeners the messageListeners to set */ protected void setMessageListeners( ConcurrentMap<OFType, List<IOFMessageListener>> messageListeners) { this.messageListeners = messageListeners; } @Override public Map<Long, IOFSwitch> getSwitches() { return Collections.unmodifiableMap(new HashMap<Long, IOFSwitch>(this.activeSwitches)); } /** * This is only to be used for testing * @return */ protected Set<IOFSwitchExt> getAllSwitches() { return Collections.unmodifiableSet(this.allSwitches); } @Override public void addOFSwitchListener(IOFSwitchListener listener) { this.switchListeners.add(listener); } @Override public void removeOFSwitchListener(IOFSwitchListener listener) { this.switchListeners.remove(listener); } /** * Adds a switch that has transitioned into the HELLO_SENT state * * @param sw the new switch */ protected void addSwitch(IOFSwitchExt sw) { this.allSwitches.add(sw); } /** * Adds a switch that has transitioned into the ACTIVE state, then * calls all related listeners * @param sw the new switch */ protected void addActiveSwitch(IOFSwitchExt sw) { this.activeSwitches.put(sw.getId(), sw); Update update = new Update(sw, true); try { this.updates.put(update); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } /** * Removes a disconnected switch and calls all related listeners * @param sw the switch that has disconnected */ protected void removeSwitch(IOFSwitchExt sw) { this.allSwitches.remove(sw); // If active remove from DPID indexed map if (SwitchState.ACTIVE == sw.getState()) { if (!this.activeSwitches.remove(sw.getId(), sw)) { log.warn("Removing switch {} has already been replaced", sw); } Update update = new Update(sw, false); try { this.updates.put(update); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } } @Override public Map<OFType, List<IOFMessageListener>> getListeners() { return Collections.unmodifiableMap(this.messageListeners); } /** * @param listenAddress the listenAddress to set */ public void setListenAddress(String listenAddress) { this.listenAddress = listenAddress; } /** * @param listenPort the listenPort to set */ public void setListenPort(int listenPort) { this.listenPort = listenPort; } /** * @param threadCount the threadCount to set */ public void setThreadCount(Integer threadCount) { this.threadCount = threadCount; } /** * Configures all switch output streams to attempt to flush on every write * @param immediate the immediate to set */ public void setImmediate(boolean immediate) { this.immediate = immediate; } /** * Used to set whether newly connected sockets have no delay turned on, * defaults to true. * @param noDelay the noDelay to set */ public void setNoDelay(boolean noDelay) { this.noDelay = noDelay; } /** * @param deletePreExistingFlows the deletePreExistingFlows to set */ public void setDeletePreExistingFlows(boolean deletePreExistingFlows) { this.deletePreExistingFlows = deletePreExistingFlows; } @Override public void addOFInitializerListener(IOFInitializerListener listener) { this.initializerList.add(listener); } @Override public void removeOFInitListener(IOFInitializerListener listener) { this.initializerList.remove(listener); Iterator<Map.Entry<IOFSwitchExt, CopyOnWriteArrayList<IOFInitializerListener>>> it = this.initializerMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<IOFSwitchExt, CopyOnWriteArrayList<IOFInitializerListener>> entry = it.next(); entry.getValue().remove(listener); } } @Override public void initializationComplete(IOFSwitch sw, IOFInitializerListener listener) { // TODO this cast isn't ideal.. is there a better alternative? log.debug("Initializer for switch {} has completed: {}", sw, listener); IOFSwitchExt swExt = (IOFSwitchExt) sw; CopyOnWriteArrayList<IOFInitializerListener> list = this.initializerMap.get(swExt); if (list != null) { list.remove(listener); log.debug("Remaining initializers for switch {}: {}", sw, list); if (list.isEmpty()) { this.initializerMap.remove(swExt); swExt.transitionToState(SwitchState.ACTIVE); } } } }
package com.netflix.nicobar.groovy2.compile; import static org.testng.Assert.assertTrue; import java.lang.reflect.Field; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.PathScriptArchive; import com.netflix.nicobar.groovy2.internal.compile.Groovy2Compiler; import com.netflix.nicobar.groovy2.testutil.GroovyTestResourceUtil; import com.netflix.nicobar.groovy2.testutil.GroovyTestResourceUtil.TestScript; public class Groovy2CompilerTest { @SuppressWarnings("unchecked") @Test public void testCustomiizerParamsProcessing() throws Exception { Groovy2Compiler compiler; List<CompilationCustomizer> customizers; Map<String, Object> compilerParams; Field f = Groovy2Compiler.class.getDeclaredField("customizerClassNames"); f.setAccessible(true); // empty parameters map compiler = new Groovy2Compiler(new HashMap<String, Object>()); customizers = (List<CompilationCustomizer>)f.get(compiler); assertTrue(customizers.size() == 0, "no valid objects expected"); // null value customizers parameter compilerParams = new HashMap<String, Object>(); compilerParams.put(Groovy2Compiler.GROOVY2_COMPILER_PARAMS_CUSTOMIZERS, null); compiler = new Groovy2Compiler(compilerParams); customizers = (List)f.get(compiler); assertTrue(customizers.size() == 0, "no valid objects expected"); // list with valid customizer compilerParams = new HashMap<String, Object>(); compilerParams.put(Groovy2Compiler.GROOVY2_COMPILER_PARAMS_CUSTOMIZERS, Arrays.asList(new String[] {"org.codehaus.groovy.control.customizers.ImportCustomizer"})); compiler = new Groovy2Compiler(compilerParams); customizers = (List)f.get(compiler); assertTrue(customizers.size() == 1, "one valid object expected"); // list with invalid objects compilerParams = new HashMap<String, Object>(); compilerParams.put(Groovy2Compiler.GROOVY2_COMPILER_PARAMS_CUSTOMIZERS, Arrays.asList(new Object[] {"org.codehaus.groovy.control.customizers.ImportCustomizer", "org.codehaus.groovy.control.customizers.ImportCustomizer", new HashMap<String, Object>(), null})); compiler = new Groovy2Compiler(compilerParams); customizers = (List)f.get(compiler); assertTrue(customizers.size() == 2, "two valid objects expected"); } @Test public void testCompile() throws Exception { Groovy2Compiler compiler; List<CompilationCustomizer> customizers; Map<String, Object> compilerParams; Path scriptRootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.HELLO_WORLD); PathScriptArchive scriptArchive = new PathScriptArchive.Builder(scriptRootPath) .setRecurseRoot(false) .addFile(TestScript.HELLO_WORLD.getScriptPath()) .build(); compilerParams = new HashMap<String, Object>(); compilerParams.put(Groovy2Compiler.GROOVY2_COMPILER_PARAMS_CUSTOMIZERS, Arrays.asList(new Object[] {"testmodule.customizers.TestCompilationCustomizer"})); compiler = new Groovy2Compiler(compilerParams); compiler.compile(scriptArchive, null, scriptRootPath); } }
package com.yahoo.vespa.hosted.node.admin.component; import com.yahoo.vespa.athenz.api.AthenzService; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; /** * Information necessary to e.g. establish communication with the config servers * * @author hakon */ public class ConfigServerInfo { private final URI loadBalancerEndpoint; private final AthenzService configServerIdentity; private final Function<String, URI> configServerHostnameToUriMapper; private final List<URI> configServerURIs; public ConfigServerInfo(String loadBalancerHostName, List<String> configServerHostNames, String scheme, int port, AthenzService configServerAthenzIdentity) { this.loadBalancerEndpoint = createLoadBalancerEndpoint(loadBalancerHostName, scheme, port); this.configServerIdentity = configServerAthenzIdentity; this.configServerHostnameToUriMapper = hostname -> URI.create(scheme + "://" + hostname + ":" + port); this.configServerURIs = configServerHostNames.stream() .map(configServerHostnameToUriMapper) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } private static URI createLoadBalancerEndpoint(String loadBalancerHost, String scheme, int port) { return URI.create(scheme + "://" + loadBalancerHost + ":" + port); } public List<URI> getConfigServerUris() { return configServerURIs; } public URI getConfigServerUri(String hostname) { return configServerHostnameToUriMapper.apply(hostname); } public URI getLoadBalancerEndpoint() { return loadBalancerEndpoint; } public AthenzService getConfigServerIdentity() { return configServerIdentity; } }
package com.yahoo.vespa.hosted.provision.maintenance; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ApplicationLockException; import com.yahoo.config.provision.Deployer; import com.yahoo.config.provision.Deployment; import com.yahoo.config.provision.HostSpec; import com.yahoo.config.provision.NodeResources; import com.yahoo.config.provision.NodeType; import com.yahoo.config.provision.TransientException; import com.yahoo.jdisc.Metric; import com.yahoo.jdisc.core.Main; import com.yahoo.log.LogLevel; import com.yahoo.transaction.Mutex; import com.yahoo.vespa.hosted.provision.Node; import com.yahoo.vespa.hosted.provision.NodeList; import com.yahoo.vespa.hosted.provision.NodeRepository; import com.yahoo.vespa.hosted.provision.node.Agent; import com.yahoo.vespa.hosted.provision.provisioning.DockerHostCapacity; import com.yahoo.vespa.hosted.provision.provisioning.HostProvisioner; import com.yahoo.vespa.hosted.provision.provisioning.HostResourcesCalculator; import com.yahoo.vespa.hosted.provision.provisioning.NodePrioritizer; import com.yahoo.yolean.Exceptions; import java.io.Closeable; import java.io.IOException; import java.time.Clock; import java.time.Duration; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.logging.Logger; public class Rebalancer extends Maintainer { private final Deployer deployer; private final HostResourcesCalculator hostResourcesCalculator; private final Optional<HostProvisioner> hostProvisioner; private final Metric metric; private final Clock clock; public Rebalancer(Deployer deployer, NodeRepository nodeRepository, HostResourcesCalculator hostResourcesCalculator, Optional<HostProvisioner> hostProvisioner, Metric metric, Clock clock, Duration interval) { super(nodeRepository, interval); this.deployer = deployer; this.hostResourcesCalculator = hostResourcesCalculator; this.hostProvisioner = hostProvisioner; this.metric = metric; this.clock = clock; } @Override protected void maintain() { if (hostProvisioner.isPresent()) return; // All nodes will be allocated on new hosts, so rebalancing makes no sense // Work with an unlocked snapshot as this can take a long time and full consistency is not needed NodeList allNodes = nodeRepository().list(); updateSkewMetric(allNodes); if ( ! zoneIsStable(allNodes)) return; Move bestMove = findBestMove(allNodes); if (bestMove == Move.none) return; deployTo(bestMove); } /** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */ private void updateSkewMetric(NodeList allNodes) { DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator); double totalSkew = 0; int hostCount = 0; for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) { hostCount++; totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host)); } metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null); } private boolean zoneIsStable(NodeList allNodes) { NodeList active = allNodes.state(Node.State.active); if (active.stream().anyMatch(node -> node.allocation().get().membership().retired())) return false; if (active.stream().anyMatch(node -> node.status().wantToRetire())) return false; return true; } /** * Find the best move to reduce allocation skew and returns it. * Returns Move.none if no moves can be made to reduce skew. */ private Move findBestMove(NodeList allNodes) { DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator); Move bestMove = Move.none; for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) { if (node.parentHostname().isEmpty()) continue; for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) { if (toHost.hostname().equals(node.parentHostname().get())) continue; if ( ! capacity.freeCapacityOf(toHost).satisfies(node.flavor().resources())) continue; double skewReductionAtFromHost = skewReductionByRemoving(node, allNodes.parentOf(node).get(), capacity); double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity); double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost; if (netSkewReduction > bestMove.netSkewReduction) bestMove = new Move(node, toHost, netSkewReduction); } } return bestMove; } /** Returns true only if this operation changes the state of the wantToRetire flag */ private boolean markWantToRetire(Node node, boolean wantToRetire) { try (Mutex lock = nodeRepository().lock(node)) { Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname()); if (nodeToMove.isEmpty()) return false; if (nodeToMove.get().state() != Node.State.active) return false; if (node.status().wantToRetire() == wantToRetire) return false; nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock); return true; } } /** * Try a redeployment to effect the chosen move. * If it can be done, that's ok; we'll try this or another move later. * * @return true if the move was done, false if it couldn't be */ private boolean deployTo(Move move) { ApplicationId application = move.node.allocation().get().owner(); try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) { if ( ! deployment.isValid()) return false; boolean couldMarkRetiredNow = markWantToRetire(move.node, true); if ( ! couldMarkRetiredNow) return false; try { if ( ! deployment.prepare()) return false; if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname()))) return false; // Deployment is not moving the from node to the target we identified for some reason if ( ! deployment.activate()) return false; log.info("Rebalancer redeployed " + application + " to " + move); return true; } finally { markWantToRetire(move.node, false); // Necessary if this failed, no-op otherwise } } } private double skewReductionByRemoving(Node node, Node fromHost, DockerHostCapacity capacity) { NodeResources freeHostCapacity = capacity.freeCapacityOf(fromHost); double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity); double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().justNumbers())); return skewBefore - skewAfter; } private double skewReductionByAdding(Node node, Node toHost, DockerHostCapacity capacity) { NodeResources freeHostCapacity = capacity.freeCapacityOf(toHost); double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity); double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.flavor().resources().justNumbers())); return skewBefore - skewAfter; } private static class Move { static final Move none = new Move(null, null, 0); final Node node; final Node toHost; final double netSkewReduction; Move(Node node, Node toHost, double netSkewReduction) { this.node = node; this.toHost = toHost; this.netSkewReduction = netSkewReduction; } @Override public String toString() { return "move " + ( node == null ? "none" : (node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]")); } } private static class MaintenanceDeployment implements Closeable { private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName()); private final ApplicationId application; private final Optional<Mutex> lock; private final Optional<Deployment> deployment; public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) { this.application = application; lock = tryLock(application, nodeRepository); deployment = tryDeployment(lock, application, deployer, nodeRepository); } /** Return whether this is - as yet - functional and can be used to carry out the deployment */ public boolean isValid() { return deployment.isPresent(); } private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) { try { // Use a short lock to avoid interfering with change deployments return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1))); } catch (ApplicationLockException e) { return Optional.empty(); } } private Optional<Deployment> tryDeployment(Optional<Mutex> lock, ApplicationId application, Deployer deployer, NodeRepository nodeRepository) { if (lock.isEmpty()) return Optional.empty(); if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty(); return deployer.deployFromLocalActive(application); } public boolean prepare() { return doStep(() -> deployment.get().prepare()); } public boolean activate() { return doStep(() -> deployment.get().activate()); } private boolean doStep(Runnable action) { if ( ! isValid()) return false; try { action.run(); return true; } catch (TransientException e) { log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " + Exceptions.toMessageString(e)); return false; } catch (RuntimeException e) { log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e); return false; } } @Override public void close() { lock.ifPresent(l -> l.close()); } } }
package org.opencb.opencga.analysis.rga; import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.lang3.StringUtils; import org.opencb.biodata.models.clinical.Disorder; import org.opencb.biodata.models.clinical.Phenotype; import org.opencb.biodata.models.pedigree.IndividualProperty; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.avro.ClinicalSignificance; import org.opencb.biodata.models.variant.avro.PopulationFrequency; import org.opencb.biodata.models.variant.avro.SequenceOntologyTerm; import org.opencb.opencga.analysis.rga.exceptions.RgaException; import org.opencb.opencga.analysis.rga.iterators.RgaIterator; import org.opencb.opencga.core.common.JacksonUtils; import org.opencb.opencga.core.models.analysis.knockout.KnockoutByIndividual; import org.opencb.opencga.core.models.analysis.knockout.KnockoutTranscript; import org.opencb.opencga.core.models.analysis.knockout.KnockoutVariant; import org.opencb.opencga.storage.core.variant.adaptors.iterators.VariantDBIterator; import org.slf4j.LoggerFactory; import java.util.*; public class IndividualRgaConverter extends AbstractRgaConverter { // This object contains the list of solr fields that are required in order to fully build each of the KnockoutByIndividual fields private static final Map<String, List<String>> CONVERTER_MAP; static { CONVERTER_MAP = new HashMap<>(); CONVERTER_MAP.put("id", Collections.singletonList(RgaDataModel.INDIVIDUAL_ID)); CONVERTER_MAP.put("sampleId", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.SAMPLE_ID)); CONVERTER_MAP.put("sex", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.SEX)); CONVERTER_MAP.put("motherId", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.MOTHER_ID)); CONVERTER_MAP.put("fatherId", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.FATHER_ID)); CONVERTER_MAP.put("fatherSampleId", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.FATHER_SAMPLE_ID)); CONVERTER_MAP.put("motherSampleId", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.MOTHER_SAMPLE_ID)); CONVERTER_MAP.put("phenotypes", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.PHENOTYPES, RgaDataModel.PHENOTYPE_JSON)); CONVERTER_MAP.put("disorders", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.DISORDERS, RgaDataModel.DISORDER_JSON)); CONVERTER_MAP.put("numParents", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.NUM_PARENTS)); CONVERTER_MAP.put("stats", Collections.emptyList()); CONVERTER_MAP.put("genes.id", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID)); CONVERTER_MAP.put("genes.name", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.GENE_NAME)); CONVERTER_MAP.put("genes.chromosome", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.CHROMOSOME)); CONVERTER_MAP.put("genes.biotype", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.GENE_BIOTYPE)); CONVERTER_MAP.put("genes.transcripts.id", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID)); CONVERTER_MAP.put("genes.transcripts.chromosome", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.CHROMOSOME)); CONVERTER_MAP.put("genes.transcripts.start", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.START)); CONVERTER_MAP.put("genes.transcripts.end", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.END)); CONVERTER_MAP.put("genes.transcripts.biotype", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.TRANSCRIPT_BIOTYPE)); CONVERTER_MAP.put("genes.transcripts.strand", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.STRAND)); CONVERTER_MAP.put("genes.transcripts.variants.id", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.VARIANTS)); CONVERTER_MAP.put("genes.transcripts.variants.filter", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.FILTERS, RgaDataModel.VARIANTS)); CONVERTER_MAP.put("genes.transcripts.variants.type", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.TYPES, RgaDataModel.VARIANTS)); CONVERTER_MAP.put("genes.transcripts.variants.knockoutType", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.KNOCKOUT_TYPES, RgaDataModel.VARIANTS)); CONVERTER_MAP.put("genes.transcripts.variants.populationFrequencies", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.POPULATION_FREQUENCIES, RgaDataModel.VARIANTS)); CONVERTER_MAP.put("genes.transcripts.variants.clinicalSignificance", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.CLINICAL_SIGNIFICANCES, RgaDataModel.VARIANTS)); CONVERTER_MAP.put("genes.transcripts.variants.sequenceOntologyTerms", Arrays.asList(RgaDataModel.INDIVIDUAL_ID, RgaDataModel.GENE_ID, RgaDataModel.TRANSCRIPT_ID, RgaDataModel.CONSEQUENCE_TYPES, RgaDataModel.VARIANTS)); logger = LoggerFactory.getLogger(IndividualRgaConverter.class); } public IndividualRgaConverter() { } public List<KnockoutByIndividual> convertToDataModelType(RgaIterator rgaIterator, VariantDBIterator variantDBIterator) { // In this list, we will store the keys of result in the order they have been processed so order is kept List<String> knockoutByIndividualOrder = new LinkedList<>(); Map<String, KnockoutByIndividual> result = new HashMap<>(); Map<String, Variant> variantMap = new HashMap<>(); while (variantDBIterator.hasNext()) { Variant variant = variantDBIterator.next(); variantMap.put(variant.getId(), variant); } while (rgaIterator.hasNext()) { RgaDataModel rgaDataModel = rgaIterator.next(); if (!result.containsKey(rgaDataModel.getIndividualId())) { knockoutByIndividualOrder.add(rgaDataModel.getIndividualId()); } extractKnockoutByIndividualMap(rgaDataModel, variantMap, result); } List<KnockoutByIndividual> knockoutByIndividualList = new ArrayList<>(knockoutByIndividualOrder.size()); for (String id : knockoutByIndividualOrder) { knockoutByIndividualList.add(result.get(id)); } return knockoutByIndividualList; } public static void extractKnockoutByIndividualMap(RgaDataModel rgaDataModel, Map<String, Variant> variantMap, Map<String, KnockoutByIndividual> result) { extractKnockoutByIndividualMap(rgaDataModel, variantMap, new HashSet<>(), result); } /** * Extract a map containing the processed KnockoutByindividuals. * * @param rgaDataModel RgaDataModel instance. * @param variantMap Map of variants. * @param variantIds Set of variant ids to be included in the result. If empty, include all of them. * @param result Map containing the KnockoutByIndividual's processed. */ public static void extractKnockoutByIndividualMap(RgaDataModel rgaDataModel, Map<String, Variant> variantMap, Set<String> variantIds, Map<String, KnockoutByIndividual> result) { if (!result.containsKey(rgaDataModel.getIndividualId())) { KnockoutByIndividual knockoutByIndividual = fillIndividualInfo(rgaDataModel); List<KnockoutByIndividual.KnockoutGene> geneList = new LinkedList<>(); knockoutByIndividual.setGenes(geneList); result.put(rgaDataModel.getIndividualId(), knockoutByIndividual); } KnockoutByIndividual knockoutByIndividual = result.get(rgaDataModel.getIndividualId()); KnockoutByIndividual.KnockoutGene knockoutGene = null; for (KnockoutByIndividual.KnockoutGene gene : knockoutByIndividual.getGenes()) { if (StringUtils.isNotEmpty(gene.getId()) && gene.getId().equals(rgaDataModel.getGeneId())) { knockoutGene = gene; } } if (knockoutGene == null) { knockoutGene = new KnockoutByIndividual.KnockoutGene(); knockoutGene.setId(rgaDataModel.getGeneId()); knockoutGene.setName(rgaDataModel.getGeneName()); knockoutGene.setStrand(rgaDataModel.getStrand()); knockoutGene.setBiotype(rgaDataModel.getGeneBiotype()); knockoutGene.setStart(rgaDataModel.getStart()); knockoutGene.setEnd(rgaDataModel.getEnd()); knockoutGene.setTranscripts(new LinkedList<>()); knockoutByIndividual.addGene(knockoutGene); } if (StringUtils.isNotEmpty(rgaDataModel.getTranscriptId())) { List<KnockoutVariant> knockoutVariantList = RgaUtils.extractKnockoutVariants(rgaDataModel, variantMap, variantIds); // Add new transcript KnockoutTranscript knockoutTranscript = new KnockoutTranscript(rgaDataModel.getTranscriptId(), rgaDataModel.getChromosome(), rgaDataModel.getStart(), rgaDataModel.getEnd(), rgaDataModel.getTranscriptBiotype(), rgaDataModel.getStrand(), knockoutVariantList); knockoutGene.addTranscripts(Collections.singletonList(knockoutTranscript)); } } public List<RgaDataModel> convertToStorageType(List<KnockoutByIndividual> knockoutByIndividualList) { List<RgaDataModel> result = new LinkedList<>(); for (KnockoutByIndividual knockoutByIndividual : knockoutByIndividualList) { try { result.addAll(convertToStorageType(knockoutByIndividual)); } catch (RgaException | JsonProcessingException e) { logger.warn("Could not parse KnockoutByIndividualList: {}", e.getMessage(), e); } } return result; } private List<RgaDataModel> convertToStorageType(KnockoutByIndividual knockoutByIndividual) throws RgaException, JsonProcessingException { if (StringUtils.isEmpty(knockoutByIndividual.getId())) { throw new RgaException("Missing mandatory field 'id'"); } if (StringUtils.isEmpty(knockoutByIndividual.getSampleId())) { throw new RgaException("Missing mandatory field 'sampleId'"); } List<RgaDataModel> result = new LinkedList<>(); if (knockoutByIndividual.getGenes() != null) { for (KnockoutByIndividual.KnockoutGene gene : knockoutByIndividual.getGenes()) { for (KnockoutTranscript transcript : gene.getTranscripts()) { List<String> compoundFilters = processFilters(transcript); List<String> phenotypes = populatePhenotypes(knockoutByIndividual.getPhenotypes()); List<String> disorders = populateDisorders(knockoutByIndividual.getDisorders()); List<String> phenotypeJson; if (knockoutByIndividual.getPhenotypes() != null) { phenotypeJson = new ArrayList<>(knockoutByIndividual.getPhenotypes().size()); for (Phenotype phenotype : knockoutByIndividual.getPhenotypes()) { phenotypeJson.add(JacksonUtils.getDefaultObjectMapper().writeValueAsString(phenotype)); } } else { phenotypeJson = Collections.emptyList(); } List<String> disorderJson; if (knockoutByIndividual.getDisorders() != null) { disorderJson = new ArrayList<>(knockoutByIndividual.getDisorders().size()); for (Disorder disorder : knockoutByIndividual.getDisorders()) { disorderJson.add(JacksonUtils.getDefaultObjectMapper().writeValueAsString(disorder)); } } else { disorderJson = Collections.emptyList(); } List<String> variantIds = new ArrayList<>(transcript.getVariants().size()); List<String> knockoutTypes = new ArrayList<>(transcript.getVariants().size()); Set<String> types = new HashSet<>(); Set<String> consequenceTypes = new HashSet<>(); Set<String> clinicalSignificances = new HashSet<>(); Set<String> filters = new HashSet<>(); for (KnockoutVariant variant : transcript.getVariants()) { variantIds.add(variant.getId()); knockoutTypes.add(variant.getKnockoutType() != null ? variant.getKnockoutType().name() : ""); if (variant.getType() != null) { types.add(variant.getType().name()); } if (variant.getSequenceOntologyTerms() != null) { for (SequenceOntologyTerm sequenceOntologyTerm : variant.getSequenceOntologyTerms()) { if (sequenceOntologyTerm.getAccession() != null) { consequenceTypes.add(sequenceOntologyTerm.getAccession()); } } } if (variant.getClinicalSignificance() != null) { for (ClinicalSignificance clinicalSignificance : variant.getClinicalSignificance()) { if (clinicalSignificance != null) { clinicalSignificances.add(clinicalSignificance.name()); } } } if (StringUtils.isNotEmpty(variant.getFilter())) { filters.add(variant.getFilter()); } } Map<String, List<Float>> popFreqs = getPopulationFrequencies(transcript); String id = knockoutByIndividual.getSampleId() + "_" + gene.getId() + "_" + transcript.getId(); String individualId = knockoutByIndividual.getId(); int numParents = 0; if (StringUtils.isNotEmpty(knockoutByIndividual.getFatherId())) { numParents++; } if (StringUtils.isNotEmpty(knockoutByIndividual.getMotherId())) { numParents++; } String sex = knockoutByIndividual.getSex() != null ? knockoutByIndividual.getSex().name() : IndividualProperty.Sex.UNKNOWN.name(); RgaDataModel model = new RgaDataModel() .setId(id) .setIndividualId(individualId) .setSampleId(knockoutByIndividual.getSampleId()) .setSex(sex) .setPhenotypes(phenotypes) .setDisorders(disorders) .setFatherId(knockoutByIndividual.getFatherId()) .setMotherId(knockoutByIndividual.getMotherId()) .setFatherSampleId(knockoutByIndividual.getFatherSampleId()) .setMotherSampleId(knockoutByIndividual.getMotherSampleId()) .setNumParents(numParents) .setGeneId(gene.getId()) .setGeneName(gene.getName()) .setGeneBiotype(gene.getBiotype()) .setChromosome(gene.getChromosome()) .setStrand(gene.getStrand()) .setStart(gene.getStart()) .setEnd(gene.getEnd()) .setTranscriptId(transcript.getId()) .setTranscriptBiotype(transcript.getBiotype()) .setVariants(variantIds) .setTypes(new ArrayList<>(types)) .setKnockoutTypes(knockoutTypes) .setFilters(new ArrayList<>(filters)) .setConsequenceTypes(new ArrayList<>(consequenceTypes)) .setClinicalSignificances(new ArrayList<>(clinicalSignificances)) .setPopulationFrequencies(popFreqs) .setCompoundFilters(compoundFilters) .setPhenotypeJson(phenotypeJson) .setDisorderJson(disorderJson); result.add(model); } } } return result; } private Map<String, List<Float>> getPopulationFrequencies(KnockoutTranscript transcript) { Map<String, List<Float>> popFreqs = new HashMap<>(); String pfKey = RgaDataModel.POPULATION_FREQUENCIES.replace("*", ""); String thousandGenomeKey = pfKey + RgaUtils.THOUSAND_GENOMES_STUDY; String gnomadGenomeKey = pfKey + RgaUtils.GNOMAD_GENOMES_STUDY; if (!transcript.getVariants().isEmpty()) { popFreqs.put(thousandGenomeKey, new ArrayList<>(transcript.getVariants().size())); popFreqs.put(gnomadGenomeKey, new ArrayList<>(transcript.getVariants().size())); } for (KnockoutVariant variant : transcript.getVariants()) { if (variant.getPopulationFrequencies() != null) { boolean gnomad = false; boolean thousandG = false; for (PopulationFrequency populationFrequency : variant.getPopulationFrequencies()) { if (populationFrequency.getPopulation().equals("ALL")) { if (RgaUtils.THOUSAND_GENOMES_STUDY.toUpperCase().equals(populationFrequency.getStudy().toUpperCase())) { popFreqs.get(thousandGenomeKey).add(populationFrequency.getAltAlleleFreq()); thousandG = true; } else if (RgaUtils.GNOMAD_GENOMES_STUDY.toUpperCase().equals(populationFrequency.getStudy().toUpperCase())) { popFreqs.get(gnomadGenomeKey).add(populationFrequency.getAltAlleleFreq()); gnomad = true; } } } if (!thousandG) { popFreqs.get(thousandGenomeKey).add(0f); } if (!gnomad) { popFreqs.get(gnomadGenomeKey).add(0f); } } } return popFreqs; } private List<String> processFilters(KnockoutTranscript transcript) throws RgaException { Set<String> results = new HashSet<>(); List<List<List<String>>> compoundHeterozygousVariantList = new LinkedList<>(); for (KnockoutVariant variant : transcript.getVariants()) { List<List<String>> independentTerms = new LinkedList<>(); // KO - Knockout types if (variant.getKnockoutType() != null) { independentTerms.add(Collections.singletonList(RgaUtils.encode(variant.getKnockoutType().name()))); } // F - Filters if (StringUtils.isNotEmpty(variant.getFilter())) { if (variant.getFilter().equalsIgnoreCase(RgaUtils.PASS)) { independentTerms.add(Collections.singletonList(RgaUtils.encode(RgaUtils.PASS))); } else { independentTerms.add(Collections.singletonList(RgaUtils.encode(RgaUtils.NOT_PASS))); } } // CT - Consequence types if (variant.getSequenceOntologyTerms() != null) { List<String> ct = new ArrayList<>(variant.getSequenceOntologyTerms().size()); for (SequenceOntologyTerm sequenceOntologyTerm : variant.getSequenceOntologyTerms()) { ct.add(RgaUtils.encode(sequenceOntologyTerm.getName())); } independentTerms.add(ct); } // PF - Population frequencies List<String> pf = new LinkedList<>(); boolean gnomad = false; boolean thousandG = false; if (variant.getPopulationFrequencies() != null) { for (PopulationFrequency populationFrequency : variant.getPopulationFrequencies()) { if (populationFrequency.getPopulation().equals("ALL")) { if (RgaUtils.THOUSAND_GENOMES_STUDY.toUpperCase().equals(populationFrequency.getStudy().toUpperCase())) { String populationFrequencyKey = RgaUtils.getPopulationFrequencyKey(populationFrequency.getAltAlleleFreq()); pf.add(RgaUtils.encode(RgaUtils.THOUSAND_GENOMES_STUDY.toUpperCase() + RgaUtils.SEPARATOR + populationFrequencyKey)); thousandG = true; } else if (RgaUtils.GNOMAD_GENOMES_STUDY.toUpperCase().equals(populationFrequency.getStudy().toUpperCase())) { String populationFrequencyKey = RgaUtils.getPopulationFrequencyKey(populationFrequency.getAltAlleleFreq()); pf.add(RgaUtils.encode(RgaUtils.GNOMAD_GENOMES_STUDY.toUpperCase() + RgaUtils.SEPARATOR + populationFrequencyKey)); gnomad = true; } } } } if (!thousandG) { pf.add(RgaUtils.encode(RgaUtils.THOUSAND_GENOMES_STUDY.toUpperCase() + RgaUtils.SEPARATOR + 0f)); } if (!gnomad) { pf.add(RgaUtils.encode(RgaUtils.GNOMAD_GENOMES_STUDY.toUpperCase() + RgaUtils.SEPARATOR + 0f)); } independentTerms.add(pf); if (variant.getKnockoutType() == KnockoutVariant.KnockoutType.COMP_HET) { compoundHeterozygousVariantList.add(independentTerms); } results.addAll(generateCombinations(independentTerms)); } if (!compoundHeterozygousVariantList.isEmpty()) { results.addAll(generateCompoundHeterozygousCombinations(compoundHeterozygousVariantList)); } return new ArrayList<>(results); } private Set<String> generateCompoundHeterozygousCombinations(List<List<List<String>>> compoundHeterozygousVariantList) throws RgaException { if (compoundHeterozygousVariantList.size() < 2) { return Collections.emptySet(); } Set<String> result = new HashSet<>(); for (int i = 0; i < compoundHeterozygousVariantList.size() - 1; i++) { for (int j = i + 1; j < compoundHeterozygousVariantList.size(); j++) { result.addAll(generateCompoundHeterozygousPairCombination(compoundHeterozygousVariantList.get(i), compoundHeterozygousVariantList.get(j))); } } return result; } private Set<String> generateCompoundHeterozygousPairCombination(List<List<String>> variant1, List<List<String>> variant2) throws RgaException { List<List<String>> result = new LinkedList<>(); /* Compound heterozygous combinations: * KO - F1 - F2 * KO - F1 - F2 - CT1 - CT2 * KO - F1 - F2 - CT1 - CT2 - PF1 - PF2 * KO - F1 - F2 - PF' ; where PF' is equivalent to the highest PF of both variants (to easily respond to PF<=x) */ String knockout = RgaUtils.encode(KnockoutVariant.KnockoutType.COMP_HET.name()); result.add(Collections.singletonList(knockout)); // Generate combinations: KO - F1 - F2; KO - F1 - F2 - CT1 - CT2; KO - F1 - F2 - CT1 - CT2 - PF1 - PF2 List<List<String>> previousIteration = result; for (int i = 1; i < 4; i++) { // The list will contain all Filter, CT or PF combinations between variant1 and variant2 in a sorted manner to reduce the // number of terms List<List<String>> sortedCombinations = generateSortedCombinations(variant1.get(i), variant2.get(i)); List<List<String>> newResults = new ArrayList<>(previousIteration.size() * sortedCombinations.size()); for (List<String> previousValues : previousIteration) { for (List<String> values : sortedCombinations) { List<String> newValues = new ArrayList<>(previousValues); newValues.addAll(values); newResults.add(newValues); } } if (i == 1) { // Remove single Knockout string list because there is already a filter just for that field result.clear(); } result.addAll(newResults); previousIteration = newResults; } // Generate also combination: KO - F1 - F2 - PF' ; where PF' is equivalent to the highest PF of both variants List<List<String>> sortedFilterList = generateSortedCombinations(variant1.get(1), variant2.get(1)); List<String> simplifiedPopFreqList = generateSimplifiedPopulationFrequencyList(variant1.get(3), variant2.get(3)); for (List<String> filterList : sortedFilterList) { for (String popFreq : simplifiedPopFreqList) { List<String> terms = new LinkedList<>(); terms.add(knockout); terms.addAll(filterList); terms.add(popFreq); result.add(terms); } } Set<String> combinations = new HashSet<>(); for (List<String> strings : result) { combinations.add(StringUtils.join(strings, RgaUtils.SEPARATOR)); } return combinations; } /** * Given two lists containing frequencies for the same populations, it will return a unified frequency for each population containing * the least restrictive value. Example: [P1-12, P2-6] - [P1-15, P2-2] will generate [P1-15, P2-6] * * @param list1 List containing the population frequencies of variant1. * @param list2 List containing the population frequencies of variant2. * @return A list containing the least restrictive population frequencies. * @throws RgaException If there is an issue with the provided lists. */ private List<String> generateSimplifiedPopulationFrequencyList(List<String> list1, List<String> list2) throws RgaException { if (list1.size() != list2.size()) { throw new RgaException("Both lists should be the same size and contain the same population frequency values"); } Map<String, Integer> map1 = new HashMap<>(); Map<String, Integer> map2 = new HashMap<>(); for (String terms : list1) { String[] split = terms.split("-"); map1.put(split[0], Integer.parseInt(split[1])); } for (String terms : list2) { String[] split = terms.split("-"); map2.put(split[0], Integer.parseInt(split[1])); } List<String> terms = new ArrayList<>(list1.size()); for (String popFreqKey : map1.keySet()) { if (map1.get(popFreqKey) > map2.get(popFreqKey)) { terms.add(popFreqKey + "-" + map1.get(popFreqKey)); } else { terms.add(popFreqKey + "-" + map2.get(popFreqKey)); } } return terms; } /** * Given two lists it will return a list containing all possible combinations, but sorted. For instance: * [A, D, F] - [B, G] will return [[A, B], [A, G], [B, D], [D, G], [B, F], [F, G]] * * @param list1 List 1. * @param list2 List 2. * @return A list containing list1-list2 sorted pairwise combinations. */ public static List<List<String>> generateSortedCombinations(List<String> list1, List<String> list2) { List<List<String>> results = new ArrayList<>(list1.size() * list2.size()); for (String v1Term : list1) { for (String v2Term : list2) { if (StringUtils.compare(v1Term, v2Term) <= 0) { results.add(Arrays.asList(v1Term, v2Term)); } else { results.add(Arrays.asList(v2Term, v1Term)); } } } return results; } /** * Given a list of [[KO], [FILTER1, FILTER2], [CTs], [PFs]], it will return all possible String combinations merging those values. * [KO - FILTER1, KO - FILTER2] * [KO - FILTER1 - CT', KO - FILTER2 - CT'] * [KO - FILTER1 - CT' - PF', KO - FILTER2 - CT' - PF'] * [KO - FILTER1 - PF', KO - FILTER2 - PF'] * @param values List of size 4 containing values for the 4 filters. * @return a list containing all possible merge combinations to store in the DB. */ private List<String> generateCombinations(List<List<String>> values) { if (values.isEmpty()) { return Collections.emptyList(); } List<List<String>> result = new LinkedList<>(); for (String value : values.get(0)) { result.add(Collections.singletonList(value)); } // Generate combinations: KO - F; KO - F - CT; KO -F - CT - PF List<List<String>> previousIteration = result; for (int i = 1; i < values.size(); i++) { List<List<String>> newResults = new ArrayList<>(previousIteration.size() * values.get(i).size()); for (List<String> previousValues : previousIteration) { for (String currentValue : values.get(i)) { List<String> newValues = new ArrayList<>(previousValues); newValues.add(currentValue); newResults.add(newValues); } } if (i == 1) { // Remove single Knockout string list because there is already a filter just for that field result.clear(); } result.addAll(newResults); previousIteration = newResults; } // Generate also combination: KO - F - PF (no consequence type this time) for (String ko : values.get(0)) { for (String filter : values.get(1)) { for (String popFreq : values.get(3)) { result.add(Arrays.asList(ko, filter, popFreq)); } } } List<String> combinations = new ArrayList<>(result.size()); for (List<String> strings : result) { combinations.add(StringUtils.join(strings, RgaUtils.SEPARATOR)); } return combinations; } private List<String> populatePhenotypes(List<Phenotype> phenotypes) { Set<String> phenotypesIds = new HashSet<>(); if (phenotypes != null) { for (Phenotype phenotype : phenotypes) { phenotypesIds.add(phenotype.getId()); phenotypesIds.add(phenotype.getName()); } } return new ArrayList(phenotypesIds); } private List<String> populateDisorders(List<Disorder> disorders) { Set<String> disorderIds = new HashSet<>(); if (disorders != null) { for (Disorder disorder : disorders) { disorderIds.add(disorder.getId()); disorderIds.add(disorder.getName()); } } return new ArrayList(disorderIds); } public List<String> getIncludeFields(List<String> includeFields) { Set<String> toInclude = new HashSet<>(); for (String includeField : includeFields) { for (String fieldKey : CONVERTER_MAP.keySet()) { if (fieldKey.startsWith(includeField)) { toInclude.addAll(CONVERTER_MAP.get(fieldKey)); } } } return new ArrayList<>(toInclude); } public List<String> getIncludeFromExcludeFields(List<String> excludeFields) { Set<String> excludedFields = new HashSet<>(); for (String excludeField : excludeFields) { for (String fieldKey : CONVERTER_MAP.keySet()) { if (fieldKey.startsWith(excludeField)) { excludedFields.add(fieldKey); } } } // Add everything that was not excluded Set<String> toInclude = new HashSet<>(); for (String field : CONVERTER_MAP.keySet()) { if (!excludedFields.contains(field)) { toInclude.addAll(CONVERTER_MAP.get(field)); } } return new ArrayList<>(toInclude); } }
package org.opennms.netmgt.ticketd; import org.opennms.netmgt.dao.AlarmDao; import org.opennms.netmgt.model.OnmsAlarm; import org.opennms.netmgt.model.TroubleTicketState; import org.opennms.netmgt.ticketd.Ticket.State; import org.springframework.beans.factory.InitializingBean; import org.springframework.orm.ObjectRetrievalFailureException; import org.springframework.util.Assert; /** * OpenNMS Trouble Ticket API implementation. * * @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a> * @author <a href="mailto:david@opennms.org">David Hustace</a> * */ public class DefaultTicketerServiceLayer implements TicketerServiceLayer, InitializingBean { private AlarmDao m_alarmDao; private TicketerPlugin m_ticketerPlugin; /** * Needs access to the AlarmDao. * * @param alarmDao */ public void setAlarmDao(AlarmDao alarmDao) { m_alarmDao = alarmDao; } /** * Needs access to the TicketerPlugin API implementation for * communication with the HelpDesk. * * @param ticketerPlugin */ public void setTicketerPlugin(TicketerPlugin ticketerPlugin) { m_ticketerPlugin = ticketerPlugin; } /** * Spring functionality implemented to validate the state of the trouble ticket * plugin API. */ public void afterPropertiesSet() throws Exception { Assert.state(m_alarmDao != null, "alarmDao property must be set"); Assert.state(m_ticketerPlugin != null, "ticketPlugin property must be set"); } /* * (non-Javadoc) * @see org.opennms.netmgt.ticketd.TicketerServiceLayer#cancelTicketForAlarm(int, java.lang.String) */ public void cancelTicketForAlarm(int alarmId, String ticketId) { OnmsAlarm alarm = m_alarmDao.get(alarmId); if (alarm == null) { throw new ObjectRetrievalFailureException("Unable to locate Alarm with ID: "+alarmId, null); } setTicketState(ticketId, Ticket.State.CANCELLED); alarm.setTTicketState(TroubleTicketState.CANCELLED); m_alarmDao.saveOrUpdate(alarm); } private void setTicketState(String ticketId, State state) { Ticket ticket = m_ticketerPlugin.get(ticketId); ticket.setState(state); m_ticketerPlugin.saveOrUpdate(ticket); } /* * (non-Javadoc) * @see org.opennms.netmgt.ticketd.TicketerServiceLayer#closeTicketForAlarm(int, java.lang.String) */ public void closeTicketForAlarm(int alarmId, String ticketId) { OnmsAlarm alarm = m_alarmDao.get(alarmId); setTicketState(ticketId, State.CLOSED); alarm.setTTicketState(TroubleTicketState.CLOSED); m_alarmDao.saveOrUpdate(alarm); } /* * (non-Javadoc) * @see org.opennms.netmgt.ticketd.TicketerServiceLayer#createTicketForAlarm(int) */ public void createTicketForAlarm(int alarmId) { OnmsAlarm alarm = m_alarmDao.get(alarmId); Ticket ticket = createTicketFromAlarm(alarm); m_ticketerPlugin.saveOrUpdate(ticket); alarm.setTTicketId(ticket.getId()); alarm.setTTicketState(TroubleTicketState.OPEN); m_alarmDao.saveOrUpdate(alarm); } /** * Called from API implemented method after successful retrieval of Alarm. * * @param alarm OpenNMS Model class alarm * @return OpenNMS Ticket with contents of alarm. * TODO: Add alarm attributes to Ticket. * TODO: Add alarmid to Ticket class for ability to reference back to Alarm (waffling on this * since ticket isn't a persisted object and other reasons) */ private Ticket createTicketFromAlarm(OnmsAlarm alarm) { Ticket ticket = new Ticket(); ticket.setSummary(alarm.getLogMsg()); ticket.setDetails(alarm.getDescription()); ticket.setId(alarm.getTTicketId()); return ticket; } /* * (non-Javadoc) * @see org.opennms.netmgt.ticketd.TicketerServiceLayer#updateTicketForAlarm(int, java.lang.String) */ public void updateTicketForAlarm(int alarmId, String ticketId) { // ticket.setState(State.OPEN); // ticket.setDetails(alarm.getDescription()); // m_ticketerPlugin.saveOrUpdate(ticket); OnmsAlarm alarm = m_alarmDao.get(alarmId); Ticket ticket = m_ticketerPlugin.get(ticketId); if (ticket.getState() == Ticket.State.CANCELLED) { alarm.setTTicketState(TroubleTicketState.CANCELLED); } else if (ticket.getState() == Ticket.State.CLOSED) { alarm.setTTicketState(TroubleTicketState.CLOSED); } else if (ticket.getState() == Ticket.State.OPEN) { alarm.setTTicketState(TroubleTicketState.OPEN); } alarm.setTTicketState(TroubleTicketState.OPEN); m_alarmDao.saveOrUpdate(alarm); } // TODO what if the alarm doesn't exist? }
package org.orienteer.graph.component.command; import com.google.inject.Inject; import com.google.inject.Provider; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.record.impl.ODocument; import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.model.IModel; import org.apache.wicket.model.ResourceModel; import org.orienteer.core.component.BootstrapType; import org.orienteer.core.component.FAIconType; import org.orienteer.core.component.command.AbstractModalWindowCommand; import org.orienteer.core.component.command.Command; import org.orienteer.core.component.command.modal.SelectDialogPanel; import org.orienteer.core.component.command.modal.SelectSubOClassDialogPage; import org.orienteer.core.component.property.DisplayMode; import org.orienteer.core.component.table.OrienteerDataTable; import org.orienteer.core.web.ODocumentPage; import org.orienteer.graph.module.GraphModule; import ru.ydn.wicket.wicketorientdb.model.OClassModel; import ru.ydn.wicket.wicketorientdb.security.ISecuredComponent; import ru.ydn.wicket.wicketorientdb.security.OSecurityHelper; import ru.ydn.wicket.wicketorientdb.security.OrientPermission; import ru.ydn.wicket.wicketorientdb.security.RequiredOrientResource; import java.util.List; /** * {@link Command} to create graph edge between {@link ODocument}s. */ public class CreateEdgeCommand extends AbstractModalWindowCommand<ODocument> implements ISecuredComponent { private IModel<OClass> classModel; private IModel<ODocument> documentModel; @Inject private Provider<OrientGraph> orientGraphProvider; public CreateEdgeCommand(OrienteerDataTable<ODocument, ?> table, IModel<ODocument> documentIModel) { this(new ResourceModel("command.link"),table,documentIModel); } public CreateEdgeCommand(IModel<?> labelModel,OrienteerDataTable<ODocument, ?> table, IModel<ODocument> documentIModel) { super(labelModel, table); setBootstrapType(BootstrapType.SUCCESS); setIcon(FAIconType.plus); setAutoNotify(false); this.classModel = new OClassModel(GraphModule.VERTEX_CLASS_NAME); this.documentModel = documentIModel; setChandingModel(true); } @Override protected void initializeContent(final ModalWindow modal) { modal.setTitle(new ResourceModel("dialog.select.edge.class")); modal.setAutoSize(true); modal.setMinimalWidth(300); SelectSubOClassDialogPage selectEdgeClassDialog = new SelectSubOClassDialogPage(modal, new OClassModel(GraphModule.EDGE_CLASS_NAME)) { @Override protected void onSelect(AjaxRequestTarget target, OClass selectedOClass) { modal.setWindowClosedCallback(null); modal.setTitle(new ResourceModel("dialog.select.vertices")); final OClassModel selectedEdgeOClassModel = new OClassModel(selectedOClass); OClassModel vertexOClassModel = new OClassModel(GraphModule.VERTEX_CLASS_NAME); modal.setContent(new SelectDialogPanel(modal.getContentId(), modal, vertexOClassModel, true) { @Override protected boolean onSelect(AjaxRequestTarget target, List<ODocument> objects, boolean selectMore) { createEdge(objects, selectedEdgeOClassModel.getObject()); this.modal.close(target); CreateEdgeCommand.this.sendActionPerformed(); return true; } }); modal.show(target); } }; modal.setContent(selectEdgeClassDialog); } @Override public RequiredOrientResource[] getRequiredResources() { return OSecurityHelper.requireOClass(classModel.getObject(), OrientPermission.CREATE); } private void createEdge(List<ODocument> documents, OClass edgeClass) { OrientGraph tx = orientGraphProvider.get(); for (ODocument createTo : documents) { tx.addEdge(null, tx.getVertex(documentModel.getObject().getIdentity()), tx.getVertex(createTo.getIdentity()), edgeClass.getName()); } tx.commit();tx.begin(); } @Override public void detachModels() { super.detachModels(); classModel.detach(); documentModel.detach(); } }
package sk.henrichg.phoneprofiles; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.AppCompatImageButton; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.readystatesoftware.systembartint.SystemBarTintManager; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ApplicationEditorIntentActivity extends AppCompatActivity { private Application application = null; private PPIntent ppIntent = null; private int startApplicationDelay; Button okButton; //private ScrollView intentScrollView; private EditText intentNameEditText; private EditText intentPackageName; private EditText intentClassName; private Spinner intentActionSpinner; private EditText intentActionEdit; private EditText intentData; private EditText intentMimeType; private TextView categoryTextView; private TextView flagsTextView; private EditText intentExtraKeyName1; private EditText intentExtraKeyValue1; private Spinner intentExtraSpinner1; private EditText intentExtraKeyName2; private EditText intentExtraKeyValue2; private Spinner intentExtraSpinner2; private EditText intentExtraKeyName3; private EditText intentExtraKeyValue3; private Spinner intentExtraSpinner3; private EditText intentExtraKeyName4; private EditText intentExtraKeyValue4; private Spinner intentExtraSpinner4; private EditText intentExtraKeyName5; private EditText intentExtraKeyValue5; private Spinner intentExtraSpinner5; String[] actionsArray; String[] categoryArray; boolean[] categoryIndices; String[] flagArray; boolean[] flagIndices; public static final String EXTRA_DIALOG_PREFERENCE_START_APPLICATION_DELAY = "dialogPreferenceStartApplicationDelay"; @Override protected void onCreate(Bundle savedInstanceState) { // must by called before super.onCreate() for PreferenceActivity GlobalGUIRoutines.setTheme(this, false, false); // must by called before super.onCreate() GlobalGUIRoutines.setLanguage(getBaseContext()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_application_editor_intent); if (/*(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) &&*/ (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)) { Window w = getWindow(); // in Activity's onCreate() for instance //w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // create our manager instance after the content view is set SystemBarTintManager tintManager = new SystemBarTintManager(this); // enable status bar tint tintManager.setStatusBarTintEnabled(true); // set a custom tint color for status bar switch (ApplicationPreferences.applicationTheme(getApplicationContext(), true)) { case "color": tintManager.setStatusBarTintColor(ContextCompat.getColor(getBaseContext(), R.color.primary)); break; case "white": tintManager.setStatusBarTintColor(ContextCompat.getColor(getBaseContext(), R.color.primaryDark19_white)); break; default: tintManager.setStatusBarTintColor(ContextCompat.getColor(getBaseContext(), R.color.primary_dark)); break; } } if (getSupportActionBar() != null) { getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.intent_editor_title); getSupportActionBar().setElevation(GlobalGUIRoutines.dpToPx(1)); } Intent intent = getIntent(); application = intent.getParcelableExtra(ApplicationEditorDialog.EXTRA_APPLICATION); ppIntent = intent.getParcelableExtra(ApplicationEditorDialog.EXTRA_PP_INTENT); if (ppIntent == null) PPApplication.logE("ApplicationEditorIntentActivity.onCreate", "ppIntent=null"); else PPApplication.logE("ApplicationEditorIntentActivity.onCreate", "ppIntent._id="+ppIntent._id); startApplicationDelay = getIntent().getIntExtra(EXTRA_DIALOG_PREFERENCE_START_APPLICATION_DELAY, 0); okButton = findViewById(R.id.application_editor_intent_ok); //intentScrollView = findViewById(R.id.application_editor_intent_scroll_view); intentNameEditText = findViewById(R.id.application_editor_intent_intent_name); intentNameEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { enableOKButton(); } }); intentPackageName = findViewById(R.id.application_editor_intent_package_name); intentClassName = findViewById(R.id.application_editor_intent_class_name); intentData = findViewById(R.id.application_editor_intent_data); intentMimeType = findViewById(R.id.application_editor_intent_mime_type); intentActionSpinner = findViewById(R.id.application_editor_intent_action_spinner); intentActionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position == 0) { intentActionEdit.setText(R.string.empty_string); intentActionEdit.setEnabled(false); } else if (position == 1) { intentActionEdit.setEnabled(true); } else { intentActionEdit.setText(R.string.empty_string); intentActionEdit.setEnabled(false); } } public void onNothingSelected(AdapterView<?> parent) { } }); intentActionEdit = findViewById(R.id.application_editor_intent_action_edit); final Activity activity = this; categoryTextView = findViewById(R.id.application_editor_intent_category_value); categoryArray = getResources().getStringArray(R.array.applicationEditorIntentCategoryArray); categoryIndices = new boolean[categoryArray.length]; AppCompatImageButton intentCategoryButton = findViewById(R.id.application_editor_intent_category_btn); intentCategoryButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(activity) .setTitle(R.string.application_editor_intent_categories_dlg_title) //.setIcon(getDialogIcon()) .setMultiChoiceItems(R.array.applicationEditorIntentCategoryArray, categoryIndices, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { categoryIndices[which] = isChecked; } }); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { intentNameEditText.clearFocus(); intentPackageName.clearFocus(); intentClassName.clearFocus(); intentActionEdit.clearFocus(); intentData.clearFocus(); intentMimeType.clearFocus(); String categoryValue = ""; int i = 0; for (boolean selected : categoryIndices) { if (selected) { if (!categoryValue.isEmpty()) //noinspection StringConcatenationInLoop categoryValue = categoryValue + "\n"; //noinspection StringConcatenationInLoop categoryValue = categoryValue + categoryArray[i]; } ++i; } categoryTextView.setText(categoryValue); /*intentScrollView.post(new Runnable() { public void run() { intentScrollView.scrollTo(0, categoryTextView.getBottom()); } });*/ } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); //AlertDialog mDialog = builder.create(); if (!isFinishing()) builder.show(); } }); flagsTextView = findViewById(R.id.application_editor_intent_flags_value); flagArray = getResources().getStringArray(R.array.applicationEditorIntentFlagArray); flagIndices = new boolean[flagArray.length]; AppCompatImageButton intentFlagsButton = findViewById(R.id.application_editor_intent_flags_btn); intentFlagsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(activity) .setTitle(R.string.application_editor_intent_flags_dlg_title) //.setIcon(getDialogIcon()) .setMultiChoiceItems(R.array.applicationEditorIntentFlagArray, flagIndices, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { flagIndices[which] = isChecked; } }); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { intentNameEditText.clearFocus(); intentPackageName.clearFocus(); intentClassName.clearFocus(); intentActionEdit.clearFocus(); intentData.clearFocus(); intentMimeType.clearFocus(); String flagsValue = ""; int i = 0; for (boolean selected : flagIndices) { if (selected) { if (!flagsValue.isEmpty()) //noinspection StringConcatenationInLoop flagsValue = flagsValue + "\n"; //noinspection StringConcatenationInLoop flagsValue = flagsValue + flagArray[i]; } ++i; } flagsTextView.setText(flagsValue); /*intentScrollView.post(new Runnable() { public void run() { intentScrollView.scrollTo(0, flagsTextView.getBottom()); } });*/ } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog mDialog = builder.create(); if (!isFinishing()) mDialog.show(); } }); intentExtraKeyName1 = findViewById(R.id.application_editor_intent_extra_key_1); intentExtraKeyValue1 = findViewById(R.id.application_editor_intent_extra_value_1); intentExtraSpinner1 = findViewById(R.id.application_editor_intent_extra_type_spinner_1); intentExtraKeyName2 = findViewById(R.id.application_editor_intent_extra_key_2); intentExtraKeyValue2 = findViewById(R.id.application_editor_intent_extra_value_2); intentExtraSpinner2 = findViewById(R.id.application_editor_intent_extra_type_spinner_2); intentExtraKeyName3 = findViewById(R.id.application_editor_intent_extra_key_3); intentExtraKeyValue3 = findViewById(R.id.application_editor_intent_extra_value_3); intentExtraSpinner3 = findViewById(R.id.application_editor_intent_extra_type_spinner_3); intentExtraKeyName4 = findViewById(R.id.application_editor_intent_extra_key_4); intentExtraKeyValue4 = findViewById(R.id.application_editor_intent_extra_value_4); intentExtraSpinner4 = findViewById(R.id.application_editor_intent_extra_type_spinner_4); intentExtraKeyName5 = findViewById(R.id.application_editor_intent_extra_key_5); intentExtraKeyValue5 = findViewById(R.id.application_editor_intent_extra_value_5); intentExtraSpinner5 = findViewById(R.id.application_editor_intent_extra_type_spinner_5); actionsArray = getResources().getStringArray(R.array.applicationEditorIntentActionArray); if (ppIntent != null) { intentNameEditText.setText(ppIntent._name); intentPackageName.setText(ppIntent._packageName); intentClassName.setText(ppIntent._className); intentData.setText(ppIntent._data); intentMimeType.setText(ppIntent._mimeType); if ((ppIntent._action == null) || ppIntent._action.isEmpty()) { intentActionSpinner.setSelection(0); intentActionEdit.setText(R.string.empty_string); intentActionEdit.setEnabled(false); } else { boolean custom = true; for (String action : actionsArray) { if (action.equals(ppIntent._action)) { custom = false; break; } } if (custom) { intentActionSpinner.setSelection(1); intentActionEdit.setText(ppIntent._action); intentActionEdit.setEnabled(false); } else { intentActionSpinner.setSelection(Arrays.asList(actionsArray).indexOf(ppIntent._action)); intentActionEdit.setText(R.string.empty_string); intentActionEdit.setEnabled(false); } } if (ppIntent._categories != null) { String categoryValue = ppIntent._categories.replaceAll("\\|", "\n"); categoryTextView.setText(categoryValue); List<String> stringList = new ArrayList<>(Arrays.asList(categoryArray)); String[] splits = ppIntent._categories.split("\\|"); for (String category : splits) { int i = stringList.indexOf(category); if (i != -1) { categoryIndices[i] = true; } } } if (ppIntent._flags != null) { String flagsValue = ppIntent._flags.replaceAll("\\|", "\n"); flagsTextView.setText(flagsValue); List<String> stringList = new ArrayList<>(Arrays.asList(flagArray)); String[] splits = ppIntent._flags.split("\\|"); for (String flag : splits) { int i = stringList.indexOf(flag); if (i != -1) flagIndices[i] = true; } } if (ppIntent._extraKey1 != null) { intentExtraKeyName1.setText(ppIntent._extraKey1); intentExtraKeyValue1.setText(ppIntent._extraValue1); intentExtraSpinner1.setSelection(ppIntent._extraType1); } if (ppIntent._extraKey2 != null) { intentExtraKeyName2.setText(ppIntent._extraKey2); intentExtraKeyValue2.setText(ppIntent._extraValue2); intentExtraSpinner2.setSelection(ppIntent._extraType2); } if (ppIntent._extraKey3 != null) { intentExtraKeyName3.setText(ppIntent._extraKey3); intentExtraKeyValue3.setText(ppIntent._extraValue3); intentExtraSpinner3.setSelection(ppIntent._extraType3); } if (ppIntent._extraKey4 != null) { intentExtraKeyName4.setText(ppIntent._extraKey4); intentExtraKeyValue4.setText(ppIntent._extraValue4); intentExtraSpinner4.setSelection(ppIntent._extraType4); } if (ppIntent._extraKey5 != null) { intentExtraKeyName5.setText(ppIntent._extraKey5); intentExtraKeyValue5.setText(ppIntent._extraValue5); intentExtraSpinner5.setSelection(ppIntent._extraType5); } } else { intentActionEdit.setEnabled(false); } enableOKButton(); okButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ppIntent._name = intentNameEditText.getText().toString(); if (application != null) application.appLabel = ppIntent._name; ppIntent._packageName = intentPackageName.getText().toString(); ppIntent._className = intentClassName.getText().toString(); ppIntent._data = intentData.getText().toString(); ppIntent._mimeType = intentMimeType.getText().toString(); int actionSpinnerId = intentActionSpinner.getSelectedItemPosition(); if (actionSpinnerId == 0) ppIntent._action = ""; else if (actionSpinnerId == 1) ppIntent._action = intentActionEdit.getText().toString(); else { ppIntent._action = actionsArray[actionSpinnerId]; } ppIntent._categories = ""; int i = 0; for (boolean selected : categoryIndices) { if (selected) { if (!ppIntent._categories.isEmpty()) //noinspection StringConcatenationInLoop ppIntent._categories = ppIntent._categories + "|"; //noinspection StringConcatenationInLoop ppIntent._categories = ppIntent._categories + categoryArray[i]; } ++i; } ppIntent._flags = ""; i = 0; for (boolean selected : flagIndices) { if (selected) { if (!ppIntent._flags.isEmpty()) //noinspection StringConcatenationInLoop ppIntent._flags = ppIntent._flags + "|"; //noinspection StringConcatenationInLoop ppIntent._flags = ppIntent._flags + flagArray[i]; } ++i; } ppIntent._extraKey1 = intentExtraKeyName1.getText().toString(); ppIntent._extraValue1 = intentExtraKeyValue1.getText().toString(); ppIntent._extraType1 = intentExtraSpinner1.getSelectedItemPosition(); ppIntent._extraKey2 = intentExtraKeyName2.getText().toString(); ppIntent._extraValue2 = intentExtraKeyValue2.getText().toString(); ppIntent._extraType2 = intentExtraSpinner2.getSelectedItemPosition(); ppIntent._extraKey3 = intentExtraKeyName3.getText().toString(); ppIntent._extraValue3 = intentExtraKeyValue3.getText().toString(); ppIntent._extraType3 = intentExtraSpinner3.getSelectedItemPosition(); ppIntent._extraKey4 = intentExtraKeyName4.getText().toString(); ppIntent._extraValue4 = intentExtraKeyValue4.getText().toString(); ppIntent._extraType4 = intentExtraSpinner4.getSelectedItemPosition(); ppIntent._extraKey5 = intentExtraKeyName5.getText().toString(); ppIntent._extraValue5 = intentExtraKeyValue5.getText().toString(); ppIntent._extraType5 = intentExtraSpinner5.getSelectedItemPosition(); Intent returnIntent = new Intent(); returnIntent.putExtra(ApplicationEditorDialog.EXTRA_PP_INTENT, ppIntent); returnIntent.putExtra(ApplicationEditorDialog.EXTRA_APPLICATION, application); returnIntent.putExtra(EXTRA_DIALOG_PREFERENCE_START_APPLICATION_DELAY, startApplicationDelay); setResult(Activity.RESULT_OK, returnIntent); finish(); } }); Button cancelButton = findViewById(R.id.application_editor_intent_cancel); //cancelButton.setAllCaps(false); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent returnIntent = new Intent(); setResult(Activity.RESULT_CANCELED, returnIntent); finish(); } }); } private void enableOKButton() { boolean enableOK = (!intentNameEditText.getText().toString().isEmpty()); okButton.setEnabled(enableOK); } }
package com.intellij.openapi.fileEditor.impl; import com.intellij.icons.AllIcons; import com.intellij.ide.GeneralSettings; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.actions.CloseAction; import com.intellij.ide.actions.ShowFilePathAction; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.UISettingsListener; import com.intellij.ide.ui.customization.CustomActionsSchema; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; import com.intellij.openapi.fileEditor.impl.text.FileDropHandler; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Queryable; import com.intellij.openapi.ui.ShadowAction; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.ex.ToolWindowManagerListener; import com.intellij.ui.ColorUtil; import com.intellij.ui.InplaceButton; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.docking.DockContainer; import com.intellij.ui.docking.DockManager; import com.intellij.ui.docking.DockableContent; import com.intellij.ui.docking.DragSession; import com.intellij.ui.tabs.*; import com.intellij.ui.tabs.impl.JBEditorTabs; import com.intellij.ui.tabs.impl.JBTabsImpl; import com.intellij.util.BitUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.TimedDeadzone; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.FocusEvent; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import java.util.Map; /** * @author Anton Katilin * @author Vladimir Kondratyev */ public final class EditorTabbedContainer implements Disposable, CloseAction.CloseTarget { private final EditorWindow myWindow; private final Project myProject; private final JBEditorTabs myTabs; @NonNls public static final String HELP_ID = "ideaInterface.editor"; private final TabInfo.DragOutDelegate myDragOutDelegate = new MyDragOutDelegate(); EditorTabbedContainer(final EditorWindow window, Project project) { myWindow = window; myProject = project; final ActionManager actionManager = ActionManager.getInstance(); myTabs = new JBEditorTabs(project, actionManager, IdeFocusManager.getInstance(project), this) { { if (hasUnderlineSelection()) { IdeEventQueue.getInstance().addDispatcher(createFocusDispatcher(), this); } } private IdeEventQueue.EventDispatcher createFocusDispatcher() { return e -> { if (e instanceof FocusEvent) { Component from = ((FocusEvent)e).getOppositeComponent(); Component to = ((FocusEvent)e).getComponent(); if (isChild(from) || isChild(to)) { myTabs.repaint(); } } return false; }; } private boolean isChild(@Nullable Component c) { if (c == null) return false; if (c == this) return true; return isChild(c.getParent()); } @Override public boolean hasUnderlineSelection() { return UIUtil.isUnderDarcula() && Registry.is("ide.new.editor.tabs.selection"); } }; myTabs.setBorder(new MyShadowBorder(myTabs)); myTabs.setTransferHandler(new MyTransferHandler()); myTabs.setDataProvider(new MyDataProvider()).setPopupGroup( () -> (ActionGroup)CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.GROUP_EDITOR_TAB_POPUP), ActionPlaces.EDITOR_TAB_POPUP, false).addTabMouseListener(new TabMouseListener()).getPresentation() .setTabDraggingEnabled(true).setUiDecorator(() -> new UiDecorator.UiDecoration(null, new Insets(TabsUtil.TAB_VERTICAL_PADDING, 8, TabsUtil.TAB_VERTICAL_PADDING, 8))).setTabLabelActionsMouseDeadzone(TimedDeadzone.NULL).setGhostsAlwaysVisible(true).setTabLabelActionsAutoHide(false) .setActiveTabFillIn(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground()).setPaintFocus(false).getJBTabs() .addListener(new TabsListener() { @Override public void selectionChanged(final TabInfo oldSelection, final TabInfo newSelection) { final FileEditorManager editorManager = FileEditorManager.getInstance(myProject); final FileEditor oldEditor = oldSelection != null ? editorManager.getSelectedEditor((VirtualFile)oldSelection.getObject()) : null; if (oldEditor != null) { oldEditor.deselectNotify(); } VirtualFile newFile = (VirtualFile)newSelection.getObject(); final FileEditor newEditor = editorManager.getSelectedEditor(newFile); if (newEditor != null) { newEditor.selectNotify(); } if (GeneralSettings.getInstance().isSyncOnFrameActivation()) { VfsUtil.markDirtyAndRefresh(true, false, false, newFile); } } }) .setSelectionChangeHandler((info, requestFocus, doChangeSelection) -> { final ActionCallback result = new ActionCallback(); CommandProcessor.getInstance().executeCommand(myProject, () -> { ((IdeDocumentHistoryImpl)IdeDocumentHistory.getInstance(myProject)).onSelectionChanged(); result.notify(doChangeSelection.run()); }, "EditorChange", null); return result; }).getPresentation().setRequestFocusOnLastFocusedComponent(true); myTabs.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (myTabs.findInfo(e) != null || isFloating()) return; if (!e.isPopupTrigger() && SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) { final ActionManager mgr = ActionManager.getInstance(); mgr.tryToExecute(mgr.getAction("HideAllWindows"), e, null, ActionPlaces.UNKNOWN, true); } } }); setTabPlacement(UISettings.getInstance().getEditorTabPlacement()); updateTabBorder(); MessageBusConnection busConnection = project.getMessageBus().connect(); busConnection.subscribe(ToolWindowManagerListener.TOPIC, new ToolWindowManagerListener() { @Override public void stateChanged() { updateTabBorder(); } @Override public void toolWindowRegistered(@NotNull final String id) { updateTabBorder(); } }); busConnection.subscribe(UISettingsListener.TOPIC, uiSettings -> updateTabBorder()); Disposer.register(project, this); } public int getTabCount() { return myTabs.getTabCount(); } @NotNull public ActionCallback setSelectedIndex(final int indexToSelect) { return setSelectedIndex(indexToSelect, true); } @NotNull public ActionCallback setSelectedIndex(final int indexToSelect, boolean focusEditor) { if (indexToSelect >= myTabs.getTabCount()) return ActionCallback.REJECTED; return myTabs.select(myTabs.getTabAt(indexToSelect), focusEditor); } @NotNull public static DockableEditor createDockableEditor(Project project, Image image, VirtualFile file, Presentation presentation, EditorWindow window) { return new DockableEditor(project, image, file, presentation, window.getSize(), window.isFilePinned(file)); } private void updateTabBorder() { if (!myProject.isOpen()) return; ToolWindowManagerEx mgr = (ToolWindowManagerEx)ToolWindowManager.getInstance(myProject); String[] ids = mgr.getToolWindowIds(); Insets border = JBUI.emptyInsets(); UISettings uiSettings = UISettings.getInstance(); List<String> topIds = mgr.getIdsOn(ToolWindowAnchor.TOP); List<String> bottom = mgr.getIdsOn(ToolWindowAnchor.BOTTOM); List<String> rightIds = mgr.getIdsOn(ToolWindowAnchor.RIGHT); List<String> leftIds = mgr.getIdsOn(ToolWindowAnchor.LEFT); if (!uiSettings.getHideToolStripes() && !uiSettings.getPresentationMode()) { border.top = !topIds.isEmpty() ? 1 : 0; border.bottom = !bottom.isEmpty() ? 1 : 0; border.left = !leftIds.isEmpty() ? 1 : 0; border.right = !rightIds.isEmpty() ? 1 : 0; } for (String each : ids) { ToolWindow eachWnd = mgr.getToolWindow(each); if (eachWnd == null || !eachWnd.isAvailable()) continue; if (eachWnd.isVisible() && eachWnd.getType() == ToolWindowType.DOCKED) { ToolWindowAnchor eachAnchor = eachWnd.getAnchor(); if (eachAnchor == ToolWindowAnchor.TOP) { border.top = 0; } else if (eachAnchor == ToolWindowAnchor.BOTTOM) { border.bottom = 0; } else if (eachAnchor == ToolWindowAnchor.LEFT) { border.left = 0; } else if (eachAnchor == ToolWindowAnchor.RIGHT) { border.right = 0; } } } myTabs.getPresentation().setPaintBorder(border.top, border.left, border.right, border.bottom).setTabSidePaintBorder(5); } @NotNull public JComponent getComponent() { return myTabs.getComponent(); } public ActionCallback removeTabAt(final int componentIndex, int indexToSelect, boolean transferFocus) { TabInfo toSelect = indexToSelect >= 0 && indexToSelect < myTabs.getTabCount() ? myTabs.getTabAt(indexToSelect) : null; final TabInfo info = myTabs.getTabAt(componentIndex); // removing hidden tab happens on end of drag-out, we've already selected the correct tab for this case in dragOutStarted if (info.isHidden() || !myProject.isOpen()) { toSelect = null; } final ActionCallback callback = myTabs.removeTab(info, toSelect, transferFocus); return myProject.isOpen() ? callback : ActionCallback.DONE; } public ActionCallback removeTabAt(final int componentIndex, int indexToSelect) { return removeTabAt(componentIndex, indexToSelect, true); } public int getSelectedIndex() { return myTabs.getIndexOf(myTabs.getSelectedInfo()); } void setForegroundAt(final int index, final Color color) { myTabs.getTabAt(index).setDefaultForeground(color); } void setWaveColor(final int index, @Nullable final Color color) { final TabInfo tab = myTabs.getTabAt(index); tab.setDefaultStyle(color == null ? SimpleTextAttributes.STYLE_PLAIN : SimpleTextAttributes.STYLE_WAVED); tab.setDefaultWaveColor(color); } void setIconAt(final int index, final Icon icon) { myTabs.getTabAt(index).setIcon(icon); } public void setTitleAt(final int index, final String text) { myTabs.getTabAt(index).setText(text); } void setToolTipTextAt(final int index, final String text) { myTabs.getTabAt(index).setTooltipText(text); } void setBackgroundColorAt(final int index, final Color color) { myTabs.getTabAt(index).setTabColor(color); } void setTabLayoutPolicy(final int policy) { switch (policy) { case JTabbedPane.SCROLL_TAB_LAYOUT: myTabs.getPresentation().setSingleRow(true); break; case JTabbedPane.WRAP_TAB_LAYOUT: myTabs.getPresentation().setSingleRow(false); break; default: throw new IllegalArgumentException("Unsupported tab layout policy: " + policy); } } public void setTabPlacement(final int tabPlacement) { switch (tabPlacement) { case SwingConstants.TOP: myTabs.getPresentation().setTabsPosition(JBTabsPosition.top); break; case SwingConstants.BOTTOM: myTabs.getPresentation().setTabsPosition(JBTabsPosition.bottom); break; case SwingConstants.LEFT: myTabs.getPresentation().setTabsPosition(JBTabsPosition.left); break; case SwingConstants.RIGHT: myTabs.getPresentation().setTabsPosition(JBTabsPosition.right); break; default: throw new IllegalArgumentException("Unknown tab placement code=" + tabPlacement); } } /** * @param ignorePopup if <code>false</code> and context menu is shown currently for some tab, * component for which menu is invoked will be returned */ @Nullable public Object getSelectedComponent(boolean ignorePopup) { final TabInfo info = ignorePopup ? myTabs.getSelectedInfo() : myTabs.getTargetInfo(); return info != null ? info.getComponent() : null; } public void insertTab(@NotNull VirtualFile file, final Icon icon, final JComponent comp, final String tooltip, final int indexToInsert) { TabInfo tab = myTabs.findInfo(file); if (tab != null) { return; } tab = new TabInfo(comp) .setText(EditorTabPresentationUtil.getEditorTabTitle(myProject, file, myWindow)) .setTabColor(EditorTabPresentationUtil.getEditorTabBackgroundColor(myProject, file, myWindow)) .setIcon(icon) .setTooltipText(tooltip) .setObject(file) .setDragOutDelegate(myDragOutDelegate); tab.setTestableUi(new MyQueryable(tab)); final DefaultActionGroup tabActions = new DefaultActionGroup(); tabActions.add(new CloseTab(comp, file)); tab.setTabLabelActions(tabActions, ActionPlaces.EDITOR_TAB); myTabs.addTabSilently(tab, indexToInsert); } boolean isEmptyVisible() { return myTabs.isEmptyVisible(); } public JBTabs getTabs() { return myTabs; } public void requestFocus(boolean forced) { if (myTabs != null) { IdeFocusManager.getInstance(myProject).requestFocus(myTabs.getComponent(), forced); } } void setPaintBlocked(boolean blocked) { myTabs.setPaintBlocked(blocked, true); } private static class MyQueryable implements Queryable { private final TabInfo myTab; MyQueryable(TabInfo tab) { myTab = tab; } @Override public void putInfo(@NotNull Map<String, String> info) { info.put("editorTab", myTab.getText()); } } /** @deprecated Use {@link EditorTabPresentationUtil#getEditorTabTitle(Project, VirtualFile, EditorWindow)} */ @NotNull public static String calcTabTitle(@NotNull Project project, @NotNull VirtualFile file) { return EditorTabPresentationUtil.getEditorTabTitle(project, file, null); } /** @deprecated Use {@link EditorTabPresentationUtil#getUniqueEditorTabTitle(Project, VirtualFile, EditorWindow)} */ @NotNull public static String calcFileName(@NotNull Project project, @NotNull VirtualFile file) { return EditorTabPresentationUtil.getUniqueEditorTabTitle(project, file, null); } /** @deprecated Use {@link EditorTabPresentationUtil#getEditorTabBackgroundColor(Project, VirtualFile, EditorWindow)} */ @Nullable public static Color calcTabColor(@NotNull Project project, @NotNull VirtualFile file) { return EditorTabPresentationUtil.getEditorTabBackgroundColor(project, file, null); } public Component getComponentAt(final int i) { final TabInfo tab = myTabs.getTabAt(i); return tab.getComponent(); } @Override public void dispose() { } private final class CloseTab extends AnAction implements DumbAware { private final VirtualFile myFile; CloseTab(@NotNull JComponent c, @NotNull VirtualFile file) { myFile = file; new ShadowAction(this, ActionManager.getInstance().getAction(IdeActions.ACTION_CLOSE), c, myTabs); } @Override public void update(final AnActionEvent e) { e.getPresentation().setIcon(AllIcons.Actions.CloseNew); e.getPresentation().setHoveredIcon(AllIcons.Actions.CloseNewHovered); e.getPresentation().setVisible(UISettings.getInstance().getShowCloseButton()); e.getPresentation().setText("Close. Alt-click to close others."); } @Override public void actionPerformed(final AnActionEvent e) { final FileEditorManagerEx mgr = FileEditorManagerEx.getInstanceEx(myProject); EditorWindow window; if (ActionPlaces.EDITOR_TAB.equals(e.getPlace())) { window = myWindow; } else { window = mgr.getCurrentWindow(); } if (window != null) { if (BitUtil.isSet(e.getModifiers(), InputEvent.ALT_MASK)) { window.closeAllExcept(myFile); } else { if (window.findFileComposite(myFile) != null) { mgr.closeFile(myFile, window); } } } } } private final class MyDataProvider implements DataProvider { @Override public Object getData(@NonNls final String dataId) { if (CommonDataKeys.PROJECT.is(dataId)) { return myProject; } if (CommonDataKeys.VIRTUAL_FILE.is(dataId)) { final VirtualFile selectedFile = myWindow.getSelectedFile(); return selectedFile != null && selectedFile.isValid() ? selectedFile : null; } if (EditorWindow.DATA_KEY.is(dataId)) { return myWindow; } if (PlatformDataKeys.HELP_ID.is(dataId)) { return HELP_ID; } if (CloseAction.CloseTarget.KEY.is(dataId)) { TabInfo selected = myTabs.getSelectedInfo(); if (selected != null) { return EditorTabbedContainer.this; } } if (EditorWindow.DATA_KEY.is(dataId)) { return myWindow; } return null; } } @Override public void close() { TabInfo selected = myTabs.getTargetInfo(); if (selected == null) return; final VirtualFile file = (VirtualFile)selected.getObject(); final FileEditorManagerEx mgr = FileEditorManagerEx.getInstanceEx(myProject); mgr .getActiveWindow() .onSuccess(wnd -> { if (wnd != null) { if (wnd.findFileComposite(file) != null) { mgr.closeFile(file, wnd); } } }); } private boolean isFloating() { return myWindow.getOwner().isFloating(); } private class TabMouseListener extends MouseAdapter { private int myActionClickCount; @Override public void mouseReleased(MouseEvent e) { if (UIUtil.isCloseClick(e, MouseEvent.MOUSE_RELEASED)) { final TabInfo info = myTabs.findInfo(e); if (info != null) { IdeEventQueue.getInstance().blockNextEvents(e); if (e.isAltDown() && e.getButton() == MouseEvent.BUTTON1) {//close others List<TabInfo> allTabInfos = myTabs.getTabs(); for (TabInfo tabInfo : allTabInfos) { if (tabInfo == info) continue; FileEditorManagerEx.getInstanceEx(myProject).closeFile((VirtualFile)tabInfo.getObject(), myWindow); } } else { FileEditorManagerEx.getInstanceEx(myProject).closeFile((VirtualFile)info.getObject(), myWindow); } } } } @Override public void mousePressed(final MouseEvent e) { if (UIUtil.isActionClick(e)) { if (e.getClickCount() == 1) { myActionClickCount = 0; } // clicks on the close window button don't count in determining whether we have a double-click on tab (IDEA-70403) final Component deepestComponent = SwingUtilities.getDeepestComponentAt(e.getComponent(), e.getX(), e.getY()); if (!(deepestComponent instanceof InplaceButton)) { myActionClickCount++; } if (myActionClickCount > 1 && !isFloating()) { final ActionManager mgr = ActionManager.getInstance(); mgr.tryToExecute(mgr.getAction("HideAllWindows"), e, null, ActionPlaces.UNKNOWN, true); } } } @Override public void mouseClicked(MouseEvent e) { if (UIUtil.isActionClick(e, MouseEvent.MOUSE_CLICKED) && (e.isMetaDown() || !SystemInfo.isMac && e.isControlDown())) { final TabInfo info = myTabs.findInfo(e); Object o = info == null ? null : info.getObject(); if (o instanceof VirtualFile) { ShowFilePathAction.show((VirtualFile)o, e); } } } } class MyDragOutDelegate implements TabInfo.DragOutDelegate { private VirtualFile myFile; private DragSession mySession; @Override public void dragOutStarted(MouseEvent mouseEvent, TabInfo info) { final TabInfo previousSelection = info.getPreviousSelection(); final Image img = JBTabsImpl.getComponentImage(info); info.setHidden(true); if (previousSelection != null) { myTabs.select(previousSelection, true); } myFile = (VirtualFile)info.getObject(); Presentation presentation = new Presentation(info.getText()); presentation.setIcon(info.getIcon()); mySession = getDockManager().createDragSession(mouseEvent, createDockableEditor(myProject, img, myFile, presentation, myWindow)); } private DockManager getDockManager() { return DockManager.getInstance(myProject); } @Override public void processDragOut(MouseEvent event, TabInfo source) { mySession.process(event); } @Override public void dragOutFinished(MouseEvent event, TabInfo source) { boolean copy = UIUtil.isControlKeyDown(event) || mySession.getResponse(event) == DockContainer.ContentResponse.ACCEPT_COPY; if (!copy) { myFile.putUserData(FileEditorManagerImpl.CLOSING_TO_REOPEN, Boolean.TRUE); FileEditorManagerEx.getInstanceEx(myProject).closeFile(myFile, myWindow); } else { source.setHidden(false); } mySession.process(event); if (!copy) { myFile.putUserData(FileEditorManagerImpl.CLOSING_TO_REOPEN, null); } myFile = null; mySession = null; } @Override public void dragOutCancelled(TabInfo source) { source.setHidden(false); if (mySession != null) { mySession.cancel(); } myFile = null; mySession = null; } } public static class DockableEditor implements DockableContent<VirtualFile> { final Image myImg; private final DockableEditorTabbedContainer myContainer; private final Presentation myPresentation; private final Dimension myPreferredSize; private final boolean myPinned; private final VirtualFile myFile; public DockableEditor(Project project, Image img, VirtualFile file, Presentation presentation, Dimension preferredSize, boolean isFilePinned) { myImg = img; myFile = file; myPresentation = presentation; myContainer = new DockableEditorTabbedContainer(project); myPreferredSize = preferredSize; myPinned = isFilePinned; } @NotNull @Override public VirtualFile getKey() { return myFile; } @Override public Image getPreviewImage() { return myImg; } @Override public Dimension getPreferredSize() { return myPreferredSize; } @Override public String getDockContainerType() { return DockableEditorContainerFactory.TYPE; } @Override public Presentation getPresentation() { return myPresentation; } @Override public void close() { myContainer.close(myFile); } public VirtualFile getFile() { return myFile; } public boolean isPinned() { return myPinned; } } private final class MyTransferHandler extends TransferHandler { private final FileDropHandler myFileDropHandler = new FileDropHandler(null); @Override public boolean importData(JComponent comp, Transferable t) { if (myFileDropHandler.canHandleDrop(t.getTransferDataFlavors())) { myFileDropHandler.handleDrop(t, myProject, myWindow); return true; } return false; } @Override public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { return myFileDropHandler.canHandleDrop(transferFlavors); } } private static class MyShadowBorder implements Border { private final JBEditorTabs myTabs; MyShadowBorder(JBEditorTabs tabs) { myTabs = tabs; } @Override public void paintBorder(Component component, Graphics g, int x, int y, int w, int h) { Rectangle selectedBounds = myTabs.getSelectedBounds(); if (selectedBounds != null && selectedBounds.y > 0) selectedBounds = null;//Not first row selection Rectangle bounds = new Rectangle(x, y, w, h); g.setColor(UIUtil.CONTRAST_BORDER_COLOR); drawLine(bounds, selectedBounds, g, 0); if (UIUtil.isUnderDarcula() || true) { //remove shadow for all for awhile return; } g.setColor(ColorUtil.withAlpha(UIUtil.CONTRAST_BORDER_COLOR, .5)); drawLine(bounds, selectedBounds, g, 1); g.setColor(ColorUtil.withAlpha(UIUtil.CONTRAST_BORDER_COLOR, .2)); drawLine(bounds, selectedBounds, g, 2); } private static void drawLine(Rectangle bounds, @Nullable Rectangle selectedBounds, Graphics g, int yShift) { if (selectedBounds != null) { if (selectedBounds.x > 0) { UIUtil.drawLine(g, bounds.x, bounds.y + yShift, selectedBounds.x - 2, bounds.y + yShift); } UIUtil.drawLine(g, selectedBounds.x + selectedBounds.width + 1, bounds.y + yShift, bounds.x + bounds.width, bounds.y + yShift); } else { UIUtil.drawLine(g, bounds.x, bounds.y + yShift, bounds.x + bounds.width, bounds.y + yShift); } } @Override public Insets getBorderInsets(Component component) { return JBUI.emptyInsets(); } @Override public boolean isBorderOpaque() { return false; } } }
package app; import java.io.IOException; import java.net.URI; import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; import com.sun.net.httpserver.HttpServer; public class Server { public static void main(String[] args) throws IOException { URI uri = URI.create("http://localhost:8080/rest/"); ResourceConfig rc = new ResourceConfig(); rc.register(Calc.class); HttpServer httpServer = JdkHttpServerFactory.createHttpServer(uri, rc); Runtime.getRuntime().addShutdownHook(new Thread(() -> httpServer.stop(0))); } }
package com.opengamma.financial.analytics; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.opengamma.core.position.PortfolioNode; import com.opengamma.core.position.Position; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.CompiledFunctionDefinition; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.property.UnitProperties; /** * Able to sum a particular requirement name from a set of underlying positions. If any values are not produced (because of missing market data or computation errors) a partial sum is produced. */ public class SummingFunction extends MissingInputsFunction { public static final String IGNORE_ROOT_NODE = "SummingFunction.IGNORE_ROOT_NODE"; /** * The number of positions that made up the sum. */ private static final String POSITION_COUNT = "PositionCount"; /** * Main implementation. */ protected static class Impl extends AbstractFunction.NonCompiledInvoker { private final String _requirementName; private final String[] _homogenousProperties = UnitProperties.unitPropertyNames(); protected Impl(final String requirementName) { _requirementName = requirementName; } private static CompiledFunctionDefinition of(final String requirementName) { return new Impl(requirementName); } protected String getRequirementName() { return _requirementName; } @Override public String getShortName() { return "Sum(" + _requirementName + ")"; } @Override public ComputationTargetType getTargetType() { return ComputationTargetType.PORTFOLIO_NODE; } @Override public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) { // Applies to any portfolio node, except the root if "Don't aggregate root node" is set if (context.getPortfolio().getAttributes().get(IGNORE_ROOT_NODE) == null) { return true; } else { return target.getPortfolioNode().getParentNodeId() != null; } } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { return Collections.singleton(new ValueSpecification(getRequirementName(), target.toSpecification(), ValueProperties.all())); } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final PortfolioNode node = target.getPortfolioNode(); final Set<ValueRequirement> requirements = new HashSet<ValueRequirement>(); // Requirement has all constraints asked of us final ValueProperties.Builder resultConstraintsBuilder = desiredValue.getConstraints().copy(); for (final String homogenousProperty : _homogenousProperties) { // TODO: this should probably only be optional if absent from the desired constraints resultConstraintsBuilder.withOptional(homogenousProperty); } ValueProperties resultConstraints = resultConstraintsBuilder.get(); for (final Position position : node.getPositions()) { requirements.add(new ValueRequirement(getRequirementName(), ComputationTargetType.POSITION, position.getUniqueId().toLatest(), resultConstraints)); } for (final PortfolioNode childNode : node.getChildNodes()) { requirements.add(new ValueRequirement(getRequirementName(), ComputationTargetType.PORTFOLIO_NODE, childNode.getUniqueId(), resultConstraints)); } return requirements; } protected Object addValue(final Object previousSum, final Object currentValue) { return SumUtils.addValue(previousSum, currentValue, getRequirementName()); } protected ValueProperties.Builder createValueProperties(final ValueProperties inputProperties, final int componentCount) { return inputProperties.copy().withoutAny(ValuePropertyNames.FUNCTION).with(ValuePropertyNames.FUNCTION, getUniqueId()).with(POSITION_COUNT, Integer.toString(componentCount)); } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) { int positionCount = 0; // Result properties are anything that was common to the input requirements ValueProperties common = null; final boolean[] homogenousProperties = new boolean[_homogenousProperties.length]; for (final ValueSpecification input : inputs.keySet()) { final ValueProperties properties = input.getProperties(); final Set<String> inputPositionCountValues = properties.getValues(POSITION_COUNT); if (inputPositionCountValues == null) { positionCount++; } else { if (inputPositionCountValues.size() == 1) { final int inputPositionCount = Integer.parseInt(inputPositionCountValues.iterator().next()); if (inputPositionCount == 0) { // Ignore this one continue; } positionCount += inputPositionCount; } } if (common == null) { common = properties; for (int i = 0; i < homogenousProperties.length; i++) { homogenousProperties[i] = properties.getValues(_homogenousProperties[i]) != null; } } else { for (int i = 0; i < homogenousProperties.length; i++) { if ((properties.getValues(_homogenousProperties[i]) != null) != homogenousProperties[i]) { // Either defines one of the properties that something else doesn't, or doesn't define // one that something else does return null; } } common = SumUtils.addProperties(common, properties); } } if (common == null) { // Can't have been any inputs - the sum will be zero with any properties the caller wants return Collections.singleton(new ValueSpecification(getRequirementName(), target.toSpecification(), createValueProperties().with(POSITION_COUNT, "0").get())); } for (int i = 0; i < homogenousProperties.length; i++) { if (homogenousProperties[i] == Boolean.TRUE) { if (common.getValues(_homogenousProperties[i]) == null) { // No common intersection of values for homogenous property return null; } } } return Collections.singleton(new ValueSpecification(getRequirementName(), target.toSpecification(), createValueProperties(common, positionCount).get())); } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final ValueRequirement desiredValue = desiredValues.iterator().next(); Object value = null; for (final ComputedValue input : inputs.getAllValues()) { final Object inputValue = input.getValue(); if (inputValue instanceof String) { // Threat the empty string as a special case - it's used in place of 0 when there are no valid inputs if (((String) inputValue).length() == 0) { continue; } } value = addValue(value, input.getValue()); } if (value == null) { // Can't have been any non-zero inputs - the sum is logical zero value = ""; } return Collections.singleton(new ComputedValue(new ValueSpecification(getRequirementName(), target.toSpecification(), desiredValue.getConstraints()), value)); } } public SummingFunction(final String requirementName) { super(Impl.of(requirementName)); } }
package fp4g.generator.models; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import fp4g.classes.MessageMethod; import fp4g.data.On; import fp4g.data.On.Filter; import fp4g.data.On.Source; import fp4g.data.expresion.ClassMap; public class OnModel implements Model { //Que necesito ac: //Nombre categoria mensaje private final String name; //Necesitar una lista de los MethodHandlers! private final List<MethodHandlerModel> methodHandlers; public OnModel(On on) { name = on.name; methodHandlers = new LinkedList<>(); HashMap<String,MethodHandlerModel> methods = new HashMap<>(); //agregar los metodos, aunque estn vacios y asumiento que todos son MessageMethod for(Entry<String,Object> entry:on.message.entrySet()) { ClassMap map = (ClassMap)entry.getValue(); methods.put(entry.getKey(), new MethodHandlerModel((MessageMethod)map.getBean())); } //tengo que recorrer los sources en busca de los methodHandlers y subirlos ac for(Source source:on.sources) { SourceModel.findAndInsert(source,methods); } methodHandlers.addAll(methods.values()); } public static class SourceModel implements Model { //El codigo private final String code; //Una lista de filtros (disyuncin) private final List<FilterD> filters; public SourceModel(Source source) { //code = on.getCode(); code = "//TODO falta el codigo.."; //TODO falta el codigo filters = new LinkedList<>(); } public static void findAndInsert(final Source source,final HashMap<String,MethodHandlerModel> methods) { final HashMap<MethodHandlerModel,SourceModel> sourcesMap = new HashMap<>(); if(source.filters.size() > 0) { for(Filter f:source.filters) { final int l = f.lenght(); for(int i=0;i<l;i++) { final MessageMethod method = f.methods[i]; final String value = f.values[i]; //encontr un metodo, que hago con el MethodHandlerModel m = methods.get(method.getMethodName()); // if(m == null) //siempre son != null // m = new MethodHandlerModel(method); // methods.put(method.getMethodName(), m); //obtengo el source model correspondiente SourceModel sm = sourcesMap.get(m); if(sm == null) { sm = new SourceModel(source); sourcesMap.put(m, sm); } //ya tengo el metodo manejador, que hago con el? //facil, ahora debes agregar este filtro //pero como diferencio si es conjuncion o disyuncin? //todos los que estn en este for, son una conjuncin if(value != null) //me aseguro que sea distinto de nulo, asi no agrega nada adicional { FilterD filterD = sm.getCurrentFilterD(f); filterD.add(method,value); //agrego el filtro actual } } //ahora como agrego otra disyuncin? //lo har en currentFilter, guardar la ultima iteracin. Si esta cambia, entonces agregar otro filtro. } } else //cuando hay 0 filtros { for(Entry<String,MethodHandlerModel> entry:methods.entrySet()) { //cuando hay 0 filtros, el source se agrega a cada uno de los metodos entry.getValue().addSource(new SourceModel(source)); } } //al finalizar for(Entry<MethodHandlerModel, SourceModel> entry:sourcesMap.entrySet()) { entry.getKey().addSource(entry.getValue()); } } //este no va para el Freemarker private FilterD current; private Filter lastFilterIter; //devuelve el filtro actual. public FilterD getCurrentFilterD(Filter lf) { if(current == null) { createNewFilterD(); lastFilterIter = lf; return current; } if(lastFilterIter != lf) { lastFilterIter = lf; createNewFilterD(); } return current; } //guarda y crea otro filtro D private void createNewFilterD() { current = new FilterD(); filters.add(current); } public final String getCode() { return code; } public final List<FilterD> getFiltersD() { return filters; } } public static class MethodHandlerModel implements Model { //que necesito ac, por cada MethodHander necesito: //Nombre del metodo private final String name; //Una lista de Source Codes private final List<SourceModel> sources; //Parametros private final String params; public MethodHandlerModel(MessageMethod method) { name = method.getMethodName(); params = method.getParams(); sources = new LinkedList<>(); } public void addSource(SourceModel value) { sources.add(value); } public final String getName() { return name; } public final List<SourceModel> getSources() { return sources; } public final String getParams() { return params; } } public static class FilterD implements Model { //que necesito ac. Por cada FilterS necesito: //Una lista de conjunciones private final List<String> conjunciones; public FilterD() { conjunciones = new LinkedList<>(); } public void add(MessageMethod method, String value) { conjunciones.add(String.format(method.getValueReplace(),value)); } public List<String> getFiltersC() { return conjunciones; } } public final String getName() { return name; } public final List<MethodHandlerModel> getMethodHandlers() { return methodHandlers; } }
package net.orfjackal.retrolambda.interfaces; import net.orfjackal.retrolambda.util.*; import org.objectweb.asm.*; import java.util.*; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static org.objectweb.asm.Opcodes.*; public class ClassHierarchyAnalyzer implements MethodRelocations { private static final MethodRef ABSTRACT_METHOD = new MethodRef("", "", ""); private final Map<Type, ClassInfo> classes = new HashMap<>(); private final Map<MethodRef, MethodRef> relocatedMethods = new HashMap<>(); private final Map<MethodRef, MethodRef> methodDefaultImpls = new HashMap<>(); private final Map<String, String> companionClasses = new HashMap<>(); public void analyze(byte[] bytecode) { ClassReader cr = new ClassReader(bytecode); ClassInfo c = new ClassInfo(cr); classes.put(c.type, c); if (Flags.hasFlag(cr.getAccess(), ACC_INTERFACE)) { analyzeInterface(c, cr); } else { analyzeClass(c, cr); } } private void analyzeClass(ClassInfo c, ClassReader cr) { cr.accept(new ClassVisitor(ASM5) { private String owner; @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { this.owner = name; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodRef method = new MethodRef(owner, name, desc); // FIXME: skip static methods c.methods.add(method); // XXX: backporting Retrolambda fails if we remove this; it tries backporting a lambda while backporting a lambda Runnable r = () -> { }; return null; } }, ClassReader.SKIP_CODE); } private void analyzeInterface(ClassInfo c, ClassReader cr) { cr.accept(new ClassVisitor(ASM5) { private String owner; private String companion; @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { this.owner = name; this.companion = name + "$"; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodRef method = new MethodRef(owner, name, desc); if (isAbstractMethod(access)) { methodDefaultImpls.put(method, ABSTRACT_METHOD); c.methods.add(method); } else if (isDefaultMethod(access)) { desc = Bytecode.prependArgumentType(desc, Type.getObjectType(owner)); methodDefaultImpls.put(method, new MethodRef(companion, name, desc)); companionClasses.put(owner, companion); c.methods.add(method); } else if (isStaticMethod(access)) { relocatedMethods.put(method, new MethodRef(companion, name, desc)); companionClasses.put(owner, companion); } return null; } private boolean isAbstractMethod(int access) { return Flags.hasFlag(access, ACC_ABSTRACT); } private boolean isStaticMethod(int access) { return Flags.hasFlag(access, ACC_STATIC); } private boolean isDefaultMethod(int access) { return !isAbstractMethod(access) && !isStaticMethod(access); } }, ClassReader.SKIP_CODE); } public List<ClassInfo> getInterfaces() { return classes.values() .stream() .filter(ClassInfo::isInterface) .collect(toList()); } public List<ClassInfo> getClasses() { return classes.values() .stream() .filter(ClassInfo::isClass) .collect(toList()); } private ClassInfo getClass(Type type) { return classes.getOrDefault(type, new ClassInfo()); } public List<Type> getInterfacesOf(Type type) { return getClass(type).interfaces; } @Override public MethodRef getMethodCallTarget(MethodRef original) { return relocatedMethods.getOrDefault(original, original); } @Override public MethodRef getMethodDefaultImplementation(MethodRef interfaceMethod) { MethodRef impl; List<Type> currentInterfaces = new ArrayList<>(); List<Type> parentInterfaces = new ArrayList<>(); currentInterfaces.add(Type.getObjectType(interfaceMethod.owner)); do { for (Type anInterface : currentInterfaces) { impl = methodDefaultImpls.get(interfaceMethod.withOwner(anInterface.getInternalName())); if (impl == ABSTRACT_METHOD) { return null; } if (impl != null) { return impl; } parentInterfaces.addAll(getInterfacesOf(anInterface)); } currentInterfaces = parentInterfaces; parentInterfaces = new ArrayList<>(); } while (!currentInterfaces.isEmpty()); return null; } @Override public List<MethodRef> getInterfaceMethods(Type type) { Set<MethodRef> results = new LinkedHashSet<>(); results.addAll(getClass(type).methods); for (Type parent : getInterfacesOf(type)) { for (MethodRef parentMethod : getInterfaceMethods(parent)) { results.add(parentMethod.withOwner(type.getInternalName())); } } return new ArrayList<>(results); } public List<MethodRef> getSuperclassMethods(Type type) { Set<MethodRef> results = new LinkedHashSet<>(); while (classes.containsKey(type)) { ClassInfo c = classes.get(type); type = c.superclass; results.addAll(getClass(type).methods); } return new ArrayList<>(results); } @Override public String getCompanionClass(String className) { return companionClasses.get(className); } static List<Type> classNamesToTypes(String[] interfaces) { return Stream.of(interfaces) .map(ClassHierarchyAnalyzer::classNameToType) .collect(toList()); } static Type classNameToType(String className) { return Type.getType("L" + className + ";"); } }
package org.duracloud.durastore.aop; import org.apache.log4j.Logger; import org.springframework.aop.AfterReturningAdvice; import org.springframework.core.Ordered; import org.springframework.jms.core.JmsTemplate; import javax.jms.Destination; import java.lang.reflect.Method; public class IngestAdvice implements AfterReturningAdvice, Ordered { private final Logger log = Logger.getLogger(getClass()); protected static final int STORE_ID_INDEX = 1; protected static final int SPACE_ID_INDEX = 2; protected static final int CONTENT_ID_INDEX = 3; protected static final int MIMETYPE_INDEX = 4; private JmsTemplate jmsTemplate; private Destination destination; private int order; public void afterReturning(Object returnObj, Method method, Object[] methodArgs, Object targetObj) throws Throwable { if (log.isDebugEnabled()) { doLogging(returnObj, method, methodArgs, targetObj); } publishIngestEvent(createIngestMessage(methodArgs)); } private void publishIngestEvent(IngestMessage ingestEvent) { getJmsTemplate().convertAndSend(getDestination(), ingestEvent); } private IngestMessage createIngestMessage(Object[] methodArgs) { String storeId = getStoreId(methodArgs); String contentId = getContentId(methodArgs); String contentMimeType = getMimeType(methodArgs); String spaceId = getSpaceId(methodArgs); IngestMessage msg = new IngestMessage(); msg.setStoreId(storeId); msg.setContentId(contentId); msg.setContentMimeType(contentMimeType); msg.setSpaceId(spaceId); return msg; } private String getStoreId(Object[] methodArgs) { log.debug("Returning 'storeId' at index: " + STORE_ID_INDEX); return (String) methodArgs[STORE_ID_INDEX]; } private String getContentId(Object[] methodArgs) { log.debug("Returning 'contentId' at index: " + CONTENT_ID_INDEX); return (String) methodArgs[CONTENT_ID_INDEX]; } private String getMimeType(Object[] methodArgs) { log.debug("Returning 'contentMimeType' at index: " + MIMETYPE_INDEX); return (String) methodArgs[MIMETYPE_INDEX]; } private String getSpaceId(Object[] methodArgs) { log.debug("Returning 'spaceId' at index: " + SPACE_ID_INDEX); return (String) methodArgs[SPACE_ID_INDEX]; } private void doLogging(Object returnObj, Method method, Object[] methodArgs, Object targetObj) { String pre0 = " String pre1 = pre0 + " String pre2 = pre1 + " log.debug(pre0 + "advice: publish to ingest topic"); if (targetObj != null && targetObj.getClass() != null) { log.debug(pre1 + "object: " + targetObj.getClass().getName()); } if (method != null) { log.debug(pre1 + "method: " + method.getName()); } if (methodArgs != null) { for (Object obj : methodArgs) { String argValue; if(obj == null) { argValue = "null"; } else { argValue = obj.toString(); } log.debug(pre2 + "method-arg: " + argValue); } } } public JmsTemplate getJmsTemplate() { return jmsTemplate; } public void setJmsTemplate(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } public Destination getDestination() { return destination; } public void setDestination(Destination destination) { this.destination = destination; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } }
package net.runelite.client.plugins.wintertodt; import com.google.inject.Provides; import java.time.Duration; import java.time.Instant; import javax.inject.Inject; import lombok.AccessLevel; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import static net.runelite.api.AnimationID.CONSTRUCTION; import static net.runelite.api.AnimationID.FIREMAKING; import static net.runelite.api.AnimationID.FLETCHING_BOW_CUTTING; import static net.runelite.api.AnimationID.IDLE; import static net.runelite.api.AnimationID.LOOKING_INTO; import static net.runelite.api.AnimationID.WOODCUTTING_3A_AXE; import static net.runelite.api.AnimationID.WOODCUTTING_ADAMANT; import static net.runelite.api.AnimationID.WOODCUTTING_BLACK; import static net.runelite.api.AnimationID.WOODCUTTING_BRONZE; import static net.runelite.api.AnimationID.WOODCUTTING_DRAGON; import static net.runelite.api.AnimationID.WOODCUTTING_INFERNAL; import static net.runelite.api.AnimationID.WOODCUTTING_IRON; import static net.runelite.api.AnimationID.WOODCUTTING_MITHRIL; import static net.runelite.api.AnimationID.WOODCUTTING_RUNE; import static net.runelite.api.AnimationID.WOODCUTTING_STEEL; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemContainer; import static net.runelite.api.ItemID.BRUMA_KINDLING; import static net.runelite.api.ItemID.BRUMA_ROOT; import net.runelite.api.MessageNode; import net.runelite.api.Player; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.events.ItemContainerChanged; import net.runelite.api.events.SetMessage; import net.runelite.client.Notifier; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.util.ColorUtil; @PluginDescriptor( name = "Wintertodt", description = "Show helpful information for the Wintertodt minigame", tags = {"minigame", "firemaking"} ) @Slf4j public class WintertodtPlugin extends Plugin { private static final int WINTERTODT_REGION = 6462; @Inject private Notifier notifier; @Inject private Client client; @Inject private OverlayManager overlayManager; @Inject private WintertodtOverlay overlay; @Inject private WintertodtConfig config; @Inject private ChatMessageManager chatMessageManager; @Getter(AccessLevel.PACKAGE) private WintertodtActivity currentActivity = WintertodtActivity.IDLE; @Getter(AccessLevel.PACKAGE) private int inventoryScore; @Getter(AccessLevel.PACKAGE) private int totalPotentialinventoryScore; @Getter(AccessLevel.PACKAGE) private int numLogs; @Getter(AccessLevel.PACKAGE) private int numKindling; @Getter(AccessLevel.PACKAGE) private boolean isInWintertodt; private Instant lastActionTime; @Provides WintertodtConfig getConfig(ConfigManager configManager) { return configManager.getConfig(WintertodtConfig.class); } @Override protected void startUp() throws Exception { reset(); overlayManager.add(overlay); } @Override protected void shutDown() throws Exception { overlayManager.remove(overlay); reset(); } private void reset() { inventoryScore = 0; totalPotentialinventoryScore = 0; numLogs = 0; numKindling = 0; currentActivity = WintertodtActivity.IDLE; lastActionTime = null; } private boolean isInWintertodtRegion() { if (client.getLocalPlayer() != null) { return client.getLocalPlayer().getWorldLocation().getRegionID() == WINTERTODT_REGION; } return false; } @Subscribe public void onGameTick(GameTick gameTick) { if (!isInWintertodtRegion()) { if (isInWintertodt) { log.debug("Left Wintertodt!"); reset(); } isInWintertodt = false; return; } if (!isInWintertodt) { reset(); log.debug("Entered Wintertodt!"); } isInWintertodt = true; checkActionTimeout(); } private void checkActionTimeout() { if (currentActivity == WintertodtActivity.IDLE) { return; } int currentAnimation = client.getLocalPlayer() != null ? client.getLocalPlayer().getAnimation() : -1; if (currentAnimation != IDLE || lastActionTime == null) { return; } Duration actionTimeout = Duration.ofSeconds(3); Duration sinceAction = Duration.between(lastActionTime, Instant.now()); if (sinceAction.compareTo(actionTimeout) >= 0) { log.debug("Activity timeout!"); currentActivity = WintertodtActivity.IDLE; } } @Subscribe public void onSetMessage(SetMessage setMessage) { if (!isInWintertodt) { return; } ChatMessageType chatMessageType = setMessage.getType(); if (chatMessageType != ChatMessageType.SERVER && chatMessageType != ChatMessageType.FILTERED) { return; } MessageNode messageNode = setMessage.getMessageNode(); final WintertodtInterruptType interruptType; if (messageNode.getValue().startsWith("The cold of")) { interruptType = WintertodtInterruptType.COLD; } else if (messageNode.getValue().startsWith("The freezing cold attack")) { interruptType = WintertodtInterruptType.SNOWFALL; } else if (messageNode.getValue().startsWith("The brazier is broken and shrapnel")) { interruptType = WintertodtInterruptType.BRAZIER; } else if (messageNode.getValue().startsWith("You have run out of bruma roots")) { interruptType = WintertodtInterruptType.OUT_OF_ROOTS; } else if (messageNode.getValue().startsWith("Your inventory is too full")) { interruptType = WintertodtInterruptType.INVENTORY_FULL; } else if (messageNode.getValue().startsWith("You fix the brazier")) { interruptType = WintertodtInterruptType.FIXED_BRAZIER; } else if (messageNode.getValue().startsWith("You light the brazier")) { interruptType = WintertodtInterruptType.LIT_BRAZIER; } else if (messageNode.getValue().startsWith("The brazier has gone out.")) { interruptType = WintertodtInterruptType.BRAZIER_WENT_OUT; } else { return; } boolean wasInterrupted = false; boolean wasDamaged = false; boolean neverNotify = false; switch (interruptType) { case COLD: case BRAZIER: case SNOWFALL: wasDamaged = true; // Recolor message for damage notification messageNode.setRuneLiteFormatMessage(ColorUtil.wrapWithColorTag(messageNode.getValue(), config.damageNotificationColor())); chatMessageManager.update(messageNode); client.refreshChat(); // all actions except woodcutting are interrupted from damage if (currentActivity != WintertodtActivity.WOODCUTTING) { wasInterrupted = true; } break; case INVENTORY_FULL: case OUT_OF_ROOTS: case BRAZIER_WENT_OUT: wasInterrupted = true; break; case LIT_BRAZIER: case FIXED_BRAZIER: wasInterrupted = true; neverNotify = true; break; } if (!neverNotify) { boolean shouldNotify = false; switch (config.notifyCondition()) { case ONLY_WHEN_INTERRUPTED: if (wasInterrupted) { shouldNotify = true; } break; case WHEN_DAMAGED: if (wasDamaged) { shouldNotify = true; } break; case EITHER: shouldNotify = true; break; } if (shouldNotify) { notifyInterrupted(interruptType, wasInterrupted); } } if (wasInterrupted) { currentActivity = WintertodtActivity.IDLE; } } private void notifyInterrupted(WintertodtInterruptType interruptType, boolean wasActivityInterrupted) { final StringBuilder str = new StringBuilder(); str.append("Wintertodt: "); if (wasActivityInterrupted) { str.append(currentActivity.getActionString()); str.append(" interrupted! "); } str.append(interruptType.getInterruptSourceString()); String notification = str.toString(); log.debug("Sending notification: {}", notification); notifier.notify(notification); } @Subscribe public void onAnimationChanged(final AnimationChanged event) { if (!isInWintertodt) { return; } final Player local = client.getLocalPlayer(); if (event.getActor() != local) { return; } final int animId = local.getAnimation(); switch (animId) { case WOODCUTTING_BRONZE: case WOODCUTTING_IRON: case WOODCUTTING_STEEL: case WOODCUTTING_BLACK: case WOODCUTTING_MITHRIL: case WOODCUTTING_ADAMANT: case WOODCUTTING_RUNE: case WOODCUTTING_DRAGON: case WOODCUTTING_INFERNAL: case WOODCUTTING_3A_AXE: setActivity(WintertodtActivity.WOODCUTTING); break; case FLETCHING_BOW_CUTTING: setActivity(WintertodtActivity.FLETCHING); break; case LOOKING_INTO: setActivity(WintertodtActivity.FEEDING_BRAZIER); break; case FIREMAKING: setActivity(WintertodtActivity.LIGHTING_BRAZIER); break; case CONSTRUCTION: setActivity(WintertodtActivity.FIXING_BRAZIER); break; } } @Subscribe public void onItemContainerChanged(ItemContainerChanged event) { final ItemContainer container = event.getItemContainer(); if (!isInWintertodt || container != client.getItemContainer(InventoryID.INVENTORY)) { return; } final Item[] inv = container.getItems(); inventoryScore = 0; totalPotentialinventoryScore = 0; numLogs = 0; numKindling = 0; for (Item item : inv) { inventoryScore += getPoints(item.getId()); totalPotentialinventoryScore += getPotentialPoints(item.getId()); switch (item.getId()) { case BRUMA_ROOT: ++numLogs; break; case BRUMA_KINDLING: ++numKindling; break; } } //If we're currently fletching but there are no more logs, go ahead and abort fletching immediately if (numLogs == 0 && currentActivity == WintertodtActivity.FLETCHING) { currentActivity = WintertodtActivity.IDLE; } //Otherwise, if we're currently feeding the brazier but we've run out of both logs and kindling, abort the feeding activity else if (numLogs == 0 && numKindling == 0 && currentActivity == WintertodtActivity.FEEDING_BRAZIER) { currentActivity = WintertodtActivity.IDLE; } } private void setActivity(WintertodtActivity action) { currentActivity = action; lastActionTime = Instant.now(); } private static int getPoints(int id) { switch (id) { case BRUMA_ROOT: return 10; case BRUMA_KINDLING: return 25; default: return 0; } } private static int getPotentialPoints(int id) { switch (id) { case BRUMA_ROOT: case BRUMA_KINDLING: return 25; default: return 0; } } }
package org.ow2.proactive.scheduler; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; /** * This class controls all aspects of the application's execution */ public class Application implements IApplication { public Object start(IApplicationContext context) throws Exception { final Display display = PlatformUI.createDisplay(); try { final int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) { return IApplication.EXIT_RESTART; } return IApplication.EXIT_OK; } finally { display.dispose(); } } public void stop() { try { final IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench == null) return; final Display display = workbench.getDisplay(); display.syncExec(new Runnable() { public void run() { if (!display.isDisposed()) workbench.close(); } }); } catch (org.eclipse.swt.SWTException e) { // nothing to do, wb was already disposed } } }
package org.jboss.security.client; import java.security.AccessController; import java.security.Principal; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import org.jboss.security.SecurityContext; import org.jboss.security.SecurityContextAssociation; import org.jboss.security.SecurityContextFactory; import org.jboss.security.SimplePrincipal; /** * Implementation of the SecurityClient contract <br/> * * <b> Usage:<b> * <pre> * SecurityClient sc = SecurityClientFactory.getSecurityClient(JBossSecurityClient.class) * sc.setUserName(somestring); * etc... * sc.login(); * </pre> * @author Anil.Saldhana@redhat.com * @since May 1, 2007 * @version $Revision$ */ public class JBossSecurityClient extends SecurityClient { protected LoginContext lc = null; private SecurityContext previousSecurityContext = null; @Override protected void peformSASLLogin() { throw new UnsupportedOperationException(); } @Override protected void performJAASLogin() throws LoginException { lc = new LoginContext(this.loginConfigName, this.callbackHandler); lc.login(); } @Override protected void performSimpleLogin() { Principal up = null; if(userPrincipal instanceof String) up = new SimplePrincipal((String)userPrincipal); else up = (Principal) userPrincipal; SecurityManager sm = System.getSecurityManager(); if (sm != null) { previousSecurityContext = RuntimeActions.PRIVILEGED.getSecurityContext(); } else { previousSecurityContext = RuntimeActions.NON_PRIVILEGED.getSecurityContext(); } SecurityContext sc = null; try { if (sm != null) { sc = RuntimeActions.PRIVILEGED.createClientSecurityContext(); } else { sc = RuntimeActions.NON_PRIVILEGED.createClientSecurityContext(); } } catch (Exception e) { throw new RuntimeException(e); } if (sm != null) { RuntimeActions.PRIVILEGED.createSubjectInfo(sc, up, credential, null); RuntimeActions.PRIVILEGED.setSecurityContext(sc); } else { RuntimeActions.NON_PRIVILEGED.createSubjectInfo(sc, up, credential, null); RuntimeActions.NON_PRIVILEGED.setSecurityContext(sc); } } @Override protected void cleanUp() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { RuntimeActions.PRIVILEGED.setSecurityContext(previousSecurityContext); } else { RuntimeActions.NON_PRIVILEGED.setSecurityContext(previousSecurityContext); } if(lc != null) try { lc.logout(); } catch (LoginException e) { throw new RuntimeException(e); } } interface RuntimeActions { SecurityContext getSecurityContext(); SecurityContext createClientSecurityContext() throws Exception; void setSecurityContext(SecurityContext securityContext); void createSubjectInfo(SecurityContext securityContext, Principal principal, Object credential, Subject subject); RuntimeActions NON_PRIVILEGED = new RuntimeActions() { @Override public SecurityContext getSecurityContext() { return SecurityContextAssociation.getSecurityContext(); } @Override public SecurityContext createClientSecurityContext() throws Exception { return SecurityContextFactory.createSecurityContext("CLIENT"); } @Override public void setSecurityContext(SecurityContext securityContext) { SecurityContextAssociation.setSecurityContext(securityContext); } @Override public void createSubjectInfo(SecurityContext securityContext, Principal principal, Object credential, Subject subject) { securityContext.getUtil().createSubjectInfo(principal, credential, subject); } }; RuntimeActions PRIVILEGED = new RuntimeActions() { @Override public SecurityContext getSecurityContext() { return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>() { @Override public SecurityContext run() { return NON_PRIVILEGED.getSecurityContext(); } }); } @Override public SecurityContext createClientSecurityContext() throws Exception { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<SecurityContext>() { @Override public SecurityContext run() throws Exception { return NON_PRIVILEGED.createClientSecurityContext(); } }); } catch (PrivilegedActionException pae) { throw pae.getException(); } } @Override public void setSecurityContext(final SecurityContext securityContext) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { NON_PRIVILEGED.setSecurityContext(securityContext); return null; } }); } @Override public void createSubjectInfo(final SecurityContext securityContext, final Principal principal, final Object credential, final Subject subject) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { NON_PRIVILEGED.createSubjectInfo(securityContext, principal, credential, subject); return null; } }); } }; } }
package org.eclipse.hono.service.auth; import java.time.Duration; import java.time.Instant; import java.util.Objects; import org.eclipse.hono.auth.Authorities; import org.eclipse.hono.auth.AuthoritiesImpl; import org.eclipse.hono.auth.HonoUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.JwtException; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.eventbus.DeliveryOptions; import io.vertx.core.json.JsonObject; import io.vertx.proton.sasl.ProtonSaslAuthenticator; import io.vertx.proton.sasl.ProtonSaslAuthenticatorFactory; /** * A factory for objects performing SASL authentication on an AMQP connection. */ @Component public final class HonoSaslAuthenticatorFactory implements ProtonSaslAuthenticatorFactory { private final AuthenticationService authenticationService; private final Vertx vertx; /** * Creates a new factory for a Vertx environment. * <p> * Verifies credentials by means of sending authentication requests to address * {@link AuthenticationConstants#EVENT_BUS_ADDRESS_AUTHENTICATION_IN} on the Vert.x * Event Bus. * * @param vertx the Vertx environment to run the factory in. * @param validator The object to use for validating auth tokens. * @throws NullPointerException if any of the parameters is {@code null}. */ @Autowired public HonoSaslAuthenticatorFactory(final Vertx vertx, @Qualifier(AuthenticationConstants.QUALIFIER_AUTHENTICATION) final AuthTokenHelper validator) { this(vertx, new EventBusAuthenticationService(vertx, validator)); } /** * Creates a new factory using a specific authentication service instance. * * @param vertx the Vertx environment to run the factory in. * @param authService The object to return on invocations of {@link #create()}. * @throws NullPointerException if any of the parameters is {@code null}. */ public HonoSaslAuthenticatorFactory(final Vertx vertx, final AuthenticationService authService) { this.vertx = Objects.requireNonNull(vertx); this.authenticationService = Objects.requireNonNull(authService); } @Override public ProtonSaslAuthenticator create() { return new HonoSaslAuthenticator(vertx, authenticationService); } /** * An authentication service that verifies credentials by means of sending authentication * requests to address {@link AuthenticationConstants#EVENT_BUS_ADDRESS_AUTHENTICATION_IN} * on the Vert.x Event Bus. * */ public static final class EventBusAuthenticationService implements AuthenticationService { private static final int AUTH_REQUEST_TIMEOUT_MILLIS = 3000; private final Logger log = LoggerFactory.getLogger(EventBusAuthenticationService.class); private final Vertx vertx; private final AuthTokenHelper tokenValidator; /** * Creates a new auth service for a Vertx environment. * <p> * * * @param vertx the Vertx environment to run the factory in. * @param validator The object to use for validating auth tokens. * @throws NullPointerException if any of the parameters is {@code null}. */ public EventBusAuthenticationService(final Vertx vertx, final AuthTokenHelper validator) { this.vertx = Objects.requireNonNull(vertx); this.tokenValidator = Objects.requireNonNull(validator); } @Override public void authenticate(final JsonObject authRequest, final Handler<AsyncResult<HonoUser>> authenticationResultHandler) { final DeliveryOptions options = new DeliveryOptions().setSendTimeout(AUTH_REQUEST_TIMEOUT_MILLIS); vertx.eventBus().send(AuthenticationConstants.EVENT_BUS_ADDRESS_AUTHENTICATION_IN, authRequest, options, reply -> { if (reply.succeeded()) { JsonObject result = (JsonObject) reply.result().body(); String token = result.getString(AuthenticationConstants.FIELD_TOKEN); log.debug("received token [length: {}] in response to authentication request", token.length()); try { Jws<Claims> expandedToken = tokenValidator.expand(result.getString(AuthenticationConstants.FIELD_TOKEN)); authenticationResultHandler.handle(Future.succeededFuture(new HonoUserImpl(expandedToken, token))); } catch (JwtException e) { authenticationResultHandler.handle(Future.failedFuture(e)); } } else { authenticationResultHandler.handle(Future.failedFuture(reply.cause())); } }); } } /** * A Hono user wrapping a JSON Web Token. * */ public static final class HonoUserImpl implements HonoUser { private static Duration expirationLeeway = Duration.ofMinutes(2); private String token; private Jws<Claims> expandedToken; private Authorities authorities; private HonoUserImpl(final Jws<Claims> expandedToken, final String token) { Objects.requireNonNull(expandedToken); Objects.requireNonNull(token); if (expandedToken.getBody() == null) { throw new IllegalArgumentException("token has no claims"); } this.token = token; this.expandedToken = expandedToken; this.authorities = AuthoritiesImpl.from(expandedToken.getBody()); } @Override public String getName() { return expandedToken.getBody().getSubject(); } @Override public Authorities getAuthorities() { return authorities; } @Override public String getToken() { return token; } @Override public boolean isExpired() { // we add some leeway to the token's expiration time to account for system clocks not being // perfectly in sync return !Instant.now().isBefore(expandedToken.getBody().getExpiration().toInstant().plus(expirationLeeway)); } } }
package weave.servlets; import static weave.config.WeaveConfig.getConnectionConfig; import static weave.config.WeaveConfig.getDataConfig; import static weave.config.WeaveConfig.initWeaveConfig; import java.rmi.RemoteException; import java.security.InvalidParameterException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpSession; import org.postgis.Geometry; import org.postgis.PGgeometry; import org.postgis.Point; import weave.beans.AttributeColumnData; import weave.beans.GeometryStreamMetadata; import weave.beans.PGGeom; import weave.beans.TableData; import weave.beans.WeaveJsonDataSet; import weave.beans.WeaveRecordList; import weave.config.ConnectionConfig; import weave.config.ConnectionConfig.ConnectionInfo; import weave.config.ConnectionConfig.WeaveAuthenticationException; import weave.config.DataConfig; import weave.config.DataConfig.DataEntity; import weave.config.DataConfig.DataEntityMetadata; import weave.config.DataConfig.DataEntityWithRelationships; import weave.config.DataConfig.DataType; import weave.config.DataConfig.EntityHierarchyInfo; import weave.config.DataConfig.EntityType; import weave.config.DataConfig.PrivateMetadata; import weave.config.DataConfig.PublicMetadata; import weave.config.WeaveConfig; import weave.config.WeaveContextParams; import weave.geometrystream.SQLGeometryStreamReader; import weave.utils.CSVParser; import weave.utils.ListUtils; import weave.utils.MapUtils; import weave.utils.Numbers; import weave.utils.SQLResult; import weave.utils.SQLUtils; import weave.utils.SQLUtils.WhereClause; import weave.utils.SQLUtils.WhereClause.ColumnFilter; import weave.utils.SQLUtils.WhereClause.NestedColumnFilters; import weave.utils.Strings; /** * This class connects to a database and gets data * uses xml configuration file to get connection/query info * * @author Andy Dufilie */ public class DataService extends WeaveServlet implements IWeaveEntityService { private static final long serialVersionUID = 1L; public static final int MAX_COLUMN_REQUEST_COUNT = 100; public DataService() { //hack_memoizeEverything = new HashMap<String, Object>(); } public void init(ServletConfig config) throws ServletException { super.init(config); initWeaveConfig(WeaveContextParams.getInstance(config.getServletContext())); } public void destroy() { SQLUtils.staticCleanup(); } // Authentication private static final String SESSION_USERNAME = "DataService.user"; private static final String SESSION_PASSWORD = "DataService.pass"; /** * @param user * @param password * @return true if the user has superuser privileges. * @throws RemoteException If authentication fails. */ public void authenticate(String username, String password) throws RemoteException { ConnectionConfig connConfig = getConnectionConfig(); ConnectionInfo info = connConfig.getConnectionInfo(ConnectionInfo.DIRECTORY_SERVICE, username, password); if (info == null) throw new RemoteException("Incorrect username or password"); HttpSession session = getServletRequestInfo().request.getSession(true); session.setAttribute(SESSION_USERNAME, username); session.setAttribute(SESSION_PASSWORD, password); } /** * Gets static, read-only connection from a ConnectionInfo object using pass-through authentication if necessary. * @param connInfo * @return * @throws RemoteException */ private Connection getStaticReadOnlyConnection(ConnectionInfo connInfo) throws RemoteException { if (connInfo.requiresAuthentication()) { HttpSession session = getServletRequestInfo().request.getSession(true); String user = (String)session.getAttribute(SESSION_USERNAME); String pass = (String)session.getAttribute(SESSION_PASSWORD); connInfo = getConnectionConfig().getConnectionInfo(connInfo.name, user, pass); if (connInfo == null) throw new WeaveAuthenticationException("Incorrect username or password"); } return connInfo.getStaticReadOnlyConnection(); } // helper functions private DataEntity getColumnEntity(int columnId) throws RemoteException { DataEntity entity = getDataConfig().getEntity(columnId); if (entity == null) throw new RemoteException("No column with id " + columnId); String entityType = entity.publicMetadata.get(PublicMetadata.ENTITYTYPE); if (!Strings.equal(entityType, EntityType.COLUMN)) throw new RemoteException(String.format("Entity with id=%s is not a column (entityType: %s)", columnId, entityType)); return entity; } private void assertColumnHasPrivateMetadata(DataEntity columnEntity, String ... fields) throws RemoteException { for (String field : fields) { if (Strings.isEmpty(columnEntity.privateMetadata.get(field))) { String dataType = columnEntity.publicMetadata.get(PublicMetadata.DATATYPE); String description = (dataType != null && dataType.equals(DataType.GEOMETRY)) ? "Geometry column" : "Column"; throw new RemoteException(String.format("%s %s is missing private metadata %s", description, columnEntity.id, field)); } } } private boolean assertStreamingGeometryColumn(DataEntity entity, boolean throwException) throws RemoteException { try { String dataType = entity.publicMetadata.get(PublicMetadata.DATATYPE); if (dataType == null || !dataType.equals(DataType.GEOMETRY)) throw new RemoteException(String.format("Column %s dataType is %s, not %s", entity.id, dataType, DataType.GEOMETRY)); assertColumnHasPrivateMetadata(entity, PrivateMetadata.CONNECTION, PrivateMetadata.SQLSCHEMA, PrivateMetadata.SQLTABLEPREFIX); return true; } catch (RemoteException e) { if (throwException) throw e; return false; } } // Server info public Map<String,Object> getServerInfo() throws RemoteException { ConnectionConfig connConfig = getConnectionConfig(); HttpSession session = getServletRequestInfo().request.getSession(true); String username = (String)session.getAttribute(SESSION_USERNAME); return MapUtils.fromPairs( "version", WeaveConfig.getVersion(), "authenticatedUser", username, "hasDirectoryService", connConfig.getConnectionInfo(ConnectionInfo.DIRECTORY_SERVICE) != null, "idFields", connConfig.getDatabaseConfigInfo().idFields ); } // DataEntity info public EntityHierarchyInfo[] getHierarchyInfo(Map<String,String> publicMetadata) throws RemoteException { return getDataConfig().getEntityHierarchyInfo(publicMetadata); } public DataEntityWithRelationships[] getEntities(int[] ids) throws RemoteException { if (ids.length > DataConfig.MAX_ENTITY_REQUEST_COUNT) throw new RemoteException(String.format("You cannot request more than %s entities at a time.", DataConfig.MAX_ENTITY_REQUEST_COUNT)); // prevent user from receiving private metadata return getDataConfig().getEntitiesWithRelationships(ids, false); } public int[] findEntityIds(Map<String,String> publicMetadata, String[] wildcardFields) throws RemoteException { int[] ids = ListUtils.toIntArray( getDataConfig().searchPublicMetadata(publicMetadata, wildcardFields) ); Arrays.sort(ids); return ids; } public String[] findPublicFieldValues(String fieldName, String valueSearch) throws RemoteException { throw new RemoteException("Not implemented yet"); } // Columns private static ConnectionInfo getColumnConnectionInfo(DataEntity entity) throws RemoteException { String connName = entity.privateMetadata.get(PrivateMetadata.CONNECTION); ConnectionConfig connConfig = getConnectionConfig(); ConnectionInfo connInfo = connConfig.getConnectionInfo(connName); if (connInfo == null) { String title = entity.publicMetadata.get(PublicMetadata.TITLE); throw new RemoteException(String.format("Connection named '%s' associated with column #%s (%s) no longer exists", connName, entity.id, title)); } return connInfo; } private static class FakeDataProperties { public int[] dim = new int[]{5}; public boolean sequence = false; public double mean = 0; public double stddev = 1; public int digits = 2; public boolean realKeys = false; public int repeat = 1; public boolean repeatKeys = false; public int sort = 0; public int getNumRows() { int numRows = repeat; for (int i = 0; i < dim.length; i++) numRows *= dim[i]; return numRows; } public List<String> generateStrings(String prefix, boolean forKeys) { int numRows = getNumRows(); List<String> strings = new ArrayList<String>(numRows); generateStrings(strings, 0, prefix, "", forKeys && !repeatKeys); return strings; } private void generateStrings(List<String> output, int depth, String prefix, String suffix, boolean noRepeat) { int n = dim[depth]; for (int i = 1; i <= n; i++) { String newSuffix = suffix + "_" + i; if (depth + 1 < dim.length) generateStrings(output, depth + 1, prefix, newSuffix, noRepeat); else for (int r = 0; r < repeat; r++) { if (noRepeat) output.add(prefix + newSuffix + "_" + r); else output.add(prefix + newSuffix); } } } public List<Double> generateDoubles(long seed) { int numRows = getNumRows(); List<Double> doubles = new ArrayList<Double>(numRows); Random rand = new Random(seed); Double value = mean; for (int i = 0; i < numRows; i++) { if (sequence) { value += stddev; } else { value = mean + stddev * rand.nextGaussian(); value = Numbers.roundSignificant(value, digits); } doubles.add(value); } if (sort != 0) Collections.sort(doubles); if (sort < 0) Collections.reverse(doubles); return doubles; } } /** * This retrieves the data and the public metadata for a single attribute column. * @param columnId Either an entity ID (int) or a Map specifying public metadata values that uniquely identify a column. * @param minParam Used for filtering numeric data * @param maxParam Used for filtering numeric data * @param sqlParams Specifies parameters to be used in place of '?' placeholders that appear in the SQL query for the column. * @return The column data. * @throws RemoteException */ @SuppressWarnings("unchecked") public AttributeColumnData getColumn(Object columnId, double minParam, double maxParam, Object[] sqlParams) throws RemoteException { DataEntity entity = null; if (columnId instanceof Map) { @SuppressWarnings("rawtypes") Map metadata = (Map)columnId; metadata.put(PublicMetadata.ENTITYTYPE, EntityType.COLUMN); int[] ids = findEntityIds(metadata, null); if (ids.length == 0) throw new RemoteException("No column with id " + columnId); if (ids.length > 1) throw new RemoteException(String.format( "The specified metadata does not uniquely identify a column (%s matching columns found): %s", ids.length, columnId )); entity = getColumnEntity(ids[0]); } else { columnId = cast(columnId, Integer.class); entity = getColumnEntity((Integer)columnId); } // if it's a geometry column, just return the metadata if (assertStreamingGeometryColumn(entity, false)) { GeometryStreamMetadata gsm = (GeometryStreamMetadata) getGeometryData(entity, GeomStreamComponent.TILE_DESCRIPTORS, null); AttributeColumnData result = new AttributeColumnData(); result.id = entity.id; result.metadata = entity.publicMetadata; result.metadataTileDescriptors = gsm.metadataTileDescriptors; result.geometryTileDescriptors = gsm.geometryTileDescriptors; return result; } String query = entity.privateMetadata.get(PrivateMetadata.SQLQUERY); String fakeData = entity.publicMetadata.get("fakeData"); String dataType = entity.publicMetadata.get(PublicMetadata.DATATYPE); int tableId = DataConfig.NULL; String tableField = null; boolean getRealKeys = true; boolean getRealData = true; // special case when sqlParams is an empty Array - don't query if (sqlParams != null && sqlParams.length == 0) { fakeData = "{dim:[0]}"; } else if (Strings.isEmpty(query) && Strings.isEmpty(fakeData)) { String entityType = entity.publicMetadata.get(PublicMetadata.ENTITYTYPE); tableField = entity.privateMetadata.get(PrivateMetadata.SQLCOLUMN); if (!Strings.equal(entityType, EntityType.COLUMN)) throw new RemoteException(String.format("Entity %s has no sqlQuery and is not a column (entityType=%s)", entity.id, entityType)); if (Strings.isEmpty(tableField)) throw new RemoteException(String.format("Entity %s has no sqlQuery and no sqlColumn private metadata", entity.id)); // if there's no query, the query lives in the table entity instead of the column entity DataConfig config = getDataConfig(); List<Integer> parentIds = config.getParentIds(entity.id); Map<Integer, String> idToType = config.getEntityTypes(parentIds); for (int id : parentIds) { if (Strings.equal(idToType.get(id), EntityType.TABLE)) { tableId = id; break; } } } List<String> keys = null; List<Double> numericData = null; List<String> stringData = null; List<Object> thirdColumn = null; // hack for dimension slider format List<PGGeom> geometricData = null; if (!Strings.isEmpty(fakeData)) { FakeDataProperties props; try { props = GSON.fromJson(fakeData, FakeDataProperties.class); } catch (Exception e) { throw new RemoteException(String.format("Unable to retrieve data for column %s (Invalid \"fakeData\" JSON)", columnId)); } getRealKeys = props.realKeys; getRealData = false; String title = entity.publicMetadata.get(PublicMetadata.TITLE); String keyType = entity.publicMetadata.get(PublicMetadata.KEYTYPE); String sqlParamsStr = "key"; if (sqlParams != null) sqlParamsStr = GSON.toJson(sqlParams); if (!getRealKeys) keys = props.generateStrings(sqlParamsStr, true); if (Strings.equal(dataType, DataType.NUMBER) || Strings.equal(dataType, DataType.DATE)) { int seed = title.hashCode() ^ keyType.hashCode() ^ sqlParamsStr.hashCode(); numericData = props.generateDoubles(seed); } else stringData = props.generateStrings(title, false); } if (!Strings.isEmpty(query) && (getRealKeys || getRealData)) { ConnectionInfo connInfo = getColumnConnectionInfo(entity); keys = new ArrayList<String>(); ////// begin MIN/MAX code // use config min,max or param min,max to filter the data double minValue = Double.NaN; double maxValue = Double.NaN; // server min,max values take priority over user-specified params if (entity.publicMetadata.containsKey(PublicMetadata.MIN)) { try { minValue = Double.parseDouble(entity.publicMetadata.get(PublicMetadata.MIN)); } catch (Exception e) { } } else { minValue = minParam; } if (entity.publicMetadata.containsKey(PublicMetadata.MAX)) { try { maxValue = Double.parseDouble(entity.publicMetadata.get(PublicMetadata.MAX)); } catch (Exception e) { } } else { maxValue = maxParam; } if (Double.isNaN(minValue)) minValue = Double.NEGATIVE_INFINITY; if (Double.isNaN(maxValue)) maxValue = Double.POSITIVE_INFINITY; ////// end MIN/MAX code try { Connection conn = getStaticReadOnlyConnection(connInfo); // use default sqlParams if not specified by query params if (sqlParams == null) { String sqlParamsString = entity.privateMetadata.get(PrivateMetadata.SQLPARAMS); try { sqlParams = (Object[])GSON.fromJson(sqlParamsString, Object[].class); } catch (Exception e) { sqlParams = CSVParser.defaultParser.parseCSVRow(sqlParamsString, true); } } SQLResult result = SQLUtils.getResultFromQuery(conn, query, sqlParams, false); // if dataType is defined in the config file, use that value. // otherwise, derive it from the sql result. if (Strings.isEmpty(dataType)) { dataType = DataType.fromSQLType(result.columnTypes[1]); entity.publicMetadata.put(PublicMetadata.DATATYPE, dataType); // fill in missing metadata for the client } if (!getRealData) { // do nothing } else if (dataType.equalsIgnoreCase(DataType.NUMBER)) // special case: "number" => Double { numericData = new LinkedList<Double>(); } else if (dataType.equalsIgnoreCase(DataType.GEOMETRY)) { geometricData = new LinkedList<PGGeom>(); } else { stringData = new LinkedList<String>(); } // hack for dimension slider format if (getRealData && result.columnTypes.length == 3) thirdColumn = new LinkedList<Object>(); Object keyObj, dataObj; double value; for (int i = 0; i < result.rows.length; i++) { keyObj = result.rows[i][0]; if (keyObj == null) continue; dataObj = result.rows[i][1]; if (dataObj == null) continue; if (numericData != null) { try { if (dataObj instanceof String) dataObj = Double.parseDouble((String)dataObj); value = ((Number)dataObj).doubleValue(); } catch (Exception e) { continue; } // filter the data based on the min,max values if (minValue <= value && value <= maxValue) numericData.add(value); else continue; } else if (geometricData != null) { // The dataObj must be cast to PGgeometry before an individual Geometry can be extracted. if (!(dataObj instanceof PGgeometry)) continue; Geometry geom = ((PGgeometry) dataObj).getGeometry(); int numPoints = geom.numPoints(); // Create PGGeom Bean here and fill it up! PGGeom bean = new PGGeom(); bean.type = geom.getType(); bean.xyCoords = new double[numPoints * 2]; for (int j = 0; j < numPoints; j++) { Point pt = geom.getPoint(j); bean.xyCoords[j * 2] = pt.x; bean.xyCoords[j * 2 + 1] = pt.y; } geometricData.add(bean); } else if (stringData != null) { stringData.add(dataObj.toString()); } // if we got here, it means a data value was added, so add the corresponding key keys.add(keyObj.toString()); // hack for dimension slider format if (thirdColumn != null) thirdColumn.add(result.rows[i][2]); } } catch (SQLException e) { System.err.println(query); e.printStackTrace(); throw new RemoteException(String.format("Unable to retrieve data for column %s", columnId)); } catch (NullPointerException e) { e.printStackTrace(); throw new RemoteException("Unexpected error", e); } } AttributeColumnData result = new AttributeColumnData(); result.id = entity.id; result.tableId = tableId; result.tableField = tableField; result.metadata = entity.publicMetadata; if (keys != null) result.keys = keys.toArray(new String[keys.size()]); if (numericData != null) result.data = numericData.toArray(); else if (geometricData != null) result.data = geometricData.toArray(); else if (stringData != null) result.data = stringData.toArray(); // hack for dimension slider if (thirdColumn != null) result.thirdColumn = thirdColumn.toArray(); // truncate fake data or keys if necessary if ((!getRealData || !getRealKeys) && result.keys != null && result.data != null && result.keys.length != result.data.length) { int minLength = Math.min(result.keys.length, result.data.length); result.keys = Arrays.copyOf(result.keys, minLength); result.data = Arrays.copyOf(result.data, minLength); } return result; } public TableData getTable(int id, Object[] sqlParams) throws RemoteException { DataEntity entity = getDataConfig().getEntity(id); ConnectionInfo connInfo = getColumnConnectionInfo(entity); String query = entity.privateMetadata.get(PrivateMetadata.SQLQUERY); Map<String, Object[]> data = new HashMap<String, Object[]>(); try { Connection conn = getStaticReadOnlyConnection(connInfo); // use default sqlParams if not specified by query params if (sqlParams == null || sqlParams.length == 0) { String sqlParamsString = entity.privateMetadata.get(PrivateMetadata.SQLPARAMS); sqlParams = CSVParser.defaultParser.parseCSVRow(sqlParamsString, true); } SQLResult result = SQLUtils.getResultFromQuery(conn, query, sqlParams, false); // transpose int iColCount = result.columnNames.length; int iRowCount = result.rows.length; for (int iCol = 0; iCol < iColCount; iCol++) { Object[] column = new Object[result.rows.length]; for (int iRow = 0; iRow < iRowCount; iRow++) column[iRow] = result.rows[iRow][iCol]; data.put(result.columnNames[iCol], column); } } catch (SQLException e) { System.err.println(query); e.printStackTrace(); throw new RemoteException(String.format("Unable to retrieve data for table %s", id)); } catch (NullPointerException e) { e.printStackTrace(); throw new RemoteException("Unexpected error", e); } TableData result = new TableData(); result.id = id; result.keyColumns = CSVParser.defaultParser.parseCSVRow(entity.privateMetadata.get(PrivateMetadata.SQLKEYCOLUMN), true); result.columns = data; return result; } /** * This function is intended for use with JsonRPC calls. * @param columnIds A list of column IDs. * @return A WeaveJsonDataSet containing all the data from the columns. * @throws RemoteException */ public WeaveJsonDataSet getDataSet(int[] columnIds) throws RemoteException { if (columnIds == null) columnIds = new int[0]; if (columnIds.length > MAX_COLUMN_REQUEST_COUNT) throw new RemoteException(String.format("You cannot request more than %s columns at a time.", MAX_COLUMN_REQUEST_COUNT)); WeaveJsonDataSet result = new WeaveJsonDataSet(); for (Integer columnId : columnIds) { try { AttributeColumnData columnData = getColumn(columnId, Double.NaN, Double.NaN, null); result.addColumnData(columnData); } catch (RemoteException e) { e.printStackTrace(); } } return result; } // geometry columns public byte[] getGeometryStreamMetadataTiles(int columnId, int[] tileIDs) throws RemoteException { DataEntity entity = getColumnEntity(columnId); if (tileIDs == null || tileIDs.length == 0) throw new RemoteException("At least one tileID must be specified."); return (byte[]) getGeometryData(entity, GeomStreamComponent.METADATA_TILES, tileIDs); } public byte[] getGeometryStreamGeometryTiles(int columnId, int[] tileIDs) throws RemoteException { DataEntity entity = getColumnEntity(columnId); if (tileIDs == null || tileIDs.length == 0) throw new RemoteException("At least one tileID must be specified."); return (byte[]) getGeometryData(entity, GeomStreamComponent.GEOMETRY_TILES, tileIDs); } private static enum GeomStreamComponent { TILE_DESCRIPTORS, METADATA_TILES, GEOMETRY_TILES }; private Object getGeometryData(DataEntity entity, GeomStreamComponent component, int[] tileIDs) throws RemoteException { assertStreamingGeometryColumn(entity, true); Connection conn = getStaticReadOnlyConnection(getColumnConnectionInfo(entity)); String schema = entity.privateMetadata.get(PrivateMetadata.SQLSCHEMA); String tablePrefix = entity.privateMetadata.get(PrivateMetadata.SQLTABLEPREFIX); try { switch (component) { case TILE_DESCRIPTORS: GeometryStreamMetadata result = new GeometryStreamMetadata(); result.metadataTileDescriptors = SQLGeometryStreamReader.getMetadataTileDescriptors(conn, schema, tablePrefix); result.geometryTileDescriptors = SQLGeometryStreamReader.getGeometryTileDescriptors(conn, schema, tablePrefix); return result; case METADATA_TILES: return SQLGeometryStreamReader.getMetadataTiles(conn, schema, tablePrefix, tileIDs); case GEOMETRY_TILES: return SQLGeometryStreamReader.getGeometryTiles(conn, schema, tablePrefix, tileIDs); default: throw new InvalidParameterException("Invalid GeometryStreamComponent param."); } } catch (Exception e) { e.printStackTrace(); throw new RemoteException(String.format("Unable to read geometry data (id=%s)", entity.id)); } } // Row query public WeaveRecordList getRows(String keyType, String[] keysArray) throws RemoteException { DataConfig dataConfig = getDataConfig(); DataEntityMetadata params = new DataEntityMetadata(); params.setPublicValues( PublicMetadata.ENTITYTYPE, EntityType.COLUMN, PublicMetadata.KEYTYPE, keyType ); List<Integer> columnIds = new ArrayList<Integer>( dataConfig.searchPublicMetadata(params.publicMetadata, null) ); if (columnIds.size() > MAX_COLUMN_REQUEST_COUNT) columnIds = columnIds.subList(0, MAX_COLUMN_REQUEST_COUNT); return DataService.getFilteredRows(ListUtils.toIntArray(columnIds), null, keysArray); } /** * Gets all column IDs referenced by this object and its nested objects. */ private static Collection<Integer> getReferencedColumnIds(NestedColumnFilters filters) { Set<Integer> ids = new HashSet<Integer>(); if (filters.cond != null) ids.add(((Number)filters.cond.f).intValue()); else for (NestedColumnFilters nested : (filters.and != null ? filters.and : filters.or)) ids.addAll(getReferencedColumnIds(nested)); return ids; } /** * Converts nested ColumnFilter.f values from a column ID to the corresponding SQL field name. * @param filters * @param entities * @return A copy of filters with field names in place of the column IDs. * @see ColumnFilter#f */ private static NestedColumnFilters convertColumnIdsToFieldNames(NestedColumnFilters filters, Map<Integer, DataEntity> entities) { if (filters == null) return null; NestedColumnFilters result = new NestedColumnFilters(); if (filters.cond != null) { result.cond = new ColumnFilter(); result.cond.v = filters.cond.v; result.cond.r = filters.cond.r; result.cond.f = entities.get(((Number)filters.cond.f).intValue()).privateMetadata.get(PrivateMetadata.SQLCOLUMN); } else { NestedColumnFilters[] in = (filters.and != null ? filters.and : filters.or); NestedColumnFilters[] out = new NestedColumnFilters[in.length]; for (int i = 0; i < in.length; i++) out[i] = convertColumnIdsToFieldNames(in[i], entities); if (filters.and == in) result.and = out; else result.or = out; } return result; } private static SQLResult getFilteredRowsFromSQL(Connection conn, String schema, String table, int[] columns, NestedColumnFilters filters, Map<Integer,DataEntity> entities) throws SQLException { String[] quotedFields = new String[columns.length]; for (int i = 0; i < columns.length; i++) quotedFields[i] = SQLUtils.quoteSymbol(conn, entities.get(columns[i]).privateMetadata.get(PrivateMetadata.SQLCOLUMN)); WhereClause<Object> where = WhereClause.fromFilters(conn, convertColumnIdsToFieldNames(filters, entities)); String query = String.format( "SELECT %s FROM %s %s", Strings.join(",", quotedFields), SQLUtils.quoteSchemaTable(conn, schema, table), where.clause ); return SQLUtils.getResultFromQuery(conn, query, where.params.toArray(), false); } @SuppressWarnings("unchecked") public static WeaveRecordList getFilteredRows(int[] columns, NestedColumnFilters filters, String[] keysArray) throws RemoteException { if (columns == null || columns.length == 0) throw new RemoteException("At least one column must be specified."); if (filters != null) filters.assertValid(); DataConfig dataConfig = getDataConfig(); WeaveRecordList result = new WeaveRecordList(); Map<Integer, DataEntity> entityLookup = new HashMap<Integer, DataEntity>(); { // get all column IDs whether or not they are to be selected. Set<Integer> allColumnIds = new HashSet<Integer>(); if (filters != null) allColumnIds.addAll(getReferencedColumnIds(filters)); for (int id : columns) allColumnIds.add(id); // get all corresponding entities for (DataEntity entity : dataConfig.getEntities(allColumnIds, true)) entityLookup.put(entity.id, entity); // check for missing columns for (int id : allColumnIds) if (entityLookup.get(id) == null) throw new RemoteException("No column with ID=" + id); // provide public metadata in the same order as the selected columns result.attributeColumnMetadata = new Map[columns.length]; for (int i = 0; i < columns.length; i++) result.attributeColumnMetadata[i] = entityLookup.get(columns[i]).publicMetadata; } String keyType = result.attributeColumnMetadata[0].get(PublicMetadata.KEYTYPE); // make sure all columns have same keyType for (int i = 1; i < columns.length; i++) if (!Strings.equal(keyType, result.attributeColumnMetadata[i].get(PublicMetadata.KEYTYPE))) throw new RemoteException("Specified columns must all have same keyType."); if (keysArray == null) { boolean canGenerateSQL = true; // check to see if all the columns are from the same SQL table. String connection = null; String sqlSchema = null; String sqlTable = null; for (DataEntity entity : entityLookup.values()) { String c = entity.privateMetadata.get(PrivateMetadata.CONNECTION); String s = entity.privateMetadata.get(PrivateMetadata.SQLSCHEMA); String t = entity.privateMetadata.get(PrivateMetadata.SQLTABLE); if (connection == null) connection = c; if (sqlSchema == null) sqlSchema = s; if (sqlTable == null) sqlTable = t; if (!Strings.equal(connection, c) || !Strings.equal(sqlSchema, s) || !Strings.equal(sqlTable, t)) { canGenerateSQL = false; break; } } if (canGenerateSQL) { Connection conn = getColumnConnectionInfo(entityLookup.get(columns[0])).getStaticReadOnlyConnection(); try { result.recordData = getFilteredRowsFromSQL(conn, sqlSchema, sqlTable, columns, filters, entityLookup).rows; } catch (SQLException e) { throw new RemoteException("getFilteredRows() failed.", e); } } } if (result.recordData == null) { throw new Error("Selecting across tables is not supported yet."); /* HashMap<String,Object[]> data = new HashMap<String,Object[]>(); if (keysArray != null) for (String key : keysArray) data.put(key, new Object[entities.length]); for (int colIndex = 0; colIndex < entities.length; colIndex++) { Object[] filters = fcrs[colIndex].filters; DataEntity info = entities[colIndex]; String sqlQuery = info.privateMetadata.get(PrivateMetadata.SQLQUERY); String sqlParams = info.privateMetadata.get(PrivateMetadata.SQLPARAMS); //if (dataWithKeysQuery.length() == 0) // throw new RemoteException(String.format("No SQL query is associated with column \"%s\" in dataTable \"%s\"", attributeColumnName, dataTableName)); String dataType = info.publicMetadata.get(PublicMetadata.DATATYPE); // use config min,max or param min,max to filter the data String infoMinStr = info.publicMetadata.get(PublicMetadata.MIN); String infoMaxStr = info.publicMetadata.get(PublicMetadata.MAX); double minValue = Double.NEGATIVE_INFINITY; double maxValue = Double.POSITIVE_INFINITY; // first try parsing config min,max values try { minValue = Double.parseDouble(infoMinStr); } catch (Exception e) { } try { maxValue = Double.parseDouble(infoMaxStr); } catch (Exception e) { } // override config min,max with param values if given // * columnInfoArray = config.getDataEntity(params); // * for each info in columnInfoArray // * get sql data // * for each row in sql data // * if key is in keys array, // * add this value to the result // * return result try { //timer.start(); boolean errorReported = false; Connection conn = getColumnConnectionInfo(info).getStaticReadOnlyConnection(); String[] sqlParamsArray = null; if (sqlParams != null && sqlParams.length() > 0) sqlParamsArray = CSVParser.defaultParser.parseCSV(sqlParams, true)[0]; SQLResult sqlResult = SQLUtils.getResultFromQuery(conn, sqlQuery, sqlParamsArray, false); //timer.lap("get row set"); // if dataType is defined in the config file, use that value. // otherwise, derive it from the sql result. if (Strings.isEmpty(dataType)) dataType = DataType.fromSQLType(sqlResult.columnTypes[1]); boolean isNumeric = dataType != null && dataType.equalsIgnoreCase(DataType.NUMBER); Object keyObj, dataObj; for (int iRow = 0; iRow < sqlResult.rows.length; iRow++) { keyObj = sqlResult.rows[iRow][0]; dataObj = sqlResult.rows[iRow][1]; if (keyObj == null || dataObj == null) continue; keyObj = keyObj.toString(); if (data.containsKey(keyObj)) { // if row has been set to null, skip if (data.get(keyObj) == null) continue; } else { // if keys are specified and row is not present, skip if (keysArray != null) continue; } try { boolean passedFilters = true; // convert the data to the appropriate type, then filter by value if (isNumeric) { if (dataObj instanceof Number) // TEMPORARY SOLUTION - FIX ME { double doubleValue = ((Number)dataObj).doubleValue(); // filter the data based on the min,max values if (minValue <= doubleValue && doubleValue <= maxValue) { // filter the value if (filters != null) { passedFilters = false; for (Object range : filters) { Number min = (Number)((Object[])range)[0]; Number max = (Number)((Object[])range)[1]; if (min.doubleValue() <= doubleValue && doubleValue <= max.doubleValue()) { passedFilters = true; break; } } } } else passedFilters = false; } else passedFilters = false; } else { String stringValue = dataObj.toString(); dataObj = stringValue; // filter the value if (filters != null) { passedFilters = false; for (Object filter : filters) { if (filter.equals(stringValue)) { passedFilters = true; break; } } } } Object[] row = data.get(keyObj); if (passedFilters) { // add existing row if it has not been added yet if (!data.containsKey(keyObj)) { for (int i = 0; i < colIndex; i++) { Object[] prevFilters = fcrs[i].filters; if (prevFilters != null) { passedFilters = false; break; } } if (passedFilters) row = new Object[entities.length]; data.put((String)keyObj, row); } if (row != null) row[colIndex] = dataObj; } else { // remove existing row if value did not pass filters if (row != null || !data.containsKey(keyObj)) data.put((String)keyObj, null); } } catch (Exception e) { if (!errorReported) { errorReported = true; e.printStackTrace(); } } } } catch (SQLException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); throw new RemoteException(e.getMessage()); } } if (keysArray == null) { List<String> keys = new LinkedList<String>(); for (Entry<String,Object[]> entry : data.entrySet()) if (entry.getValue() != null) keys.add(entry.getKey()); keysArray = keys.toArray(new String[keys.size()]); } Object[][] rows = new Object[keysArray.length][]; for (int iKey = 0; iKey < keysArray.length; iKey++) rows[iKey] = data.get(keysArray[iKey]); result.recordData = rows; */ } result.keyType = keyType; result.recordKeys = keysArray; return result; } // backwards compatibility /** * Use getHierarchyInfo() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public EntityHierarchyInfo[] getDataTableList() throws RemoteException { return getDataConfig().getEntityHierarchyInfo(MapUtils.<String,String>fromPairs(PublicMetadata.ENTITYTYPE, EntityType.TABLE)); } /** * Use getEntities() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public int[] getEntityChildIds(int parentId) throws RemoteException { return ListUtils.toIntArray( getDataConfig().getChildIds(parentId) ); } /** * Use getEntities() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public int[] getParents(int childId) throws RemoteException { int[] ids = ListUtils.toIntArray( getDataConfig().getParentIds(childId) ); Arrays.sort(ids); return ids; } /** * Use findEntityIds() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public int[] getEntityIdsByMetadata(Map<String,String> publicMetadata, int entityType) throws RemoteException { publicMetadata.put(PublicMetadata.ENTITYTYPE, EntityType.fromInt(entityType)); return findEntityIds(publicMetadata, null); } /** * Use getEntities() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public DataEntity[] getEntitiesById(int[] ids) throws RemoteException { return getEntities(ids); } /** * @param metadata The metadata query. * @return The id of the matching column. * @throws RemoteException Thrown if the metadata query does not match exactly one column. */ @Deprecated public AttributeColumnData getColumnFromMetadata(Map<String, String> metadata) throws RemoteException { if (metadata == null || metadata.size() == 0) throw new RemoteException("No metadata query parameters specified."); metadata.put(PublicMetadata.ENTITYTYPE, EntityType.COLUMN); final String DATATABLE = "dataTable"; final String NAME = "name"; // exclude these parameters from the query if (metadata.containsKey(NAME)) metadata.remove(PublicMetadata.TITLE); String minStr = metadata.remove(PublicMetadata.MIN); String maxStr = metadata.remove(PublicMetadata.MAX); String paramsStr = metadata.remove(PrivateMetadata.SQLPARAMS); DataConfig dataConfig = getDataConfig(); Collection<Integer> ids = dataConfig.searchPublicMetadata(metadata, null); // attempt recovery for backwards compatibility if (ids.size() == 0) { if (metadata.containsKey(DATATABLE) && metadata.containsKey(NAME)) { // try to find columns sqlTable==dataTable and sqlColumn=name Map<String,String> privateMetadata = new HashMap<String,String>(); String sqlTable = metadata.get(DATATABLE); String sqlColumn = metadata.get(NAME); for (int i = 0; i < 2; i++) { if (i == 1) sqlTable = sqlTable.toLowerCase(); privateMetadata.put(PrivateMetadata.SQLTABLE, sqlTable); privateMetadata.put(PrivateMetadata.SQLCOLUMN, sqlColumn); ids = dataConfig.searchPrivateMetadata(privateMetadata, null); if (ids.size() > 0) break; } } else if (metadata.containsKey(NAME) && Strings.equal(metadata.get(PublicMetadata.DATATYPE), DataType.GEOMETRY)) { metadata.put(PublicMetadata.TITLE, metadata.remove(NAME)); ids = dataConfig.searchPublicMetadata(metadata, null); } if (ids.size() == 0) throw new RemoteException("No column matches metadata query: " + metadata); } // warning if more than one column if (ids.size() > 1) { String message = String.format( "WARNING: Multiple columns (%s) match metadata query: %s", ids.size(), metadata ); System.err.println(message); //throw new RemoteException(message); } // return first column int id = ListUtils.getFirstSortedItem(ids, DataConfig.NULL); double min = Double.NaN, max = Double.NaN; try { min = (Double)cast(minStr, double.class); } catch (Throwable t) { } try { max = (Double)cast(maxStr, double.class); } catch (Throwable t) { } String[] sqlParams = CSVParser.defaultParser.parseCSVRow(paramsStr, true); return getColumn(id, min, max, sqlParams); } }
package org.zstack.kvm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestClientException; import org.springframework.web.util.UriComponentsBuilder; import org.zstack.compute.host.HostBase; import org.zstack.compute.host.HostSystemTags; import org.zstack.compute.vm.VmSystemTags; import org.zstack.core.CoreGlobalProperty; import org.zstack.core.MessageCommandRecorder; import org.zstack.core.Platform; import org.zstack.core.ansible.AnsibleConstant; import org.zstack.core.ansible.AnsibleGlobalProperty; import org.zstack.core.ansible.AnsibleRunner; import org.zstack.core.ansible.SshFileMd5Checker; import org.zstack.core.db.SimpleQuery; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.core.logging.Log; import org.zstack.core.thread.ChainTask; import org.zstack.core.thread.SyncTaskChain; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.configuration.InstanceOfferingInventory; import org.zstack.header.core.AsyncLatch; import org.zstack.header.core.Completion; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.host.*; import org.zstack.header.host.MigrateVmOnHypervisorMsg.StorageMigrationPolicy; import org.zstack.header.image.ImagePlatform; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.header.message.NeedReplyMessage; import org.zstack.header.network.l2.*; import org.zstack.header.rest.JsonAsyncRESTCallback; import org.zstack.header.rest.RESTFacade; import org.zstack.header.storage.snapshot.VolumeSnapshotInventory; import org.zstack.header.vm.*; import org.zstack.header.volume.VolumeInventory; import org.zstack.header.volume.VolumeVO; import org.zstack.kvm.KVMAgentCommands.*; import org.zstack.kvm.KVMConstant.KvmVmState; import org.zstack.tag.TagManager; import org.zstack.utils.*; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import org.zstack.utils.path.PathUtil; import org.zstack.utils.ssh.Ssh; import org.zstack.utils.ssh.SshResult; import org.zstack.utils.ssh.SshShell; import javax.persistence.TypedQuery; import java.util.*; import java.util.concurrent.TimeUnit; import static org.zstack.utils.CollectionDSL.e; import static org.zstack.utils.CollectionDSL.map; public class KVMHost extends HostBase implements Host { private static final CLogger logger = Utils.getLogger(KVMHost.class); @Autowired private KVMHostFactory factory; @Autowired private RESTFacade restf; @Autowired private KVMExtensionEmitter extEmitter; @Autowired private ErrorFacade errf; @Autowired private TagManager tagmgr; private KVMHostContext context; // ///////////////////// REST URL ////////////////////////// private String baseUrl; private String connectPath; private String pingPath; private String checkPhysicalNetworkInterfacePath; private String startVmPath; private String stopVmPath; private String pauseVmPath; private String resumeVmPath; private String rebootVmPath; private String destroyVmPath; private String attachDataVolumePath; private String detachDataVolumePath; private String echoPath; private String attachNicPath; private String detachNicPath; private String migrateVmPath; private String snapshotPath; private String mergeSnapshotPath; private String hostFactPath; private String attachIsoPath; private String detachIsoPath; private String checkVmStatePath; private String getConsolePortPath; private String changeCpuMemoryPath; private String deleteConsoleFirewall; private String changeVmPasswordPath; private String setRootPasswordPath; private String agentPackageName = KVMGlobalProperty.AGENT_PACKAGE_NAME; KVMHost(KVMHostVO self, KVMHostContext context) { super(self); this.context = context; baseUrl = context.getBaseUrl(); UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_CONNECT_PATH); connectPath = ub.build().toUriString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_PING_PATH); pingPath = ub.build().toUriString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_CHECK_PHYSICAL_NETWORK_INTERFACE_PATH); checkPhysicalNetworkInterfacePath = ub.build().toUriString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_START_VM_PATH); startVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_STOP_VM_PATH); stopVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_PAUSE_VM_PATH); pauseVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_RESUME_VM_PATH); resumeVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_REBOOT_VM_PATH); rebootVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_DESTROY_VM_PATH); destroyVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_ATTACH_VOLUME); attachDataVolumePath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_DETACH_VOLUME); detachDataVolumePath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_ECHO_PATH); echoPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_ATTACH_NIC_PATH); attachNicPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_DETACH_NIC_PATH); detachNicPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_MIGRATE_VM_PATH); migrateVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_TAKE_VOLUME_SNAPSHOT_PATH); snapshotPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_MERGE_SNAPSHOT_PATH); mergeSnapshotPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_HOST_FACT_PATH); hostFactPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_ATTACH_ISO_PATH); attachIsoPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_DETACH_ISO_PATH); detachIsoPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_VM_CHECK_STATE); checkVmStatePath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_GET_VNC_PORT_PATH); getConsolePortPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_VM_CHANGE_CPUMEMORY); changeCpuMemoryPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_VM_CHANGE_PASSWORD_PATH); changeVmPasswordPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_VM_SET_ROOT_PASSWORD_PATH); setRootPasswordPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH); deleteConsoleFirewall = ub.build().toString(); } @Override protected void handleApiMessage(APIMessage msg) { super.handleApiMessage(msg); } @Override protected void handleLocalMessage(Message msg) { if (msg instanceof CheckNetworkPhysicalInterfaceMsg) { handle((CheckNetworkPhysicalInterfaceMsg) msg); } else if (msg instanceof StartVmOnHypervisorMsg) { handle((StartVmOnHypervisorMsg) msg); } else if (msg instanceof CreateVmOnHypervisorMsg) { handle((CreateVmOnHypervisorMsg) msg); } else if (msg instanceof StopVmOnHypervisorMsg) { handle((StopVmOnHypervisorMsg) msg); } else if (msg instanceof RebootVmOnHypervisorMsg) { handle((RebootVmOnHypervisorMsg) msg); } else if (msg instanceof DestroyVmOnHypervisorMsg) { handle((DestroyVmOnHypervisorMsg) msg); } else if (msg instanceof AttachVolumeToVmOnHypervisorMsg) { handle((AttachVolumeToVmOnHypervisorMsg) msg); } else if (msg instanceof DetachVolumeFromVmOnHypervisorMsg) { handle((DetachVolumeFromVmOnHypervisorMsg) msg); } else if (msg instanceof VmAttachNicOnHypervisorMsg) { handle((VmAttachNicOnHypervisorMsg) msg); } else if (msg instanceof MigrateVmOnHypervisorMsg) { handle((MigrateVmOnHypervisorMsg) msg); } else if (msg instanceof TakeSnapshotOnHypervisorMsg) { handle((TakeSnapshotOnHypervisorMsg) msg); } else if (msg instanceof MergeVolumeSnapshotOnKvmMsg) { handle((MergeVolumeSnapshotOnKvmMsg) msg); } else if (msg instanceof KVMHostAsyncHttpCallMsg) { handle((KVMHostAsyncHttpCallMsg) msg); } else if (msg instanceof KVMHostSyncHttpCallMsg) { handle((KVMHostSyncHttpCallMsg) msg); } else if (msg instanceof DetachNicFromVmOnHypervisorMsg) { handle((DetachNicFromVmOnHypervisorMsg) msg); } else if (msg instanceof AttachIsoOnHypervisorMsg) { handle((AttachIsoOnHypervisorMsg) msg); } else if (msg instanceof DetachIsoOnHypervisorMsg) { handle((DetachIsoOnHypervisorMsg) msg); } else if (msg instanceof CheckVmStateOnHypervisorMsg) { handle((CheckVmStateOnHypervisorMsg) msg); } else if (msg instanceof GetVmConsoleAddressFromHostMsg) { handle((GetVmConsoleAddressFromHostMsg) msg); } else if (msg instanceof KvmRunShellMsg) { handle((KvmRunShellMsg) msg); } else if (msg instanceof VmDirectlyDestroyOnHypervisorMsg) { handle((VmDirectlyDestroyOnHypervisorMsg) msg); } else if (msg instanceof OnlineChangeVmCpuMemoryMsg) { handle((OnlineChangeVmCpuMemoryMsg) msg); } else if (msg instanceof ChangeVmPasswordMsg) { handle((ChangeVmPasswordMsg) msg); } else if (msg instanceof PauseVmOnHypervisorMsg) { handle((PauseVmOnHypervisorMsg) msg); } else if (msg instanceof ResumeVmOnHypervisorMsg) { handle((ResumeVmOnHypervisorMsg) msg); } else { super.handleLocalMessage(msg); } } private void directlyDestroy(final VmDirectlyDestroyOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); final VmDirectlyDestroyOnHypervisorReply reply = new VmDirectlyDestroyOnHypervisorReply(); DestroyVmCmd cmd = new DestroyVmCmd(); cmd.setUuid(msg.getVmUuid()); restf.asyncJsonPost(destroyVmPath, cmd, new JsonAsyncRESTCallback<DestroyVmResponse>(msg, completion) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } @Override public void success(DestroyVmResponse ret) { if (!ret.isSuccess()) { reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public Class<DestroyVmResponse> getReturnClass() { return DestroyVmResponse.class; } }); } private void handle(final VmDirectlyDestroyOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { directlyDestroy(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("directly-delete-vm-%s-msg-on-kvm-%s", msg.getVmUuid(), self.getUuid()); } }); } private SshResult runShell(String script) { Ssh ssh = new Ssh(); ssh.setHostname(self.getManagementIp()); ssh.setPort(getSelf().getPort()); ssh.setUsername(getSelf().getUsername()); ssh.setPassword(getSelf().getPassword()); ssh.shell(script); return ssh.runAndClose(); } private void handle(KvmRunShellMsg msg) { SshResult result = runShell(msg.getScript()); KvmRunShellReply reply = new KvmRunShellReply(); if (result.isSshFailure()) { reply.setError(errf.stringToOperationError( String.format("unable to connect to KVM[ip:%s, username:%s, sshPort:%d ] to do DNS check," + " please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), result.getExitErrorMessage()) )); } else { reply.setStdout(result.getStdout()); reply.setStderr(result.getStderr()); reply.setReturnCode(result.getReturnCode()); } bus.reply(msg, reply); } private void handle(final ChangeVmPasswordMsg msg) { final ChangeVmPasswordReply reply = new ChangeVmPasswordReply(); ChangeVmPasswordCmd cmd = new ChangeVmPasswordCmd(); cmd.setAccountPerference(msg.getAccountPerference()); cmd.setTimeout(msg.getTimeout()); restf.asyncJsonPost(changeVmPasswordPath, cmd, new JsonAsyncRESTCallback<ChangeVmPasswordResponse>(msg) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); } @Override public void success(ChangeVmPasswordResponse ret) { if (!ret.isSuccess()) { reply.setError(errf.stringToOperationError(ret.getError())); } else { reply.setVmAccountPerference(ret.getVmAccountPerference()); } bus.reply(msg, reply); } @Override public Class<ChangeVmPasswordResponse> getReturnClass() { return ChangeVmPasswordResponse.class; } }); } private void handle(final OnlineChangeVmCpuMemoryMsg msg) { final OnlineChangeVmCpuMemoryReply reply = new OnlineChangeVmCpuMemoryReply(); OnlineChangeCpuMemoryCmd cmd = new OnlineChangeCpuMemoryCmd(); cmd.setVmUuid(msg.getVmInstanceUuid()); cmd.setCpuNum(msg.getInstanceOfferingInventory().getCpuNum()); cmd.setMemorySize(msg.getInstanceOfferingInventory().getMemorySize()); restf.asyncJsonPost(changeCpuMemoryPath, cmd, new JsonAsyncRESTCallback<OnlineChangeCpuMemoryResponse>(msg) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); } @Override public void success(OnlineChangeCpuMemoryResponse ret) { if (!ret.isSuccess()) { reply.setError(errf.stringToOperationError(ret.getError())); } else { InstanceOfferingInventory inventory = new InstanceOfferingInventory(); inventory.setCpuNum(ret.getCpuNum()); inventory.setMemorySize(ret.getMemorySize()); reply.setInstanceOfferingInventory(inventory); } bus.reply(msg, reply); } @Override public Class<OnlineChangeCpuMemoryResponse> getReturnClass() { return OnlineChangeCpuMemoryResponse.class; } }); } private void handle(final GetVmConsoleAddressFromHostMsg msg) { final GetVmConsoleAddressFromHostReply reply = new GetVmConsoleAddressFromHostReply(); GetVncPortCmd cmd = new GetVncPortCmd(); cmd.setVmUuid(msg.getVmInstanceUuid()); restf.asyncJsonPost(getConsolePortPath, cmd, new JsonAsyncRESTCallback<GetVncPortResponse>() { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); } @Override public void success(GetVncPortResponse ret) { if (!ret.isSuccess()) { reply.setError(errf.stringToOperationError(ret.getError())); } else { reply.setHostIp(self.getManagementIp()); reply.setProtocol(ret.getProtocol()); reply.setPort(ret.getPort()); } bus.reply(msg, reply); } @Override public Class<GetVncPortResponse> getReturnClass() { return GetVncPortResponse.class; } }); } private void handle(final CheckVmStateOnHypervisorMsg msg) { final CheckVmStateOnHypervisorReply reply = new CheckVmStateOnHypervisorReply(); if (self.getStatus() != HostStatus.Connected) { reply.setError(errf.stringToOperationError( String.format("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus()) )); bus.reply(msg, reply); return; } // NOTE: don't run this message in the sync task // there can be many such kind of messages // running in the sync task may cause other tasks starved CheckVmStateCmd cmd = new CheckVmStateCmd(); cmd.vmUuids = msg.getVmInstanceUuids(); cmd.hostUuid = self.getUuid(); restf.asyncJsonPost(checkVmStatePath, cmd, new JsonAsyncRESTCallback<CheckVmStateRsp>(msg) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); } @Override public void success(CheckVmStateRsp ret) { if (!ret.isSuccess()) { reply.setError(errf.stringToOperationError(ret.getError())); } else { Map<String, String> m = new HashMap<>(); for (Map.Entry<String, String> e : ret.states.entrySet()) { m.put(e.getKey(), KvmVmState.valueOf(e.getValue()).toVmInstanceState().toString()); } reply.setStates(m); } bus.reply(msg, reply); } @Override public Class<CheckVmStateRsp> getReturnClass() { return CheckVmStateRsp.class; } }); } private void handle(final DetachIsoOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { detachIso(msg, new NoErrorCompletion(msg, chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("detach-iso-%s-on-host-%s", msg.getIsoUuid(), self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void detachIso(final DetachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) { final DetachIsoOnHypervisorReply reply = new DetachIsoOnHypervisorReply(); DetachIsoCmd cmd = new DetachIsoCmd(); cmd.isoUuid = msg.getIsoUuid(); cmd.vmUuid = msg.getVmInstanceUuid(); KVMHostInventory inv = (KVMHostInventory) getSelfInventory(); for (KVMPreDetachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreDetachIsoExtensionPoint.class)) { ext.preDetachIsoExtensionPoint(inv, cmd); } restf.asyncJsonPost(detachIsoPath, cmd, new JsonAsyncRESTCallback<DetachIsoRsp>(msg, completion) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } @Override public void success(DetachIsoRsp ret) { if (!ret.isSuccess()) { reply.setError(errf.stringToOperationError(ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public Class<DetachIsoRsp> getReturnClass() { return DetachIsoRsp.class; } }); } private void handle(final AttachIsoOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { attachIso(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("attach-iso-%s-on-host-%s", msg.getIsoSpec().getImageUuid(), self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void attachIso(final AttachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) { final AttachIsoOnHypervisorReply reply = new AttachIsoOnHypervisorReply(); IsoTO iso = new IsoTO(); iso.setImageUuid(msg.getIsoSpec().getImageUuid()); iso.setPath(msg.getIsoSpec().getInstallPath()); AttachIsoCmd cmd = new AttachIsoCmd(); cmd.vmUuid = msg.getVmInstanceUuid(); cmd.iso = iso; KVMHostInventory inv = (KVMHostInventory) getSelfInventory(); for (KVMPreAttachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreAttachIsoExtensionPoint.class)) { ext.preAttachIsoExtensionPoint(inv, cmd); } restf.asyncJsonPost(attachIsoPath, cmd, new JsonAsyncRESTCallback<AttachIsoRsp>(msg, completion) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } @Override public void success(AttachIsoRsp ret) { if (!ret.isSuccess()) { reply.setError(errf.stringToOperationError(ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public Class<AttachIsoRsp> getReturnClass() { return AttachIsoRsp.class; } }); } private void handle(final DetachNicFromVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { detachNic(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "detach-nic-on-kvm-host-" + self.getUuid(); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void detachNic(final DetachNicFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) { final DetachNicFromVmOnHypervisorReply reply = new DetachNicFromVmOnHypervisorReply(); NicTO to = completeNicInfo(msg.getNic()); DetachNicCommand cmd = new DetachNicCommand(); cmd.setVmUuid(msg.getVmInstanceUuid()); cmd.setNic(to); restf.asyncJsonPost(detachNicPath, cmd, new JsonAsyncRESTCallback<DetachNicRsp>(msg, completion) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } @Override public void success(DetachNicRsp ret) { if (!ret.isSuccess()) { reply.setError(errf.stringToOperationError(ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public Class<DetachNicRsp> getReturnClass() { return DetachNicRsp.class; } }); } private void handle(final KVMHostSyncHttpCallMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { executeSyncHttpCall(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("execute-sync-http-call-on-kvm-host-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void executeSyncHttpCall(KVMHostSyncHttpCallMsg msg, NoErrorCompletion completion) { if (!msg.isNoStatusCheck()) { checkStatus(); } String url = buildUrl(msg.getPath()); MessageCommandRecorder.record(msg.getCommandClassName()); LinkedHashMap rsp = restf.syncJsonPost(url, msg.getCommand(), LinkedHashMap.class); KVMHostSyncHttpCallReply reply = new KVMHostSyncHttpCallReply(); reply.setResponse(rsp); bus.reply(msg, reply); completion.done(); } private void handle(final KVMHostAsyncHttpCallMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { executeAsyncHttpCall(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("execute-async-http-call-on-kvm-host-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private String buildUrl(String path) { UriComponentsBuilder ub = UriComponentsBuilder.newInstance(); ub.scheme(KVMGlobalProperty.AGENT_URL_SCHEME); ub.host(self.getManagementIp()); ub.port(KVMGlobalProperty.AGENT_PORT); if (!"".equals(KVMGlobalProperty.AGENT_URL_ROOT_PATH)) { ub.path(KVMGlobalProperty.AGENT_URL_ROOT_PATH); } ub.path(path); return ub.build().toUriString(); } private void executeAsyncHttpCall(final KVMHostAsyncHttpCallMsg msg, final NoErrorCompletion completion) { if (!msg.isNoStatusCheck()) { checkStatus(); } String url = buildUrl(msg.getPath()); MessageCommandRecorder.record(msg.getCommandClassName()); restf.asyncJsonPost(url, msg.getCommand(), new JsonAsyncRESTCallback<LinkedHashMap>(msg, completion) { @Override public void fail(ErrorCode err) { KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply(); if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR)) { reply.setError(errf.instantiateErrorCode(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, "cannot do the operation on the KVM host", err)); } else { reply.setError(reply.getError()); } bus.reply(msg, reply); completion.done(); } @Override public void success(LinkedHashMap ret) { KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply(); reply.setResponse(ret); bus.reply(msg, reply); completion.done(); } @Override public Class<LinkedHashMap> getReturnClass() { return LinkedHashMap.class; } }, TimeUnit.SECONDS, msg.getCommandTimeout()); } private void handle(final MergeVolumeSnapshotOnKvmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { mergeVolumeSnapshot(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("merge-volume-snapshot-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void mergeVolumeSnapshot(final MergeVolumeSnapshotOnKvmMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); final MergeVolumeSnapshotOnKvmReply reply = new MergeVolumeSnapshotOnKvmReply(); VolumeInventory volume = msg.getTo(); if (volume.getVmInstanceUuid() != null) { SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class); q.select(VmInstanceVO_.state); q.add(VmInstanceVO_.uuid, Op.EQ, volume.getVmInstanceUuid()); VmInstanceState state = q.findValue(); if (state != VmInstanceState.Stopped && state != VmInstanceState.Running) { throw new OperationFailureException(errf.stringToOperationError( String.format("cannot do volume snapshot merge when vm[uuid:%s] is in state of %s." + " The operation is only allowed when vm is Running or Stopped", volume.getUuid(), state) )); } if (state == VmInstanceState.Running) { String libvirtVersion = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN); if (new VersionComparator(KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION).compare(libvirtVersion) > 0) { throw new OperationFailureException(errf.stringToOperationError( String.format("live volume snapshot merge needs libvirt version greater than %s," + " current libvirt version is %s." + " Please stop vm and redo the operation or detach the volume if it's data volume", KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION, libvirtVersion) )); } } } VolumeSnapshotInventory snapshot = msg.getFrom(); MergeSnapshotCmd cmd = new MergeSnapshotCmd(); cmd.setFullRebase(msg.isFullRebase()); cmd.setDestPath(volume.getInstallPath()); cmd.setSrcPath(snapshot.getPrimaryStorageInstallPath()); cmd.setVmUuid(volume.getVmInstanceUuid()); cmd.setDeviceId(volume.getDeviceId()); restf.asyncJsonPost(mergeSnapshotPath, cmd, new JsonAsyncRESTCallback<MergeSnapshotRsp>(msg, completion) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } @Override public void success(MergeSnapshotRsp ret) { if (!ret.isSuccess()) { reply.setError(errf.stringToOperationError(ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public Class<MergeSnapshotRsp> getReturnClass() { return MergeSnapshotRsp.class; } }); } private void handle(final TakeSnapshotOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { takeSnapshot(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("take-snapshot-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void takeSnapshot(final TakeSnapshotOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); final TakeSnapshotOnHypervisorReply reply = new TakeSnapshotOnHypervisorReply(); TakeSnapshotCmd cmd = new TakeSnapshotCmd(); if (msg.getVmUuid() != null) { SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class); q.select(VmInstanceVO_.state); q.add(VmInstanceVO_.uuid, SimpleQuery.Op.EQ, msg.getVmUuid()); VmInstanceState vmState = q.findValue(); if (vmState != VmInstanceState.Running && vmState != VmInstanceState.Stopped && vmState != VmInstanceState.Paused) { throw new OperationFailureException(errf.stringToOperationError( String.format("vm[uuid:%s] is not Running or Stopped, current state[%s]", msg.getVmUuid(), vmState) )); } if (!HostSystemTags.LIVE_SNAPSHOT.hasTag(self.getUuid())) { if (vmState != VmInstanceState.Stopped) { throw new OperationFailureException(errf.instantiateErrorCode(SysErrors.NO_CAPABILITY_ERROR, String.format("kvm host[uuid:%s, name:%s, ip:%s] doesn't not support live snapshot. please stop vm[uuid:%s] and try again", self.getUuid(), self.getName(), self.getManagementIp(), msg.getVmUuid()) )); } } cmd.setVolumeUuid(msg.getVolume().getUuid()); cmd.setVmUuid(msg.getVmUuid()); cmd.setDeviceId(msg.getVolume().getDeviceId()); } cmd.setVolumeInstallPath(msg.getVolume().getInstallPath()); cmd.setInstallPath(msg.getInstallPath()); cmd.setFullSnapshot(msg.isFullSnapshot()); restf.asyncJsonPost(snapshotPath, cmd, new JsonAsyncRESTCallback<TakeSnapshotResponse>(msg, completion) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } @Override public void success(TakeSnapshotResponse ret) { if (ret.isSuccess()) { reply.setNewVolumeInstallPath(ret.getNewVolumeInstallPath()); reply.setSnapshotInstallPath(ret.getSnapshotInstallPath()); reply.setSize(ret.getSize()); } else { reply.setError(errf.stringToOperationError(ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public Class<TakeSnapshotResponse> getReturnClass() { return TakeSnapshotResponse.class; } }); } private void migrateVm(final Iterator<MigrateStruct> it, final Completion completion) { final String hostIp; final String vmUuid; final StorageMigrationPolicy storageMigrationPolicy; synchronized (it) { if (!it.hasNext()) { completion.success(); return; } MigrateStruct s = it.next(); vmUuid = s.vmUuid; hostIp = s.dstHostIp; storageMigrationPolicy = s.storageMigrationPolicy; } SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class); q.select(VmInstanceVO_.internalId); q.add(VmInstanceVO_.uuid, Op.EQ, vmUuid); final Long vmInternalId = q.findValue(); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("migrate-vm-%s-on-kvm-host-%s", vmUuid, self.getUuid())); chain.then(new ShareFlow() { @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "migrate-vm"; @Override public void run(final FlowTrigger trigger, Map data) { MigrateVmCmd cmd = new MigrateVmCmd(); cmd.setDestHostIp(hostIp); cmd.setSrcHostIp(self.getManagementIp()); cmd.setStorageMigrationPolicy(storageMigrationPolicy == null ? null : storageMigrationPolicy.toString()); cmd.setVmUuid(vmUuid); restf.asyncJsonPost(migrateVmPath, cmd, new JsonAsyncRESTCallback<MigrateVmResponse>(trigger) { @Override public void fail(ErrorCode err) { completion.fail(err); } @Override public void success(MigrateVmResponse ret) { if (!ret.isSuccess()) { ErrorCode err = errf.instantiateErrorCode(HostErrors.FAILED_TO_MIGRATE_VM_ON_HYPERVISOR, String.format("failed to migrate vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s], %s", vmUuid, self.getUuid(), self.getManagementIp(), hostIp, ret.getError()) ); trigger.fail(err); } else { String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]", vmUuid, self.getUuid(), self.getManagementIp(), hostIp); logger.debug(info); trigger.next(); } } @Override public Class<MigrateVmResponse> getReturnClass() { return MigrateVmResponse.class; } }); } }); flow(new NoRollbackFlow() { String __name__ = "harden-vm-console-on-dst-host"; @Override public void run(final FlowTrigger trigger, Map data) { HardenVmConsoleCmd cmd = new HardenVmConsoleCmd(); cmd.vmInternalId = vmInternalId; cmd.vmUuid = vmUuid; cmd.hostManagementIp = hostIp; UriComponentsBuilder ub = UriComponentsBuilder.newInstance(); ub.scheme(KVMGlobalProperty.AGENT_URL_SCHEME); ub.host(hostIp); ub.port(KVMGlobalProperty.AGENT_PORT); ub.path(KVMConstant.KVM_HARDEN_CONSOLE_PATH); String url = ub.build().toString(); restf.asyncJsonPost(url, cmd, new JsonAsyncRESTCallback<AgentResponse>(trigger) { @Override public void fail(ErrorCode err) { //TODO logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, err)); trigger.next(); } @Override public void success(AgentResponse ret) { if (!ret.isSuccess()) { //TODO logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, ret.getError())); } trigger.next(); } @Override public Class<AgentResponse> getReturnClass() { return AgentResponse.class; } }); } }); flow(new NoRollbackFlow() { String __name__ = "delete-vm-console-firewall-on-source-host"; @Override public void run(final FlowTrigger trigger, Map data) { DeleteVmConsoleFirewallCmd cmd = new DeleteVmConsoleFirewallCmd(); cmd.vmInternalId = vmInternalId; cmd.vmUuid = vmUuid; cmd.hostManagementIp = self.getManagementIp(); restf.asyncJsonPost(deleteConsoleFirewall, cmd, new JsonAsyncRESTCallback<AgentResponse>(trigger) { @Override public void fail(ErrorCode err) { //TODO logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" + " the source host[uuid:%s, ip:%s], %s", vmUuid, self.getUuid(), self.getManagementIp(), err)); trigger.next(); } @Override public void success(AgentResponse ret) { if (!ret.isSuccess()) { logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" + " the source host[uuid:%s, ip:%s], %s", vmUuid, self.getUuid(), self.getManagementIp(), ret.getError())); } trigger.next(); } @Override public Class<AgentResponse> getReturnClass() { return AgentResponse.class; } }); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]", vmUuid, self.getUuid(), self.getManagementIp(), hostIp); logger.debug(info); migrateVm(it, completion); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } private void handle(final MigrateVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { migrateVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("migrate-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } class MigrateStruct { String vmUuid; String dstHostIp; StorageMigrationPolicy storageMigrationPolicy; } private void migrateVm(final MigrateVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); List<MigrateStruct> lst = new ArrayList<>(); MigrateStruct s = new MigrateStruct(); s.vmUuid = msg.getVmInventory().getUuid(); s.dstHostIp = msg.getDestHostInventory().getManagementIp(); s.storageMigrationPolicy = msg.getStorageMigrationPolicy(); lst.add(s); final MigrateVmOnHypervisorReply reply = new MigrateVmOnHypervisorReply(); migrateVm(lst.iterator(), new Completion(msg, completion) { @Override public void success() { bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); completion.done(); } }); } private void handle(final VmAttachNicOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { attachNic(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("attach-nic-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void attachNic(final VmAttachNicOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); NicTO to = completeNicInfo(msg.getNicInventory()); final VmAttachNicOnHypervisorReply reply = new VmAttachNicOnHypervisorReply(); AttachNicCommand cmd = new AttachNicCommand(); cmd.setVmUuid(msg.getNicInventory().getVmInstanceUuid()); cmd.setNic(to); KVMHostInventory inv = (KVMHostInventory) getSelfInventory(); for (KvmPreAttachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreAttachNicExtensionPoint.class)) { ext.preAttachNicExtensionPoint(inv, cmd); } restf.asyncJsonPost(attachNicPath, cmd, new JsonAsyncRESTCallback<AttachNicResponse>(msg, completion) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } @Override public void success(AttachNicResponse ret) { if (!ret.isSuccess()) { reply.setError(errf.stringToTimeoutError(String.format("failed to attach nic[uuid:%s, vm:%s] on kvm host[uuid:%s, ip:%s]," + "because %s", msg.getNicInventory().getUuid(), msg.getNicInventory().getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()))); } bus.reply(msg, reply); completion.done(); } @Override public Class<AttachNicResponse> getReturnClass() { return AttachNicResponse.class; } }); } private void handle(final DetachVolumeFromVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { detachVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("detach-volume-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void detachVolume(final DetachVolumeFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); VolumeTO to = new VolumeTO(); final VolumeInventory vol = msg.getInventory(); final VmInstanceInventory vm = msg.getVmInventory(); to.setInstallPath(vol.getInstallPath()); to.setDeviceId(vol.getDeviceId()); to.setDeviceType(getVolumeTOType(vol)); to.setVolumeUuid(vol.getUuid()); // volumes can only be attached on Windows if the virtio is enabled // so for Windows, use virtio as well to.setUseVirtio(ImagePlatform.Windows.toString().equals(vm.getPlatform()) || ImagePlatform.valueOf(vm.getPlatform()).isParaVirtualization()); to.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(vol.getUuid())); to.setWwn(setVolumeWwn(vol.getUuid())); final DetachVolumeFromVmOnHypervisorReply reply = new DetachVolumeFromVmOnHypervisorReply(); final DetachDataVolumeCmd cmd = new DetachDataVolumeCmd(); cmd.setVolume(to); cmd.setVmUuid(vm.getUuid()); extEmitter.beforeDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd); restf.asyncJsonPost(detachDataVolumePath, cmd, new JsonAsyncRESTCallback<DetachDataVolumeResponse>(msg, completion) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, err); completion.done(); } @Override public void success(DetachDataVolumeResponse ret) { if (!ret.isSuccess()) { String err = String.format("failed to detach data volume[uuid:%s, installPath:%s] from vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(), getSelf().getUuid(), getSelf().getManagementIp(), ret.getError()); logger.warn(err); reply.setError(errf.stringToOperationError(err)); extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError()); } else { extEmitter.afterDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd); } bus.reply(msg, reply); completion.done(); } @Override public Class<DetachDataVolumeResponse> getReturnClass() { return DetachDataVolumeResponse.class; } }); } private void handle(final AttachVolumeToVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { attachVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("attach-volume-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private String setVolumeWwn(String volumeUUid) { if (!KVMSystemTags.VOLUME_WWN.hasTag(volumeUUid)) { KVMSystemTags.VOLUME_WWN.createTag(volumeUUid, VolumeVO.class, map(e(KVMSystemTags.VOLUME_WWN_TOKEN, new WwnUtils().getRandomWwn()))); } String wwn = KVMSystemTags.VOLUME_WWN.getTokenByResourceUuid(volumeUUid, KVMSystemTags.VOLUME_WWN_TOKEN); DebugUtils.Assert(new WwnUtils().isValidWwn(wwn), String.format("Not a valid wwn[%s] for volume[uuid:%s]", wwn, volumeUUid)); return wwn; } private void attachVolume(final AttachVolumeToVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); VolumeTO to = new VolumeTO(); final VolumeInventory vol = msg.getInventory(); final VmInstanceInventory vm = msg.getVmInventory(); to.setInstallPath(vol.getInstallPath()); to.setDeviceId(vol.getDeviceId()); to.setDeviceType(getVolumeTOType(vol)); to.setVolumeUuid(vol.getUuid()); // volumes can only be attached on Windows if the virtio is enabled // so for Windows, use virtio as well to.setUseVirtio(ImagePlatform.Windows.toString().equals(vm.getPlatform()) || ImagePlatform.valueOf(vm.getPlatform()).isParaVirtualization()); to.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(vol.getUuid())); to.setWwn(setVolumeWwn(vol.getUuid())); to.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value()); final AttachVolumeToVmOnHypervisorReply reply = new AttachVolumeToVmOnHypervisorReply(); final AttachDataVolumeCmd cmd = new AttachDataVolumeCmd(); cmd.setVolume(to); cmd.setVmUuid(msg.getVmInventory().getUuid()); extEmitter.beforeAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd); restf.asyncJsonPost(attachDataVolumePath, cmd, new JsonAsyncRESTCallback<AttachDataVolumeResponse>(msg, completion) { @Override public void fail(ErrorCode err) { extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, err); reply.setError(err); bus.reply(msg, reply); completion.done(); } @Override public void success(AttachDataVolumeResponse ret) { if (!ret.isSuccess()) { String err = String.format("failed to attach data volume[uuid:%s, installPath:%s] to vm[uuid:%s, name:%s]" + " on kvm host[uuid:%s, ip:%s], because %s", vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(), getSelf().getUuid(), getSelf().getManagementIp(), ret.getError()); logger.warn(err); reply.setError(errf.stringToOperationError(err)); extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError()); } else { extEmitter.afterAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd); } bus.reply(msg, reply); completion.done(); } @Override public Class<AttachDataVolumeResponse> getReturnClass() { return AttachDataVolumeResponse.class; } }); } private void handle(final DestroyVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { destroyVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("destroy-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void destroyVm(final DestroyVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); final VmInstanceInventory vminv = msg.getVmInventory(); try { extEmitter.beforeDestroyVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv); } catch (KVMException e) { String err = String.format("failed to destroy vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), e.getMessage()); logger.warn(err, e); throw new OperationFailureException(errf.stringToOperationError(err)); } DestroyVmCmd cmd = new DestroyVmCmd(); cmd.setUuid(vminv.getUuid()); restf.asyncJsonPost(destroyVmPath, cmd, new JsonAsyncRESTCallback<DestroyVmResponse>(msg, completion) { @Override public void fail(ErrorCode err) { DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply(); if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR)) { err = errf.instantiateErrorCode(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, "unable to destroy a vm", err); } reply.setError(err); extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError()); bus.reply(msg, reply); completion.done(); } @Override public void success(DestroyVmResponse ret) { DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply(); if (!ret.isSuccess()) { String err = String.format("unable to destroy vm[uuid:%s, name:%s] on kvm host [uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, err)); extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError()); } else { logger.debug(String.format("successfully destroyed vm[uuid:%s] on kvm host[uuid:%s]", vminv.getUuid(), self.getUuid())); extEmitter.destroyVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv); } bus.reply(msg, reply); completion.done(); } @Override public Class<DestroyVmResponse> getReturnClass() { return DestroyVmResponse.class; } }); } private void handle(final RebootVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { rebootVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("reboot-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private List<String> toKvmBootDev(List<String> order) { List<String> ret = new ArrayList<String>(); for (String o : order) { if (VmBootDevice.HardDisk.toString().equals(o)) { ret.add(BootDev.hd.toString()); } else if (VmBootDevice.CdRom.toString().equals(o)) { ret.add(BootDev.cdrom.toString()); } else { throw new CloudRuntimeException(String.format("unknown boot device[%s]", o)); } } return ret; } private void rebootVm(final RebootVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); final VmInstanceInventory vminv = msg.getVmInventory(); try { extEmitter.beforeRebootVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv); } catch (KVMException e) { String err = String.format("failed to reboot vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), e.getMessage()); logger.warn(err, e); throw new OperationFailureException(errf.stringToOperationError(err)); } RebootVmCmd cmd = new RebootVmCmd(); long timeout = TimeUnit.MILLISECONDS.toSeconds(msg.getTimeout()); cmd.setUuid(vminv.getUuid()); cmd.setTimeout(timeout); cmd.setBootDev(toKvmBootDev(msg.getBootOrders())); restf.asyncJsonPost(rebootVmPath, cmd, new JsonAsyncRESTCallback<RebootVmResponse>(msg, completion) { @Override public void fail(ErrorCode err) { RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply(); reply.setError(err); extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err); bus.reply(msg, reply); completion.done(); } @Override public void success(RebootVmResponse ret) { RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply(); if (!ret.isSuccess()) { String err = String.format("unable to reboot vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_REBOOT_VM_ON_HYPERVISOR, err)); extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError()); } else { extEmitter.rebootVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv); } bus.reply(msg, reply); completion.done(); } @Override public Class<RebootVmResponse> getReturnClass() { return RebootVmResponse.class; } }); } private void handle(final StopVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { stopVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("stop-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void stopVm(final StopVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); final VmInstanceInventory vminv = msg.getVmInventory(); try { extEmitter.beforeStopVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv); } catch (KVMException e) { String err = String.format("failed to stop vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), e.getMessage()); logger.warn(err, e); throw new OperationFailureException(errf.stringToOperationError(err)); } StopVmCmd cmd = new StopVmCmd(); cmd.setUuid(vminv.getUuid()); cmd.setType(msg.getType()); cmd.setTimeout(120); restf.asyncJsonPost(stopVmPath, cmd, new JsonAsyncRESTCallback<StopVmResponse>(msg, completion) { @Override public void fail(ErrorCode err) { StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply(); if (err.isError(SysErrors.IO_ERROR, SysErrors.HTTP_ERROR)) { err = errf.instantiateErrorCode(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, "unable to stop a vm", err); } reply.setError(err); extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err); bus.reply(msg, reply); completion.done(); } @Override public void success(StopVmResponse ret) { StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply(); if (!ret.isSuccess()) { String err = String.format("unable to stop vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, err)); logger.warn(err); extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError()); } else { extEmitter.stopVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv); } bus.reply(msg, reply); completion.done(); } @Override public Class<StopVmResponse> getReturnClass() { return StopVmResponse.class; } }); } private void handle(final CreateVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("start-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } @Transactional private L2NetworkInventory getL2NetworkTypeFromL3NetworkUuid(String l3NetworkUuid) { String sql = "select l2 from L2NetworkVO l2 where l2.uuid = (select l3.l2NetworkUuid from L3NetworkVO l3 where l3.uuid = :l3NetworkUuid)"; TypedQuery<L2NetworkVO> query = dbf.getEntityManager().createQuery(sql, L2NetworkVO.class); query.setParameter("l3NetworkUuid", l3NetworkUuid); L2NetworkVO l2vo = query.getSingleResult(); return L2NetworkInventory.valueOf(l2vo); } private NicTO completeNicInfo(VmNicInventory nic) { L2NetworkInventory l2inv = getL2NetworkTypeFromL3NetworkUuid(nic.getL3NetworkUuid()); KVMCompleteNicInformationExtensionPoint extp = factory.getCompleteNicInfoExtension(L2NetworkType.valueOf(l2inv.getType())); NicTO to = extp.completeNicInformation(l2inv, nic); if (to.getUseVirtio() == null) { SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class); q.select(VmInstanceVO_.platform); q.add(VmInstanceVO_.uuid, Op.EQ, nic.getVmInstanceUuid()); String platform = q.findValue(); to.setUseVirtio(ImagePlatform.valueOf(platform).isParaVirtualization()); } return to; } private String getVolumeTOType(VolumeInventory vol) { return vol.getInstallPath().startsWith("iscsi") ? VolumeTO.ISCSI : VolumeTO.FILE; } private void startVm(final VmInstanceSpec spec, final NeedReplyMessage msg, final NoErrorCompletion completion) { checkStateAndStatus(); final StartVmCmd cmd = new StartVmCmd(); boolean virtio; String consoleMode; String nestedVirtualization; String platform = spec.getVmInventory().getPlatform() == null ? spec.getImageSpec().getInventory().getPlatform() : spec.getVmInventory().getPlatform(); if (ImagePlatform.Windows.toString().equals(platform)) { virtio = VmSystemTags.WINDOWS_VOLUME_ON_VIRTIO.hasTag(spec.getVmInventory().getUuid()); } else { virtio = ImagePlatform.valueOf(platform).isParaVirtualization(); } int cpuNum = spec.getVmInventory().getCpuNum(); cmd.setCpuNum(cpuNum); int socket; int cpuOnSocket; //TODO: this is a HACK!!! if (ImagePlatform.Windows.toString().equals(platform) || ImagePlatform.WindowsVirtio.toString().equals(platform)) { if (cpuNum == 1) { socket = 1; cpuOnSocket = 1; } else if (cpuNum % 2 == 0) { socket = 2; cpuOnSocket = cpuNum / 2; } else { socket = cpuNum; cpuOnSocket = 1; } } else { socket = 1; cpuOnSocket = cpuNum; } cmd.setSocketNum(socket); cmd.setCpuOnSocket(cpuOnSocket); cmd.setVmName(spec.getVmInventory().getName()); cmd.setVmInstanceUuid(spec.getVmInventory().getUuid()); cmd.setCpuSpeed(spec.getVmInventory().getCpuSpeed()); cmd.setMemory(spec.getVmInventory().getMemorySize()); cmd.setUseVirtio(virtio); cmd.setClock(ImagePlatform.isType(platform, ImagePlatform.Windows, ImagePlatform.WindowsVirtio) ? "localtime" : "utc"); VolumeTO rootVolume = new VolumeTO(); { rootVolume.setInstallPath(spec.getDestRootVolume().getInstallPath()); rootVolume.setDeviceId(spec.getDestRootVolume().getDeviceId()); rootVolume.setDeviceType(getVolumeTOType(spec.getDestRootVolume())); rootVolume.setVolumeUuid(spec.getDestRootVolume().getUuid()); rootVolume.setUseVirtio(virtio); rootVolume.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(spec.getDestRootVolume().getUuid())); rootVolume.setWwn(setVolumeWwn(spec.getDestRootVolume().getUuid())); rootVolume.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value()); } consoleMode = KVMGlobalConfig.VM_CONSOLE_MODE.value(String.class); nestedVirtualization = KVMGlobalConfig.NESTED_VIRTUALIZATION.value(String.class); cmd.setConsoleMode(consoleMode); cmd.setNestedVirtualization(nestedVirtualization); cmd.setRootVolume(rootVolume); List<VolumeTO> dataVolumes = new ArrayList<>(spec.getDestDataVolumes().size()); for (VolumeInventory data : spec.getDestDataVolumes()) { VolumeTO v = new VolumeTO(); v.setInstallPath(data.getInstallPath()); v.setDeviceId(data.getDeviceId()); v.setDeviceType(getVolumeTOType(data)); v.setVolumeUuid(data.getUuid()); // always use virtio driver for data volume v.setUseVirtio(true); v.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(data.getUuid())); v.setWwn(setVolumeWwn(data.getUuid())); v.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value()); dataVolumes.add(v); } cmd.setDataVolumes(dataVolumes); cmd.setVmInternalId(spec.getVmInventory().getInternalId()); List<NicTO> nics = new ArrayList<>(spec.getDestNics().size()); for (VmNicInventory nic : spec.getDestNics()) { nics.add(completeNicInfo(nic)); } cmd.setNics(nics); if (spec.getDestIso() != null) { IsoTO bootIso = new IsoTO(); bootIso.setPath(spec.getDestIso().getInstallPath()); bootIso.setImageUuid(spec.getDestIso().getImageUuid()); cmd.setBootIso(bootIso); } cmd.setBootDev(toKvmBootDev(spec.getBootOrders())); cmd.setHostManagementIp(self.getManagementIp()); cmd.setConsolePassword(spec.getConsolePassword()); cmd.setInstanceOfferingOnlineChange(spec.getInstanceOfferingOnlineChange()); addons(spec, cmd); KVMHostInventory khinv = KVMHostInventory.valueOf(getSelf()); try { extEmitter.beforeStartVmOnKvm(khinv, spec, cmd); } catch (KVMException e) { String err = String.format("failed to start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", spec.getVmInventory().getUuid(), spec.getVmInventory().getName(), self.getUuid(), self.getManagementIp(), e.getMessage()); logger.warn(err, e); throw new OperationFailureException(errf.stringToOperationError(err)); } extEmitter.addOn(khinv, spec, cmd); restf.asyncJsonPost(startVmPath, cmd, new JsonAsyncRESTCallback<StartVmResponse>(msg, completion) { @Override public void fail(ErrorCode err) { StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply(); reply.setError(err); reply.setSuccess(false); extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, err); bus.reply(msg, reply); completion.done(); } @Override public void success(StartVmResponse ret) { StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply(); if (ret.isSuccess()) { String info = String.format("successfully start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s]", spec.getVmInventory().getUuid(), spec.getVmInventory().getName(), self.getUuid(), self.getManagementIp()); logger.debug(info); extEmitter.startVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), spec); } else { String err = String.format("failed to start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", spec.getVmInventory().getUuid(), spec.getVmInventory().getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR, err)); logger.warn(err); extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, reply.getError()); } bus.reply(msg, reply); completion.done(); } @Override public Class<StartVmResponse> getReturnClass() { return StartVmResponse.class; } }); } private void addons(final VmInstanceSpec spec, StartVmCmd cmd) { KVMAddons.Channel chan = new KVMAddons.Channel(); chan.setSocketPath(makeChannelSocketPath(spec.getVmInventory().getUuid())); chan.setTargetName(String.format("org.qemu.guest_agent.0")); cmd.getAddons().put(chan.NAME, chan); logger.debug(String.format("make kvm channel device[path:%s, target:%s]", chan.getSocketPath(), chan.getTargetName())); } private String makeChannelSocketPath(String apvmuuid) { return PathUtil.join(String.format("/var/lib/libvirt/qemu/%s", apvmuuid)); } private void handle(final StartVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("start-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void handle(final CheckNetworkPhysicalInterfaceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { checkPhysicalInterface(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("check-network-physical-interface-on-host-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void pauseVm(final PauseVmOnHypervisorMsg msg,final NoErrorCompletion completion) { checkStatus(); final VmInstanceInventory vminv = msg.getVmInventory(); PauseVmOnHypervisorReply reply = new PauseVmOnHypervisorReply(); PauseVmCmd cmd = new PauseVmCmd(); cmd.setUuid(vminv.getUuid()); cmd.setTimeout(120); restf.asyncJsonPost(pauseVmPath, cmd, new JsonAsyncRESTCallback<PauseVmResponse>(msg,completion) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } @Override public void success(PauseVmResponse ret) { if(!ret.isSuccess()) { String err = String.format("unable to pause vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, err)); logger.warn(err); } bus.reply(msg, reply); completion.done(); } @Override public Class<PauseVmResponse> getReturnClass() { return PauseVmResponse.class ; } }); } private void handle(final PauseVmOnHypervisorMsg msg){ thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain){ pauseVm(msg,new NoErrorCompletion(chain){ @Override public void done() { chain.next(); } }); } @Override public String getName(){ return String.format("pause-vm-%s-on-host-%s",msg.getVmInventory().getUuid(),self.getUuid()); } @Override protected int getSyncLevel(){ return getHostSyncLevel(); } }); } private void handle(final ResumeVmOnHypervisorMsg msg){ thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { resumeVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("resume-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void resumeVm(final ResumeVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); final VmInstanceInventory vminv = msg.getVmInventory(); ResumeVmOnHypervisorReply reply = new ResumeVmOnHypervisorReply(); ResumeVmCmd cmd = new ResumeVmCmd(); cmd.setUuid(vminv.getUuid()); cmd.setTimeout(120); restf.asyncJsonPost(resumeVmPath, cmd, new JsonAsyncRESTCallback<ResumeVmResponse>(msg, completion) { @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } @Override public void success(ResumeVmResponse ret) { if (!ret.isSuccess()) { String err = String.format("unable to resume vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, err)); logger.warn(err); } bus.reply(msg, reply); completion.done(); } @Override public Class<ResumeVmResponse> getReturnClass() { return ResumeVmResponse.class; } }); } private void checkPhysicalInterface(CheckNetworkPhysicalInterfaceMsg msg, NoErrorCompletion completion) { checkState(); CheckPhysicalNetworkInterfaceCmd cmd = new CheckPhysicalNetworkInterfaceCmd(); cmd.addInterfaceName(msg.getPhysicalInterface()); CheckNetworkPhysicalInterfaceReply reply = new CheckNetworkPhysicalInterfaceReply(); CheckPhysicalNetworkInterfaceResponse rsp = restf.syncJsonPost(checkPhysicalNetworkInterfacePath, cmd, CheckPhysicalNetworkInterfaceResponse.class); if (!rsp.isSuccess()) { String err = rsp.getFailedInterfaceNames().isEmpty() ? rsp.getError() : String.format( "%s, failed to check physical network interfaces[names : %s] on kvm host[uuid:%s, ip:%s]", rsp.getError(), msg.getPhysicalInterface(), context.getInventory() .getUuid(), context.getInventory().getManagementIp()); reply.setError(errf.stringToOperationError(err)); logger.warn(err); } bus.reply(msg, reply); completion.done(); } @Override public void handleMessage(Message msg) { try { if (msg instanceof APIMessage) { handleApiMessage((APIMessage) msg); } else { handleLocalMessage(msg); } } catch (Exception e) { bus.logExceptionWithMessageDump(msg, e); bus.replyErrorByMessageType(msg, e); } } @Override public void changeStateHook(HostState current, HostStateEvent stateEvent, HostState next) { } @Override public void deleteHook() { } @Override protected HostInventory getSelfInventory() { return KVMHostInventory.valueOf(getSelf()); } protected void pingHook(final Completion completion) { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("ping-kvm-host-%s", self.getUuid())); chain.then(new ShareFlow() { @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "ping-host"; @AfterDone List<Runnable> afterDone = new ArrayList<>(); @Override public void run(FlowTrigger trigger, Map data) { PingCmd cmd = new PingCmd(); cmd.hostUuid = self.getUuid(); restf.asyncJsonPost(pingPath, cmd, new JsonAsyncRESTCallback<PingResponse>(trigger) { @Override public void fail(ErrorCode err) { trigger.fail(err); } @Override public void success(PingResponse ret) { if (ret.isSuccess()) { if (!self.getUuid().equals(ret.getHostUuid())) { afterDone.add(() -> { String info = String.format("detected abnormal status[host uuid change, expected: %s but: %s] of kvmagent," + "it's mainly caused by kvmagent restarts behind zstack management server. Report this to ping task, it will issue a reconnect soon", self.getUuid(), ret.getHostUuid()); logger.warn(info); ReconnectHostMsg rmsg = new ReconnectHostMsg(); rmsg.setHostUuid(self.getUuid()); bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid()); bus.send(rmsg); }); } trigger.next(); } else { trigger.fail(errf.stringToOperationError(ret.getError())); } } @Override public Class<PingResponse> getReturnClass() { return PingResponse.class; } }); } }); flow(new NoRollbackFlow() { String __name__ = "call-ping-no-failure-plugins"; @Override public void run(FlowTrigger trigger, Map data) { List<KVMPingAgentNoFailureExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentNoFailureExtensionPoint.class); if (exts.isEmpty()) { trigger.next(); return; } AsyncLatch latch = new AsyncLatch(exts.size(), new NoErrorCompletion(trigger) { @Override public void done() { trigger.next(); } }); KVMHostInventory inv = (KVMHostInventory) getSelfInventory(); for (KVMPingAgentNoFailureExtensionPoint ext : exts) { ext.kvmPingAgentNoFailure(inv, new NoErrorCompletion(latch) { @Override public void done() { latch.ack(); } }); } } }); flow(new NoRollbackFlow() { String __name__ = "call-ping-plugins"; @Override public void run(FlowTrigger trigger, Map data) { List<KVMPingAgentExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentExtensionPoint.class); Iterator<KVMPingAgentExtensionPoint> it = exts.iterator(); callPlugin(it, trigger); } private void callPlugin(Iterator<KVMPingAgentExtensionPoint> it, FlowTrigger trigger) { if (!it.hasNext()) { trigger.next(); return; } KVMPingAgentExtensionPoint ext = it.next(); logger.debug(String.format("calling KVMPingAgentExtensionPoint[%s]", ext.getClass())); ext.kvmPingAgent((KVMHostInventory) getSelfInventory(), new Completion(trigger) { @Override public void success() { callPlugin(it, trigger); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } @Override protected int getVmMigrateQuantity() { return KVMGlobalConfig.VM_MIGRATION_QUANTITY.value(Integer.class); } private ErrorCode connectToAgent() { ErrorCode errCode = null; try { ConnectCmd cmd = new ConnectCmd(); cmd.setHostUuid(self.getUuid()); cmd.setSendCommandUrl(restf.getSendCommandUrl()); cmd.setIptablesRules(KVMGlobalProperty.IPTABLES_RULES); ConnectResponse rsp = restf.syncJsonPost(connectPath, cmd, ConnectResponse.class); if (!rsp.isSuccess() || !rsp.isIptablesSucc()) { String err = String.format("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s", self.getUuid(), self.getManagementIp(), connectPath, rsp.getError()); errCode = errf.stringToOperationError(err); } else { VersionComparator libvirtVersion = new VersionComparator(rsp.getLibvirtVersion()); VersionComparator qemuVersion = new VersionComparator(rsp.getQemuVersion()); boolean liveSnapshot = libvirtVersion.compare(KVMConstant.MIN_LIBVIRT_LIVESNAPSHOT_VERSION) >= 0 && qemuVersion.compare(KVMConstant.MIN_QEMU_LIVESNAPSHOT_VERSION) >= 0; String hostOS = HostSystemTags.OS_DISTRIBUTION.getTokenByResourceUuid(self.getUuid(), HostSystemTags.OS_DISTRIBUTION_TOKEN); //liveSnapshot = liveSnapshot && (!"CentOS".equals(hostOS) || KVMGlobalConfig.ALLOW_LIVE_SNAPSHOT_ON_REDHAT.value(Boolean.class)); if (liveSnapshot) { logger.debug(String.format("kvm host[OS:%s, uuid:%s, name:%s, ip:%s] supports live snapshot with libvirt[version:%s], qemu[version:%s]", hostOS, self.getUuid(), self.getName(), self.getManagementIp(), rsp.getLibvirtVersion(), rsp.getQemuVersion())); HostSystemTags.LIVE_SNAPSHOT.reCreateInherentTag(self.getUuid()); } else { HostSystemTags.LIVE_SNAPSHOT.deleteInherentTag(self.getUuid()); } } } catch (RestClientException e) { String err = String.format("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s", self.getUuid(), self.getManagementIp(), connectPath, e.getMessage()); errCode = errf.stringToOperationError(err); } catch (Throwable t) { logger.warn(t.getMessage(), t); errCode = errf.throwableToInternalError(t); } return errCode; } private KVMHostVO getSelf() { return (KVMHostVO) self; } private void continueConnect(final boolean newAdded, final Completion completion) { ErrorCode errCode = connectToAgent(); if (errCode != null) { throw new OperationFailureException(errCode); } FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("continue-connecting-kvm-host-%s-%s", self.getManagementIp(), self.getUuid())); for (KVMHostConnectExtensionPoint extp : factory.getConnectExtensions()) { KVMHostConnectedContext ctx = new KVMHostConnectedContext(); ctx.setInventory((KVMHostInventory) getSelfInventory()); ctx.setNewAddedHost(newAdded); chain.then(extp.createKvmHostConnectingFlow(ctx)); } chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { String err = String.format("connection error for KVM host[uuid:%s, ip:%s]", self.getUuid(), self.getManagementIp()); completion.fail(errf.instantiateErrorCode(HostErrors.CONNECTION_ERROR, err, errCode)); } }).start(); } private void createHostVersionSystemTags(String distro, String release, String version) { HostSystemTags.OS_DISTRIBUTION.createInherentTag(self.getUuid(), map(e(HostSystemTags.OS_DISTRIBUTION_TOKEN, distro))); HostSystemTags.OS_RELEASE.createInherentTag(self.getUuid(), map(e(HostSystemTags.OS_RELEASE_TOKEN, release))); HostSystemTags.OS_VERSION.createInherentTag(self.getUuid(), map(e(HostSystemTags.OS_VERSION_TOKEN, version))); } @Override public void connectHook(final ConnectHostInfo info, final Completion complete) { if (CoreGlobalProperty.UNIT_TEST_ON) { if (info.isNewAdded()) { createHostVersionSystemTags("zstack", "kvmSimulator", "0.1"); KVMSystemTags.LIBVIRT_VERSION.createInherentTag(self.getUuid(), map(e(KVMSystemTags.LIBVIRT_VERSION_TOKEN, "1.2.9"))); KVMSystemTags.QEMU_IMG_VERSION.createInherentTag(self.getUuid(), map(e(KVMSystemTags.QEMU_IMG_VERSION_TOKEN, "2.0.0"))); } continueConnect(info.isNewAdded(), complete); } else { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("run-ansible-for-kvm-%s", self.getUuid())); chain.then(new ShareFlow() { @Override public void setup() { if (info.isNewAdded()) { if ((!AnsibleGlobalProperty.ZSTACK_REPO.contains("zstack-mn")) && (!AnsibleGlobalProperty.ZSTACK_REPO.equals("false"))) { flow(new NoRollbackFlow() { String __name__ = "ping-DNS-check-list"; @Override public void run(FlowTrigger trigger, Map data) { String checkList = KVMGlobalConfig.HOST_DNS_CHECK_LIST.value(); new Log(self.getUuid()).log(KVMHostLabel.ADD_HOST_CHECK_DNS, checkList); checkList = checkList.replaceAll(",", " "); SshShell sshShell = new SshShell(); sshShell.setHostname(getSelf().getManagementIp()); sshShell.setUsername(getSelf().getUsername()); sshShell.setPassword(getSelf().getPassword()); sshShell.setPort(getSelf().getPort()); SshResult ret = sshShell.runScriptWithToken("scripts/check-public-dns-name.sh", map(e("dnsCheckList", checkList))); if (ret.isSshFailure()) { trigger.fail(errf.stringToOperationError( String.format("unable to connect to KVM[ip:%s, username:%s, sshPort: %d, ] to do DNS check, please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()) )); } else if (ret.getReturnCode() != 0) { trigger.fail(errf.stringToOperationError( String.format("failed to ping all DNS/IP in %s; please check /etc/resolv.conf to make sure your host is able to reach public internet, or change host.DNSCheckList if you have some special network setup", KVMGlobalConfig.HOST_DNS_CHECK_LIST.value()) )); } else { trigger.next(); } } }); } } flow(new NoRollbackFlow() { String __name__ = "check-if-host-can-reach-management-node"; @Override public void run(FlowTrigger trigger, Map data) { new Log(self.getUuid()).log(KVMHostLabel.ADD_HOST_CHECK_PING_MGMT_NODE); SshShell sshShell = new SshShell(); sshShell.setHostname(getSelf().getManagementIp()); sshShell.setUsername(getSelf().getUsername()); sshShell.setPassword(getSelf().getPassword()); sshShell.setPort(getSelf().getPort()); ShellUtils.run(String.format("arp -d %s || true", getSelf().getManagementIp())); SshResult ret = sshShell.runCommand(String.format("curl --connect-timeout 10 %s", restf.getCallbackUrl())); if (ret.isSshFailure()) { throw new OperationFailureException(errf.stringToOperationError( String.format("unable to connect to KVM[ip:%s, username:%s, sshPort:%d] to check the management node connectivity," + "please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()) )); } else if (ret.getReturnCode() != 0) { throw new OperationFailureException(errf.stringToOperationError( String.format("the KVM host[ip:%s] cannot access the management node's callback url. It seems" + " that the KVM host cannot reach the management IP[%s]. %s %s", self.getManagementIp(), Platform.getManagementServerIp(), ret.getStderr(), ret.getExitErrorMessage()) )); } trigger.next(); } }); flow(new NoRollbackFlow() { String __name__ = "apply-ansible-playbook"; @Override public void run(final FlowTrigger trigger, Map data) { new Log(self.getUuid()).log(KVMHostLabel.CALL_ANSIBLE); String srcPath = PathUtil.findFileOnClassPath(String.format("ansible/kvm/%s", agentPackageName), true).getAbsolutePath(); String destPath = String.format("/var/lib/zstack/kvm/package/%s", agentPackageName); SshFileMd5Checker checker = new SshFileMd5Checker(); checker.setUsername(getSelf().getUsername()); checker.setPassword(getSelf().getPassword()); checker.setSshPort(getSelf().getPort()); checker.setTargetIp(getSelf().getManagementIp()); checker.addSrcDestPair(SshFileMd5Checker.ZSTACKLIB_SRC_PATH, String.format("/var/lib/zstack/kvm/package/%s", AnsibleGlobalProperty.ZSTACKLIB_PACKAGE_NAME)); checker.addSrcDestPair(srcPath, destPath); AnsibleRunner runner = new AnsibleRunner(); runner.installChecker(checker); runner.setAgentPort(KVMGlobalProperty.AGENT_PORT); runner.setTargetIp(getSelf().getManagementIp()); runner.setPlayBookName(KVMConstant.ANSIBLE_PLAYBOOK_NAME); runner.setUsername(getSelf().getUsername()); runner.setPassword(getSelf().getPassword()); runner.setSshPort(getSelf().getPort()); if (info.isNewAdded()) { runner.putArgument("init", "true"); runner.setFullDeploy(true); } runner.putArgument("pkg_kvmagent", agentPackageName); runner.putArgument("hostname", String.format("%s.zstack.org", self.getManagementIp().replaceAll("\\.", "-"))); UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl()); ub.path(new StringBind(KVMConstant.KVM_ANSIBLE_LOG_PATH_FROMAT).bind("uuid", self.getUuid()).toString()); String postUrl = ub.build().toString(); runner.putArgument("post_url", postUrl); runner.run(new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); flow(new NoRollbackFlow() { String __name__ = "echo-host"; @Override public void run(final FlowTrigger trigger, Map data) { new Log(self.getUuid()).log(KVMHostLabel.ECHO_AGENT); restf.echo(echoPath, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); if (info.isNewAdded()) { flow(new NoRollbackFlow() { String __name__ = "ansbile-get-kvm-host-facts"; @Override public void run(FlowTrigger trigger, Map data) { String privKeyFile = PathUtil.findFileOnClassPath(AnsibleConstant.RSA_PRIVATE_KEY).getAbsolutePath(); ShellResult ret = ShellUtils.runAndReturn(String.format("ansible -i %s --private-key %s -m setup -a filter=ansible_distribution* %s -e 'ansible_ssh_port=%d ansible_ssh_user=%s'", AnsibleConstant.INVENTORY_FILE, privKeyFile, self.getManagementIp(), getSelf().getPort(), getSelf().getUsername()), AnsibleConstant.ROOT_DIR); if (!ret.isReturnCode(0)) { trigger.fail(errf.stringToOperationError( String.format("unable to get kvm host[uuid:%s, ip:%s] facts by ansible\n%s", self.getUuid(), self.getManagementIp(), ret.getExecutionLog()) )); return; } String[] pairs = ret.getStdout().split(">>"); if (pairs.length != 2) { trigger.fail(errf.stringToOperationError(String.format("unrecognized ansible facts mediaType, %s", ret.getStdout()))); return; } LinkedHashMap output = JSONObjectUtil.toObject(pairs[1], LinkedHashMap.class); LinkedHashMap facts = (LinkedHashMap) output.get("ansible_facts"); if (facts == null) { trigger.fail(errf.stringToOperationError(String.format("unrecognized ansible facts mediaType, cannot find field 'ansible_facts', %s", ret.getStdout()))); return; } String distro = (String) facts.get("ansible_distribution"); String release = (String) facts.get("ansible_distribution_release"); String version = (String) facts.get("ansible_distribution_version"); createHostVersionSystemTags(distro, release, version); trigger.next(); } }); } flow(new NoRollbackFlow() { String __name__ = "collect-kvm-host-facts"; @Override public void run(final FlowTrigger trigger, Map data) { new Log(self.getUuid()).log(KVMHostLabel.COLLECT_HOST_FACTS); HostFactCmd cmd = new HostFactCmd(); restf.asyncJsonPost(hostFactPath, cmd, new JsonAsyncRESTCallback<HostFactResponse>(trigger) { @Override public void fail(ErrorCode err) { trigger.fail(err); } @Override public void success(HostFactResponse ret) { if (!ret.isSuccess()) { trigger.fail(errf.stringToOperationError(ret.getError())); return; } if (ret.getHvmCpuFlag() == null) { trigger.fail(errf.stringToOperationError( "cannot find either 'vmx' or 'svm' in /proc/cpuinfo, please make sure you have enabled virtualization in your BIOS setting" )); return; } KVMSystemTags.QEMU_IMG_VERSION.recreateTag(self.getUuid(), map(e(KVMSystemTags.QEMU_IMG_VERSION_TOKEN, ret.getQemuImgVersion()))); KVMSystemTags.LIBVIRT_VERSION.recreateTag(self.getUuid(), map(e(KVMSystemTags.LIBVIRT_VERSION_TOKEN, ret.getLibvirtVersion()))); KVMSystemTags.HVM_CPU_FLAG.recreateTag(self.getUuid(), map(e(KVMSystemTags.HVM_CPU_FLAG_TOKEN, ret.getHvmCpuFlag()))); if (ret.getLibvirtVersion().compareTo(KVMConstant.MIN_LIBVIRT_VIRTIO_SCSI_VERSION) >= 0) { KVMSystemTags.VIRTIO_SCSI.reCreateInherentTag(self.getUuid()); } trigger.next(); } @Override public Class<HostFactResponse> getReturnClass() { return HostFactResponse.class; } }); } }); flow(new NoRollbackFlow() { String __name__ = "prepare-host-env"; @Override public void run(FlowTrigger trigger, Map data) { new Log(self.getUuid()).log(KVMHostLabel.PREPARE_FIREWALL); String script = "which iptables > /dev/null && iptables -C FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 && iptables -D FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 || true"; runShell(script); trigger.next(); } }); error(new FlowErrorHandler(complete) { @Override public void handle(ErrorCode errCode, Map data) { complete.fail(errCode); } }); done(new FlowDoneHandler(complete) { @Override public void handle(Map data) { continueConnect(info.isNewAdded(), complete); } }); } }).start(); } } @Override protected int getHostSyncLevel() { return KVMGlobalConfig.HOST_SYNC_LEVEL.value(Integer.class); } @Override public void executeHostMessageHandlerHook(HostMessageHandlerExtensionPoint ext, Message msg) { } @Override protected HostVO updateHost(APIUpdateHostMsg msg) { if (!(msg instanceof APIUpdateKVMHostMsg)) { return super.updateHost(msg); } KVMHostVO vo = (KVMHostVO) super.updateHost(msg); vo = vo == null ? getSelf() : vo; APIUpdateKVMHostMsg umsg = (APIUpdateKVMHostMsg) msg; if (umsg.getUsername() != null) { vo.setUsername(umsg.getUsername()); } if (umsg.getPassword() != null) { vo.setPassword(umsg.getPassword()); } if (umsg.getSshPort() != null && umsg.getSshPort() > 0 && umsg.getSshPort() <= 65535) { vo.setPort(umsg.getSshPort()); } return vo; } }
package gov.nih.nci.caarray.magetab; import gov.nih.nci.caarray.domain.file.CaArrayFile; import gov.nih.nci.caarray.domain.file.CaArrayFileSet; import gov.nih.nci.caarray.domain.file.FileExtension; import gov.nih.nci.caarray.domain.file.FileStatus; import gov.nih.nci.caarray.domain.file.FileType; import gov.nih.nci.caarray.magetab.adf.AdfDocument; import gov.nih.nci.caarray.magetab.data.DataMatrix; import gov.nih.nci.caarray.magetab.data.NativeDataFile; import gov.nih.nci.caarray.magetab.idf.IdfDocument; import gov.nih.nci.caarray.magetab.io.FileRef; import gov.nih.nci.caarray.magetab.io.JavaIOFileRef; import gov.nih.nci.caarray.magetab.sdrf.SdrfDocument; import gov.nih.nci.caarray.test.data.arraydata.GenepixArrayDataFiles; import gov.nih.nci.caarray.test.data.magetab.MageTabDataFiles; import gov.nih.nci.caarray.test.data.magetab.SdrfTestFiles; import java.io.File; import java.io.FilenameFilter; import java.util.Collection; import java.util.Locale; /** * MAGE-TAB document sets to be used as test data. */ @SuppressWarnings("PMD.CyclomaticComplexity") public final class TestMageTabSets { private TestMageTabSets() { super(); } /** * Example set of documents included with MAGE-TAB specification. */ public static final MageTabFileSet MAGE_TAB_UNSUPPORTED_DATA_INPUT_SET = getUnsupportedDataInputSet(); /** * Example set of documents included with MAGE-TAB specification. */ public static final MageTabFileSet MAGE_TAB_MISPLACED_FACTOR_VALUES_INPUT_SET = getMisplacedFactorValuesInputSet(); /** * Example set of documents included with MAGE-TAB specification. */ public static final MageTabFileSet MAGE_TAB_SPECIFICATION_INPUT_SET = getSpecificationInputSet(); /** * Example set of documents included with MAGE-TAB specification. */ public static final MageTabFileSet MAGE_TAB_SPECIFICATION_CASE_SENSITIVITY_INPUT_SET = getSpecificationCaseSensitivityInputSet(); /** * Example set of documents based on the MAGE-TAB specification example, with no array design ref in the SDRF. */ public static final MageTabFileSet MAGE_TAB_SPECIFICATION_NO_ARRAY_DESIGN_INPUT_SET = getSpecificationNoArrayDesignInputSet(); /** * Example set of documents based on the MAGE-TAB specification example, with no experiment description in the IDF. */ public static final MageTabFileSet MAGE_TAB_SPECIFICATION_NO_EXP_DESC_INPUT_SET = getSpecificationNoExpDescInputSet(); /** * Example set of documents included with MAGE-TAB specification, minus the data matrix */ public static final MageTabFileSet MAGE_TAB_SPECIFICATION_NO_DATA_MATRIX_INPUT_SET = getSpecificationWithoutDataMatrixInputSet(); /** * Example set of documents with ERRORS based on the MAGE-TAB specification. */ public static final MageTabFileSet MAGE_TAB_ERROR_SPECIFICATION_INPUT_SET = getErrorSpecificationInputSet(); /** * Example set of documents with ERRORS based on the MAGE-TAB specification. */ public static final MageTabFileSet MAGE_TAB_GEDP_INPUT_SET = getGedpSpecificationInputSet(); /** * Example set of MAGE-TAB data with 10 large CEL files and no derived data. */ public static final MageTabFileSet PERFORMANCE_TEST_10_INPUT_SET = getPerformanceTest10InputSet(); /** * MAGE-TAB input set from TCGA Broad data. */ public static final MageTabFileSet TCGA_BROAD_INPUT_SET = getTcgaBroadInputSet(); /** * MAGE-TAB input set derived from EBI generated template. */ public static final MageTabFileSet EBI_TEMPLATE_INPUT_SET = getEbiTemplateInputSet(); /** * MAGE-TAB input set derived from 1x export data */ public static final MageTabFileSet CAARRAY1X_INPUT_SET = getCaarray1xInputSet(); /** * MAGE-TAB input set from TCGA Broad data. */ public static final MageTabFileSet DEFECT_12537_INPUT_SET = getDefect12537InputSet(); /** * MAGE-TAB input set from TCGA Broad data. */ public static final MageTabFileSet DEFECT_12537_ERROR_INPUT_SET = getDefect12537ErrorInputSet(); /** * Example set of MAGE-TAB data. */ public static final MageTabFileSet GSK_TEST_INPUT_SET = getGskTestSet(); /** * MAGE-TAB data set containing data derived from other derived data. */ public static final MageTabFileSet DERIVED_DATA_INPUT_SET = getDerivedDataInputSet(); /** * MAGE-TAB input set containing valid usage of Characteristics[ExternalSampleId] for Sample(s). */ public static final MageTabFileSet VALID_FEATURE_13141_INPUT_SET = getValidFeature13141InputSet(); /** * MAGE-TAB input set containing valid usage of Characteristics[ExternalSampleId] for Sample(s). */ public static final MageTabFileSet INVALID_FEATURE_13141_INPUT_SET = getInvalidFeature13141InputSet(); /** * Invalid MAGE-TAB input set containing multiple IDF files. */ public static final MageTabFileSet INVALID_DUPLICATE_TERM_SOURCES_INPUT_SET = getInvalidDuplicateTermSourcesInputSet(); /** * Document set parsed ... */ public static final MageTabFileSet DEFECT_16421 = getDefect16421ErrorInputSet(); /** * Document set parsed ... */ public static final MageTabFileSet DEFECT_17200 = getDefect17200InputSet(); /** * Document set parsed ... */ public static final MageTabFileSet DEFECT_16421_2 = getDefect16421ErrorInputSet2(); /** * MAGE-TAB input set for testing node column order validation */ public static final MageTabFileSet INVALID_NODE_ORDER_SET = getInvalidNodeOrderSet(); /** * MAGE-TAB input set for testing missing biomaterial columns validation */ public static final MageTabFileSet NO_BIOMATERIAL_SET = getNoBiomaterialSet(); /** * MAGE-TAB input set for testing missing hyb columns validation */ public static final MageTabFileSet NO_HYBRIDIZATION_SET = getNoHybridizationSet(); /** * MAGE-TAB input set for testing missing data file columns validation */ public static final MageTabFileSet NO_DATA_FILE_SET = getNoDataFileSet(); /** * MAGE-TAB input set based on the base specification set with some changes. */ public static final MageTabFileSet MAGE_TAB_SPECIFICATION_UPDATE_ANNOTATIONS_INPUT_SET = getSpecificationUpdateAnnotationsInputSet(); /** * MAGE-TAB input set based on the base specification set with some changes, as well as an additional biomaterial chain. */ public static final MageTabFileSet MAGE_TAB_SPECIFICATION_UPDATE_ANNOTATIONS_ADD_BM_INPUT_SET = getSpecificationUpdateAnnotationsAddBmInputSet(); /** * MAGE-TAB input set to use as the baseline for later changes to the biomaterial chain. */ public static final MageTabFileSet UPDATE_BIO_MATERIAL_CHAIN_BASELINE_INPUT_SET = getUpdateBioMaterialChainBaselineInputSet(); /** * MAGE-TAB input set to use to update the biomaterial chain defined in UPDATE_BIO_MATERIAL_CHAIN_BASELINE_SET. */ public static final MageTabFileSet UPDATE_BIO_MATERIAL_CHAIN_NEW_BIO_MATERIALS_INPUT_SET = getUpdateBioMaterialChainNewBioMaterialsInputSet(); /** * MAGE-TAB input set to use to add new data files to the biomaterial chain defined in UPDATE_BIO_MATERIAL_CHAIN_BASELINE_SET. */ public static final MageTabFileSet UPDATE_BIO_MATERIAL_CHAIN_NEW_DATA_FILES_INPUT_SET = getUpdateBioMaterialChainNewDataFilesInputSet(); /** * MAGE-TAB input set to use as the baseline for later changes to the files */ public static final MageTabFileSet UPDATE_FILES_BASELINE_INPUT_SET = getUpdateFilesBaselineInputSet(); /** * MAGE-TAB input set to use to add new data files to the biomaterial chain defined in UPDATE_BIO_MATERIAL_CHAIN_BASELINE_SET. */ public static final MageTabFileSet UPDATE_FILES_NEW_INPUT_SET = getUpdateFilesNewInputSet(); /** * MAGE-TAB input set containing valid usage of Characteristics[ExternalSampleId] for Sample(s). */ public static final MageTabFileSet EXTENDED_FACTOR_VALUES_INPUT_SET = getExtendedFactorValuesInputSet(); /** * MAGE-TAB input set for testing renaming of term sources upon import (GForge 27244) */ public static final MageTabFileSet RENAMING_TERM_SOURCES_INPUT_SET = getRenamingTermSourcesInputSet(); public static final MageTabFileSet MULTI_DERIVED_1_INPUT_SET = getSdrfTestInputSet(SdrfTestFiles.MULTI_DERIVED_1_IDF, SdrfTestFiles.MULTI_DERIVED_1_SDRF); public static final MageTabFileSet MULTI_NORMALIZATION_1_INPUT_SET = getSdrfTestInputSet(SdrfTestFiles.MULTI_NORMALIZATION_1_IDF, SdrfTestFiles.MULTI_NORMALIZATION_1_SDRF); public static final MageTabFileSet MULTI_NO_SCAN_1_INPUT_SET = getSdrfTestInputSet(SdrfTestFiles.MULTI_NO_SCAN_1_IDF, SdrfTestFiles.MULTI_NO_SCAN_1_SDRF); public static final MageTabFileSet MULTI_NO_SCAN_2_INPUT_SET = getSdrfTestInputSet(SdrfTestFiles.MULTI_NO_SCAN_2_IDF, SdrfTestFiles.MULTI_NO_SCAN_2_SDRF); public static final MageTabFileSet MULTI_NO_SCAN_3_INPUT_SET = getSdrfTestInputSet(SdrfTestFiles.MULTI_NO_SCAN_3_IDF, SdrfTestFiles.MULTI_NO_SCAN_3_SDRF); public static final MageTabFileSet NO_DERIVED_1_INPUT_SET = getSdrfTestInputSet(SdrfTestFiles.NO_DERIVED_1_IDF, SdrfTestFiles.NO_DERIVED_1_SDRF); public static final MageTabFileSet NO_DERIVED_2_INPUT_SET = getSdrfTestInputSet(SdrfTestFiles.NO_DERIVED_2_IDF, SdrfTestFiles.NO_DERIVED_2_SDRF); public static final MageTabFileSet NORMAL_1_INPUT_SET = getSdrfTestInputSet(SdrfTestFiles.NORMAL_1_IDF, SdrfTestFiles.NORMAL_1_SDRF); public static final MageTabFileSet NORMAL_2_INPUT_SET = getSdrfTestInputSet(SdrfTestFiles.NORMAL_2_IDF, SdrfTestFiles.NORMAL_2_SDRF); public static final MageTabFileSet NORMAL_3_INPUT_SET = getSdrfTestInputSet(SdrfTestFiles.NORMAL_3_IDF, SdrfTestFiles.NORMAL_3_SDRF); private static MageTabFileSet getValidFeature13141InputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.FEATURE_13141_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.FEATURE_13141_SDRF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.FEATURE_13141_SDRF2)); addCelFiles(fileSet, MageTabDataFiles.FEATURE_13141_DIRECTORY); return fileSet; } private static MageTabFileSet getInvalidFeature13141InputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.FEATURE_13141_INVALID_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.FEATURE_13141_INVALID_SDRF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.FEATURE_13141_INVALID_SDRF2)); addCelFiles(fileSet, MageTabDataFiles.FEATURE_13141_DIRECTORY); return fileSet; } private static MageTabFileSet getInvalidDuplicateTermSourcesInputSet() { MageTabFileSet mageTabFileSet = new MageTabFileSet(); mageTabFileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.DUPLICATE_TERM_SOURCES_INVALID_IDF)); mageTabFileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.DUPLICATE_TERM_SOURCES_INVALID_SDRF)); addCelFiles(mageTabFileSet, MageTabDataFiles.DUPLICATE_TERM_SOURCES_DIRECTORY); addChpFiles(mageTabFileSet, MageTabDataFiles.DUPLICATE_TERM_SOURCES_DIRECTORY); return mageTabFileSet; } private static MageTabFileSet getMisplacedFactorValuesInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.MISPLACED_FACTOR_VALUES_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.MISPLACED_FACTOR_VALUES_SDRF)); return fileSet; } private static MageTabFileSet getEbiTemplateInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.EBI_TEMPLATE_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.EBI_TEMPLATE_SDRF)); return fileSet; } private static MageTabFileSet getTcgaBroadInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.TCGA_BROAD_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.TCGA_BROAD_SDRF)); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.TCGA_BROAD_DATA_MATRIX)); addCelFiles(fileSet, MageTabDataFiles.TCGA_BROAD_DATA_DIRECTORY); return fileSet; } private static void addCelFiles(MageTabFileSet fileSet, File dataFileDirectory) { addDataFiles(fileSet, dataFileDirectory, "cel"); } private static void addExpFiles(MageTabFileSet fileSet, File dataFileDirectory) { addDataFiles(fileSet, dataFileDirectory, "exp"); } private static void addChpFiles(MageTabFileSet fileSet, File dataFileDirectory) { addDataFiles(fileSet, dataFileDirectory, "chp"); } private static void addDataFiles(MageTabFileSet fileSet, File dataFileDirectory, String extension) { FilenameFilter filter = createExtensionFilter(extension); File[] celFiles = dataFileDirectory.listFiles(filter); for (File file : celFiles) { fileSet.addNativeData(new JavaIOFileRef(file)); } } private static MageTabFileSet getPerformanceTest10InputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.PERFORMANCE_10_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.PERFORMANCE_10_SDRF)); addCelFiles(fileSet, MageTabDataFiles.PERFORMANCE_DIRECTORY); return fileSet; } private static MageTabFileSet getSpecificationInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_SDRF)); fileSet.addAdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_ADF)); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_DATA_MATRIX)); addCelFiles(fileSet, MageTabDataFiles.SPECIFICATION_EXAMPLE_DIRECTORY); return fileSet; } private static MageTabFileSet getSpecificationCaseSensitivityInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_CASE_SENSITIVITY_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_CASE_SENSITIVITY_SDRF)); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_CASE_SENSITIVITY_DATA_MATRIX)); addCelFiles(fileSet, MageTabDataFiles.SPECIFICATION_CASE_SENSITIVITY_DIRECTORY); return fileSet; } private static MageTabFileSet getSpecificationNoArrayDesignInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_NO_ARRAY_DESIGN_SDRF)); fileSet.addAdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_ADF)); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_DATA_MATRIX)); addCelFiles(fileSet, MageTabDataFiles.SPECIFICATION_EXAMPLE_DIRECTORY); return fileSet; } private static MageTabFileSet getSpecificationNoExpDescInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_NO_EXP_DESC_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_SDRF)); fileSet.addAdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_ADF)); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_DATA_MATRIX)); addCelFiles(fileSet, MageTabDataFiles.SPECIFICATION_EXAMPLE_DIRECTORY); return fileSet; } private static MageTabFileSet getSpecificationWithoutDataMatrixInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_SDRF)); fileSet.addAdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_EXAMPLE_ADF)); addCelFiles(fileSet, MageTabDataFiles.SPECIFICATION_EXAMPLE_DIRECTORY); return fileSet; } private static MageTabFileSet getUnsupportedDataInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.UNSUPPORTED_DATA_EXAMPLE_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.UNSUPPORTED_DATA_EXAMPLE_SDRF)); fileSet.addAdf(new JavaIOFileRef(MageTabDataFiles.UNSUPPORTED_DATA_EXAMPLE_ADF)); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.UNSUPPORTED_DATA_EXAMPLE_DATA_MATRIX)); addCelFiles(fileSet, MageTabDataFiles.UNSUPPORTED_DATA_EXAMPLE_DIRECTORY); fileSet.addNativeData(new JavaIOFileRef(new File(MageTabDataFiles.UNSUPPORTED_DATA_EXAMPLE_DIRECTORY, "unsupported.mas5.exp"))); return fileSet; } private static MageTabFileSet getGedpSpecificationInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.GEDP_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.GEDP_SDRF)); return fileSet; } private static MageTabFileSet getErrorSpecificationInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_ERROR_EXAMPLE_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_ERROR_EXAMPLE_SDRF)); return fileSet; } private static MageTabFileSet getCaarray1xInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.CAARRAY1X_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.CAARRAY1X_SDRF)); addDataFiles(fileSet, MageTabDataFiles.CAARRAY1X_DIRECTORY, "gpr"); return fileSet; } private static MageTabFileSet getGskTestSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.GSK_TEST_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.GSK_TEST_SDRF)); addCelFiles(fileSet, MageTabDataFiles.GSK_TEST_DIRECTORY); addExpFiles(fileSet, MageTabDataFiles.GSK_TEST_DIRECTORY); return fileSet; } private static MageTabFileSet getDefect12537InputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.DEFECT_12537_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.DEFECT_12537_SDRF)); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.DEFECT_12537_ABSOLUTE_DATA_MATRIX)); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.DEFECT_12537_RMA_DATA_MATRIX)); addCelFiles(fileSet, MageTabDataFiles.DEFECT_12537_DATA_DIRECTORY); return fileSet; } private static MageTabFileSet getDefect12537ErrorInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.DEFECT_12537_ERROR__IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.DEFECT_12537_ERROR_SDRF)); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.DEFECT_12537_ERROR_ABSOLUTE_DATA_MATRIX)); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.DEFECT_12537_ERROR_RMA_DATA_MATRIX)); addCelFiles(fileSet, MageTabDataFiles.DEFECT_12537_ERROR_DATA_DIRECTORY); return fileSet; } private static MageTabFileSet getDerivedDataInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_DERIVED_DATA_EXAMPLE_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_DERIVED_DATA_EXAMPLE_SDRF)); fileSet.addAdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_DERIVED_DATA_EXAMPLE_ADF)); addCelFiles(fileSet, MageTabDataFiles.SPECIFICATION_DERIVED_DATA_EXAMPLE_DIRECTORY); addChpFiles(fileSet, MageTabDataFiles.SPECIFICATION_DERIVED_DATA_EXAMPLE_DIRECTORY); return fileSet; } private static MageTabFileSet getSpecificationUpdateAnnotationsInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_UPDATE_ANNOTATIONS_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_UPDATE_ANNOTATIONS_SDRF)); return fileSet; } private static MageTabFileSet getSpecificationUpdateAnnotationsAddBmInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_UPDATE_ANNOTATIONS_ADD_NEW_BM_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_UPDATE_ANNOTATIONS_ADD_NEW_BM_SDRF)); addCelFiles(fileSet, MageTabDataFiles.SPECIFICATION_UPDATE_ANNOTATIONS_ADD_NEW_BM_DIRECTORY); fileSet.addDataMatrix(new JavaIOFileRef(MageTabDataFiles.SPECIFICATION_UPDATE_ANNOTATIONS_ADD_NEW_BM_DATA_MATRIX_FILE)); return fileSet; } private static MageTabFileSet getDefect16421ErrorInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.DEFECT_16421_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.DEFECT_16421_SDRF)); addCelFiles(fileSet, MageTabDataFiles.DEFECT_16421_CEL); return fileSet; } private static MageTabFileSet getDefect17200InputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.DEFECT_17200_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.DEFECT_17200_SDRF)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.DEFECT_17200_GPR)); fileSet.addNativeData(new JavaIOFileRef(GenepixArrayDataFiles.GPR_3_0_6)); return fileSet; } private static MageTabFileSet getDefect16421ErrorInputSet2() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.DEFECT_16421_2_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.DEFECT_16421_2_SDRF)); addCelFiles(fileSet, MageTabDataFiles.INVALID_COLUMN_ORDER_DIRECTORY); return fileSet; } private static MageTabFileSet getInvalidNodeOrderSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.INVALID_NODE_ORDER_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.INVALID_NODE_ORDER_SDRF)); addCelFiles(fileSet, MageTabDataFiles.INVALID_COLUMN_ORDER_DIRECTORY); return fileSet; } private static MageTabFileSet getNoBiomaterialSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.NO_BIOMATERIAL_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.NO_BIOMATERIAL_SDRF)); addCelFiles(fileSet, MageTabDataFiles.MISSING_COLUMNS_DIRECTORY); return fileSet; } private static MageTabFileSet getNoHybridizationSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.NO_HYBRIDIZATION_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.NO_HYBRIDIZATION_SDRF)); addCelFiles(fileSet, MageTabDataFiles.MISSING_COLUMNS_DIRECTORY); return fileSet; } private static MageTabFileSet getNoDataFileSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.NO_DATA_FILE_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.NO_DATA_FILE_SDRF)); addCelFiles(fileSet, MageTabDataFiles.MISSING_COLUMNS_DIRECTORY); return fileSet; } private static MageTabFileSet getUpdateBioMaterialChainBaselineInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_BASELINE_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_BASELINE_SDRF)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_DATA_FILE_2)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_DATA_FILE_1)); return fileSet; } private static MageTabFileSet getUpdateBioMaterialChainNewBioMaterialsInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_NEW_BIOMATERIALS_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_NEW_BIOMATERIALS_SDRF)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_DATA_FILE_3)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_DATA_FILE_4)); return fileSet; } private static MageTabFileSet getUpdateBioMaterialChainNewDataFilesInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_NEW_DATA_FILES_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_NEW_DATA_FILES_SDRF)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_BIOMATERIAL_CHAIN_DATA_FILE_1A)); return fileSet; } private static MageTabFileSet getUpdateFilesBaselineInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.UPDATE_FILES_BASELINE_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.UPDATE_FILES_BASELINE_SDRF)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_FILES_CEL2)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_FILES_CEL1)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_FILES_EXP1)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_FILES_EXP2)); return fileSet; } private static MageTabFileSet getUpdateFilesNewInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.UPDATE_FILES_NEW_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.UPDATE_FILES_NEW_SDRF)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_FILES_CEL1A)); fileSet.addNativeData(new JavaIOFileRef(MageTabDataFiles.UPDATE_FILES_EXP2A)); return fileSet; } private static FilenameFilter createExtensionFilter(final String extension) { return new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase(Locale.getDefault()).endsWith("." + extension.toLowerCase(Locale.getDefault())); } }; } public static CaArrayFileSet getFileSet(MageTabDocumentSet documentSet) { CaArrayFileSet fileSet = new CaArrayFileSet(); addFiles(fileSet, documentSet.getIdfDocuments()); addFiles(fileSet, documentSet.getSdrfDocuments()); addFiles(fileSet, documentSet.getAdfDocuments()); addFiles(fileSet, documentSet.getDataMatrixes()); addFiles(fileSet, documentSet.getNativeDataFiles()); return fileSet; } public static CaArrayFileSet getFileSet(MageTabFileSet inputSet) { CaArrayFileSet fileSet = new CaArrayFileSet(); addFiles(fileSet, inputSet.getIdfFiles(), IdfDocument.class); addFiles(fileSet, inputSet.getSdrfFiles(), SdrfDocument.class); addFiles(fileSet, inputSet.getDataMatrixFiles(), DataMatrix.class); addFiles(fileSet, inputSet.getNativeDataFiles(), NativeDataFile.class); return fileSet; } private static void addFiles(CaArrayFileSet fileSet, Collection<? extends AbstractMageTabDocument> mageTabDocuments) { for (AbstractMageTabDocument mageTabDocument : mageTabDocuments) { addFile(fileSet, mageTabDocument.getFile().getName(), mageTabDocument.getClass()); } } private static void addFiles(CaArrayFileSet fileSet, Collection<FileRef> files, Class<? extends AbstractMageTabDocument> documentType) { for (FileRef file : files) { addFile(fileSet, file.getName(), documentType); } } private static FileType guessFileType(String fileName, Class<? extends AbstractMageTabDocument> documentType) { if (IdfDocument.class.equals(documentType)) { return FileType.MAGE_TAB_IDF; } else if (SdrfDocument.class.equals(documentType)) { return FileType.MAGE_TAB_SDRF; } else if (AdfDocument.class.equals(documentType)) { return FileType.MAGE_TAB_ADF; } else if (DataMatrix.class.equals(documentType)) { return FileType.MAGE_TAB_DATA_MATRIX; } else { return FileExtension.getTypeFromExtension(fileName); } } private static void addFile(CaArrayFileSet fileSet, String name, Class<? extends AbstractMageTabDocument> documentType) { CaArrayFile caArrayFile = new CaArrayFile(); caArrayFile.setFileStatus(FileStatus.UPLOADED); caArrayFile.setName(name); caArrayFile.setFileType(guessFileType(name, documentType)); fileSet.add(caArrayFile); } private static MageTabFileSet getExtendedFactorValuesInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.EXTENDED_FACTOR_VALUES_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.EXTENDED_FACTOR_VALUES_SDRF)); addCelFiles(fileSet, MageTabDataFiles.EXTENDED_FACTOR_VALUES_DIRECTORY); return fileSet; } private static MageTabFileSet getRenamingTermSourcesInputSet() { MageTabFileSet fileSet = new MageTabFileSet(); fileSet.addIdf(new JavaIOFileRef(MageTabDataFiles.RENAMING_TERM_SOURCES_IDF)); fileSet.addSdrf(new JavaIOFileRef(MageTabDataFiles.RENAMING_TERM_SOURCES_SDRF)); addCelFiles(fileSet, MageTabDataFiles.RENAMING_TERM_SOURCES_DIRECTORY); addChpFiles(fileSet, MageTabDataFiles.RENAMING_TERM_SOURCES_DIRECTORY); return fileSet; } private static MageTabFileSet getSdrfTestInputSet(File idf, File sdrf) { MageTabFileSet mtfs = new MageTabFileSet(); mtfs.addIdf(new JavaIOFileRef(idf)); mtfs.addSdrf(new JavaIOFileRef(sdrf)); mtfs.addNativeData(new JavaIOFileRef(SdrfTestFiles.TEST_1_CEL)); mtfs.addNativeData(new JavaIOFileRef(SdrfTestFiles.TEST_2_CEL)); mtfs.addDataMatrix(new JavaIOFileRef(SdrfTestFiles.TEST_1_DATA)); mtfs.addDataMatrix(new JavaIOFileRef(SdrfTestFiles.TEST_2_DATA)); return mtfs; } }
package net.sasasin.emailchecker; import java.io.IOException; import java.net.SocketException; import java.util.List; import org.apache.commons.net.smtp.SMTPClient; import org.xbill.DNS.Record; import org.xbill.DNS.TextParseException; public class EMailChecker { public EMailChecker() { } public boolean checkAddress(String emailAddress) { String[] parts = emailAddress.split("@"); if (parts.length != 2) { return false; } String hostname = parts[1]; DnsClient dnsClient = new DnsClient(); List<Record> mailServers = null; try { mailServers = dnsClient.lookUpMx(hostname); } catch (TextParseException e) { e.printStackTrace(); return false; } if (mailServers.size() == 0) { return false; } for (Record i : mailServers) { SMTPClient client = new SMTPClient(); client.setConnectTimeout(2000); try { String mailServer = i.getAdditionalName().toString(); client.connect(mailServer); client.helo(hostname); client.setSender(emailAddress); return client.addRecipient(emailAddress); } catch (SocketException e) { System.err.println("connect to: " + i.getAdditionalName().toString()); System.err.println("check for: " + emailAddress); e.printStackTrace(); } catch (IOException e) { System.err.println("connect to: " + i.getAdditionalName().toString()); System.err.println("check for: " + emailAddress); e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } return false; } }
package com.jme3.network.kernel.tcp; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.channels.spi.SelectorProvider; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.jme3.network.Filter; import com.jme3.network.kernel.*; /** * A Kernel implementation based on NIO selectors. * * @version $Revision$ * @author Paul Speed */ public class SelectorKernel extends AbstractKernel { static Logger log = Logger.getLogger(SelectorKernel.class.getName()); private InetSocketAddress address; private SelectorThread thread; private Map<Long,NioEndpoint> endpoints = new ConcurrentHashMap<Long,NioEndpoint>(); public SelectorKernel( InetAddress host, int port ) { this( new InetSocketAddress(host, port) ); } public SelectorKernel( int port ) throws IOException { this( new InetSocketAddress(port) ); } public SelectorKernel( InetSocketAddress address ) { this.address = address; } protected SelectorThread createSelectorThread() { return new SelectorThread(); } public void initialize() { if( thread != null ) throw new IllegalStateException( "Kernel already initialized." ); thread = createSelectorThread(); try { thread.connect(); thread.start(); } catch( IOException e ) { throw new KernelException( "Error hosting:" + address, e ); } } public void terminate() throws InterruptedException { if( thread == null ) throw new IllegalStateException( "Kernel not initialized." ); try { thread.close(); thread = null; } catch( IOException e ) { throw new KernelException( "Error closing host connection:" + address, e ); } } public void broadcast( Filter<? super Endpoint> filter, ByteBuffer data, boolean reliable, boolean copy ) { if( !reliable ) throw new UnsupportedOperationException( "Unreliable send not supported by this kernel." ); if( copy ) { // Copy the data just once byte[] temp = new byte[data.remaining()]; System.arraycopy(data.array(), data.position(), temp, 0, data.remaining()); data = ByteBuffer.wrap(temp); } // Hand it to all of the endpoints that match our routing for( NioEndpoint p : endpoints.values() ) { // Does it match the filter? if( filter != null && !filter.apply(p) ) continue; // Give it the data... but let each endpoint track their // own completion over the shared array of bytes by // duplicating it p.send( data.duplicate(), false, false ); } // Wake up the selector so it can reinitialize its // state accordingly. wakeupSelector(); } protected NioEndpoint addEndpoint( SocketChannel c ) { // Note: we purposely do NOT put the key in the endpoint. // SelectionKeys are dangerous outside the selector thread // and this is safer. NioEndpoint p = new NioEndpoint( this, nextEndpointId(), c ); endpoints.put( p.getId(), p ); // Enqueue an endpoint event for the listeners addEvent( EndpointEvent.createAdd( this, p ) ); return p; } protected void removeEndpoint( NioEndpoint p, SocketChannel c ) { endpoints.remove( p.getId() ); // Enqueue an endpoint event for the listeners addEvent( EndpointEvent.createRemove( this, p ) ); // If there are no pending messages then add one so that the // kernel-user knows to wake up if it is only listening for // envelopes. if( !hasEnvelopes() ) { // Note: this is not really a race condition. At worst, our // event has already been handled by now and it does no harm // to check again. addEnvelope( EVENTS_PENDING ); } } /** * Called by the endpoints when they need to be closed. */ protected void closeEndpoint( NioEndpoint p ) throws IOException { log.log( Level.INFO, "Closing endpoint:{0}.", p ); thread.cancel(p); } /** * Used internally by the endpoints to wakeup the selector * when they have data to send. */ protected void wakeupSelector() { thread.wakeupSelector(); } protected void newData( NioEndpoint p, SocketChannel c, ByteBuffer shared, int size ) { // Note: if ever desirable, it would be possible to accumulate // data per source channel and only 'finalize' it when // asked for more envelopes then were ready. I just don't // think it will be an issue in practice. The busier the // server, the more the buffers will fill before we get to them. // And if the server isn't busy, who cares if we chop things up // smaller... the network is still likely to deliver things in // bulk anyway. // Must copy the shared data before we use it byte[] dataCopy = new byte[size]; System.arraycopy(shared.array(), 0, dataCopy, 0, size); Envelope env = new Envelope( p, dataCopy, true ); addEnvelope( env ); } /** * This class is purposely tucked neatly away because * messing with the selector from other threads for any * reason is very bad. This is the safest architecture. */ protected class SelectorThread extends Thread { private ServerSocketChannel serverChannel; private Selector selector; private AtomicBoolean go = new AtomicBoolean(true); private ByteBuffer working = ByteBuffer.allocate( 8192 ); /** * Because we want to keep the keys to ourselves, we'll do * the endpoint -> key mapping internally. */ private Map<NioEndpoint,SelectionKey> endpointKeys = new ConcurrentHashMap<NioEndpoint,SelectionKey>(); public SelectorThread() { setName( "Selector@" + address ); setDaemon(true); } public void connect() throws IOException { // Create a new selector this.selector = SelectorProvider.provider().openSelector(); // Create a new non-blocking server socket channel this.serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); // Bind the server socket to the specified address and port serverChannel.socket().bind(address); // Register the server socket channel, indicating an interest in // accepting new connections serverChannel.register(selector, SelectionKey.OP_ACCEPT); log.log( Level.INFO, "Hosting TCP connection:{0}.", address ); } public void close() throws IOException, InterruptedException { // Set the thread to stop go.set(false); // Make sure the channel is closed serverChannel.close(); // And wait for it join(); } protected void wakeupSelector() { selector.wakeup(); } protected void setupSelectorOptions() { // For now, selection keys will either be in OP_READ // or OP_WRITE. So while we are writing a buffer, we // will not be reading. This is way simpler and less // error prone... it can always be changed when everything // else works if we are looking to micro-optimize. // Setup options based on the current state of // the endpoints. This could potentially be more // efficiently done as change requests... or simply // keeping a thread-safe set of endpoints with pending // writes. For most cases, it shouldn't matter. for( Map.Entry<NioEndpoint,SelectionKey> e : endpointKeys.entrySet() ) { if( e.getKey().hasPending() ) { e.getValue().interestOps(SelectionKey.OP_WRITE); } } } protected void accept( SelectionKey key ) throws IOException { // Would only get accepts on a server channel ServerSocketChannel serverChan = (ServerSocketChannel)key.channel(); // Setup the connection to be non-blocking SocketChannel remoteChan = serverChan.accept(); remoteChan.configureBlocking(false); // And disable Nagle's buffering algorithm... we want // data to go when we put it there. Socket sock = remoteChan.socket(); sock.setTcpNoDelay(true); // Let the selector know we're interested in reading // data from the channel SelectionKey endKey = remoteChan.register( selector, SelectionKey.OP_READ ); // And now create a new endpoint NioEndpoint p = addEndpoint( remoteChan ); endKey.attach(p); endpointKeys.put(p, endKey); } protected void cancel( NioEndpoint p ) throws IOException { log.log( Level.INFO, "Closing endpoint:{0}.", p ); SelectionKey key = endpointKeys.remove(p); if( key == null ) { log.log( Level.INFO, "Endpoint already closed:{0}.", p ); return; // already closed it } SocketChannel c = (SocketChannel)key.channel(); // Note: key.cancel() is specifically thread safe. One of // the few things one can do with a key from another // thread. key.cancel(); c.close(); removeEndpoint( p, c ); } protected void cancel( SelectionKey key, SocketChannel c ) throws IOException { NioEndpoint p = (NioEndpoint)key.attachment(); log.log( Level.INFO, "Closing channel endpoint:{0}.", p ); endpointKeys.remove(p); key.cancel(); c.close(); removeEndpoint( p, c ); } protected void read( SelectionKey key ) throws IOException { NioEndpoint p = (NioEndpoint)key.attachment(); SocketChannel c = (SocketChannel)key.channel(); working.clear(); int size; try { size = c.read(working); } catch( IOException e ) { // The remove end forcibly closed the connection... // close out our end and cancel the key cancel( key, c ); return; } if( size == -1 ) { // The remote end shut down cleanly... // close out our end and cancel the key cancel( key, c ); return; } newData( p, c, working, size ); } protected void write( SelectionKey key ) throws IOException { NioEndpoint p = (NioEndpoint)key.attachment(); SocketChannel c = (SocketChannel)key.channel(); // We will send what we can and move on. ByteBuffer current = p.peekPending(); if( current == NioEndpoint.CLOSE_MARKER ) { // This connection wants to be closed now closeEndpoint(p); // Nothing more to do return; } c.write( current ); // If we wrote all of that packet then we need to remove it if( current.remaining() == 0 ) { p.removePending(); } // If we happened to empty the pending queue then let's read // again. if( !p.hasPending() ) { key.interestOps( SelectionKey.OP_READ ); } } protected void select() throws IOException { selector.select(); for( Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext(); ) { SelectionKey key = i.next(); i.remove(); if( !key.isValid() ) { // When does this happen? log.log( Level.INFO, "Key is not valid:{0}.", key ); continue; } try { if( key.isAcceptable() ) accept(key); else if( key.isWritable() ) write(key); else if( key.isReadable() ) read(key); } catch( IOException e ) { if( !go.get() ) return; // error likely due to shutting down reportError( e ); // And at this level, errors likely mean the key is now // dead and it doesn't hurt to kick them anyway. If we // find IOExceptions that are not fatal, this can be // readdressed cancel( key, (SocketChannel)key.channel() ); } } } public void run() { log.log( Level.INFO, "Kernel started for connection:{0}.", address ); // An atomic is safest and costs almost nothing while( go.get() ) { // Setup any queued option changes setupSelectorOptions(); // Check for available keys and process them try { select(); } catch( ClosedSelectorException e ) { if( !go.get() ) return; // it's because we're shutting down throw new KernelException( "Premature selector closing", e ); } catch( IOException e ) { if( !go.get() ) return; // error likely due to shutting down reportError( e ); } } } } }
package com.intellij.psi.impl.source.resolve.reference.impl.providers; import com.intellij.javaee.web.WebModuleProperties; import com.intellij.javaee.web.WebUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.jsp.JspFile; import com.intellij.psi.impl.source.jsp.JspManager; import com.intellij.psi.impl.source.jsp.JspContextManager; import com.intellij.psi.impl.source.resolve.reference.ProcessorRegistry; import com.intellij.psi.impl.source.resolve.reference.PsiReferenceProvider; import com.intellij.psi.impl.source.resolve.reference.ReferenceType; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlTagValue; import com.intellij.util.Function; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author Maxim.Mossienko */ public class FileReferenceSet { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet"); private static final char SEPARATOR = '/'; private static final String SEPARATOR_STRING = "/"; private FileReference[] myReferences; private PsiElement myElement; private final int myStartInElement; @NotNull private final ReferenceType myType; private final PsiReferenceProvider myProvider; private boolean myCaseSensitive; private String myPathString; private final boolean myAllowEmptyFileReferenceAtEnd; public static final CustomizableReferenceProvider.CustomizationKey<Function<PsiFile, PsiElement>> DEFAULT_PATH_EVALUATOR_OPTION = new CustomizableReferenceProvider.CustomizationKey<Function<PsiFile, PsiElement>>(PsiBundle.message("default.path.evaluator.option")); private @Nullable Map<CustomizableReferenceProvider.CustomizationKey, Object> myOptions; @Nullable public static FileReferenceSet createSet(PsiElement element, final boolean soft) { String text; int offset; if (element instanceof XmlAttributeValue) { text = ((XmlAttributeValue)element).getValue(); offset = 1; } else if (element instanceof XmlTag) { final XmlTag tag = ((XmlTag)element); final XmlTagValue value = tag.getValue(); final String s = value.getText(); text = s.trim(); offset = value.getTextRange().getStartOffset() + s.indexOf(text) - element.getTextOffset(); } else { return null; } if (text != null) { text = WebUtil.trimURL(text); } return new FileReferenceSet(text, element, offset, ReferenceType.FILE_TYPE, null, true) { protected boolean isSoft() { return soft; } }; } public FileReferenceSet(String str, PsiElement element, int startInElement, PsiReferenceProvider provider, final boolean isCaseSensitive) { this(str, element, startInElement, ReferenceType.FILE_TYPE, provider, isCaseSensitive, true); } public FileReferenceSet(String str, PsiElement element, int startInElement, @NotNull ReferenceType type, PsiReferenceProvider provider, final boolean isCaseSensitive) { this(str, element, startInElement, type, provider, isCaseSensitive, true); } public FileReferenceSet(String str, PsiElement element, int startInElement, @NotNull ReferenceType type, PsiReferenceProvider provider, final boolean isCaseSensitive, boolean allowEmptyFileReferenceAtEnd) { myType = type; myElement = element; myStartInElement = startInElement; myProvider = provider; myCaseSensitive = isCaseSensitive; myPathString = str.trim(); myAllowEmptyFileReferenceAtEnd = allowEmptyFileReferenceAtEnd; myOptions = provider instanceof CustomizableReferenceProvider ? ((CustomizableReferenceProvider)provider).getOptions() : null; reparse(str); } PsiElement getElement() { return myElement; } void setElement(final PsiElement element) { myElement = element; } public boolean isCaseSensitive() { return myCaseSensitive; } public void setCaseSensitive(final boolean caseSensitive) { myCaseSensitive = caseSensitive; for (FileReference ref : myReferences) { ref.clearResolveCaches(); } } int getStartInElement() { return myStartInElement; } PsiReferenceProvider getProvider() { return myProvider; } protected void reparse(String str) { final List<FileReference> referencesList = new ArrayList<FileReference>(); // skip white space int currentSlash = -1; while (currentSlash + 1 < str.length() && Character.isWhitespace(str.charAt(currentSlash + 1))) currentSlash++; if (currentSlash + 1 < str.length() && str.charAt(currentSlash + 1) == SEPARATOR) currentSlash++; int index = 0; while (true) { final int nextSlash = str.indexOf(SEPARATOR, currentSlash + 1); final String subreferenceText = nextSlash > 0 ? str.substring(currentSlash + 1, nextSlash) : str.substring(currentSlash + 1); if (subreferenceText.length() > 0 || myAllowEmptyFileReferenceAtEnd) { // ? check at end FileReference currentContextRef = new FileReference(this, new TextRange(myStartInElement + currentSlash + 1, myStartInElement + ( nextSlash > 0 ? nextSlash : str.length())), index++, subreferenceText); referencesList.add(currentContextRef); } if ((currentSlash = nextSlash) < 0) { break; } } setReferences(referencesList.toArray(new FileReference[referencesList.size()])); } protected void setReferences(final FileReference[] references) { myReferences = references; } public FileReference getReference(int index) { return myReferences[index]; } @NotNull public FileReference[] getAllReferences() { return myReferences; } @NotNull ReferenceType getType(int index) { if (index != myReferences.length - 1) { return new ReferenceType(new int[]{myType.getPrimitives()[0], ReferenceType.WEB_DIRECTORY_ELEMENT, ReferenceType.DIRECTORY}); } return myType; } protected boolean isSoft() { return false; } @NotNull public Collection<PsiElement> getDefaultContexts(PsiElement element) { Project project = element.getProject(); PsiFile file = element.getContainingFile(); if (file == null) { LOG.assertTrue(false, "Invalid element: " + element); } if (!file.isPhysical()) file = file.getOriginalFile(); if (file == null) return Collections.emptyList(); if (myOptions != null) { final Function<PsiFile, PsiElement> value = DEFAULT_PATH_EVALUATOR_OPTION.getValue(myOptions); if (value != null) { final PsiElement result = value.fun(file); return result == null ? Collections.<PsiElement>emptyList() : Collections.singleton(result); } } final WebModuleProperties properties = WebUtil.getWebModuleProperties(file); PsiElement result = null; if (isAbsolutePathReference()) { result = getAbsoluteTopLevelDirLocation(properties, project, file); } else { JspFile jspFile = PsiUtil.getJspFile(file); if (jspFile != null) { final JspContextManager manager = JspContextManager.getInstance(project); JspFile contextFile = manager.getContextFile(jspFile); Set<JspFile> visited = new HashSet<JspFile>(); while (contextFile != null && !visited.contains(jspFile)) { visited.add(jspFile); jspFile = contextFile; contextFile = manager.getContextFile(jspFile); } file = jspFile; } final PsiDirectory dir = file.getContainingDirectory(); if (dir != null) { if (properties != null) { result = JspManager.getInstance(project).findWebDirectoryByFile(dir.getVirtualFile(), properties); if (result == null) result = dir; } else { result = dir; } } } return result == null ? Collections.<PsiElement>emptyList() : Collections.singleton(result); } public boolean isAbsolutePathReference() { return myPathString.startsWith(SEPARATOR_STRING); } @Nullable public static PsiElement getAbsoluteTopLevelDirLocation(final WebModuleProperties properties, final Project project, final PsiFile file) { PsiElement result = null; if (properties != null) { result = JspManager.getInstance(project).findWebDirectoryElementByPath("/", properties); } else { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { final VirtualFile contentRootForFile = ProjectRootManager.getInstance(project).getFileIndex() .getContentRootForFile(virtualFile); if (contentRootForFile != null) { result = PsiManager.getInstance(project).findDirectory(contentRootForFile); } } } return result; } protected PsiScopeProcessor createProcessor(final List result, ReferenceType type) throws ProcessorRegistry.IncompatibleReferenceTypeException { return ProcessorRegistry.getProcessorByType(type, result, null); } public <Option> void addCustomization(CustomizableReferenceProvider.CustomizationKey<Option> key, Option value) { if (myOptions == null) { myOptions = new HashMap<CustomizableReferenceProvider.CustomizationKey, Object>(5); } myOptions.put(key,value); } }
package edu.umd.cs.findbugs.ba.npe; import java.util.BitSet; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.CodeExceptionGen; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.MethodGen; import org.apache.bcel.generic.ObjectType; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.Nullable; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.AnalysisFeatures; import edu.umd.cs.findbugs.ba.AssertionMethods; import edu.umd.cs.findbugs.ba.BasicBlock; 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.Dataflow; import edu.umd.cs.findbugs.ba.DataflowAnalysisException; import edu.umd.cs.findbugs.ba.DataflowTestDriver; import edu.umd.cs.findbugs.ba.DepthFirstSearch; import edu.umd.cs.findbugs.ba.Edge; import edu.umd.cs.findbugs.ba.EdgeTypes; import edu.umd.cs.findbugs.ba.FrameDataflowAnalysis; import edu.umd.cs.findbugs.ba.JavaClassAndMethod; import edu.umd.cs.findbugs.ba.Location; import edu.umd.cs.findbugs.ba.NullnessAnnotation; import edu.umd.cs.findbugs.ba.NullnessAnnotationDatabase; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.ba.XMethodParameter; import edu.umd.cs.findbugs.ba.vna.ValueNumber; import edu.umd.cs.findbugs.ba.vna.ValueNumberDataflow; import edu.umd.cs.findbugs.ba.vna.ValueNumberFrame; /** * A dataflow analysis to detect potential null pointer dereferences. * * @author David Hovemeyer * @see IsNullValue * @see IsNullValueFrame * @see IsNullValueFrameModelingVisitor */ public class IsNullValueAnalysis extends FrameDataflowAnalysis<IsNullValue, IsNullValueFrame> implements EdgeTypes, IsNullValueAnalysisFeatures { static final boolean DEBUG = SystemProperties.getBoolean("inva.debug"); static { if (DEBUG) System.out.println("inva.debug enabled"); } private MethodGen methodGen; private IsNullValueFrameModelingVisitor visitor; private ValueNumberDataflow vnaDataflow; private int[] numNonExceptionSuccessorMap; private Set<LocationWhereValueBecomesNull> locationWhereValueBecomesNullSet; private final boolean trackValueNumbers; private IsNullValueFrame lastFrame; private IsNullValueFrame instanceOfFrame; private IsNullValueFrame cachedEntryFact; private JavaClassAndMethod classAndMethod; public IsNullValueAnalysis(MethodGen methodGen, CFG cfg, ValueNumberDataflow vnaDataflow, DepthFirstSearch dfs, AssertionMethods assertionMethods) { super(dfs); this.trackValueNumbers = AnalysisContext.currentAnalysisContext().getBoolProperty( AnalysisFeatures.TRACK_VALUE_NUMBERS_IN_NULL_POINTER_ANALYSIS); this.methodGen = methodGen; this.visitor = new IsNullValueFrameModelingVisitor( methodGen.getConstantPool(), assertionMethods, vnaDataflow, trackValueNumbers); this.vnaDataflow = vnaDataflow; this.numNonExceptionSuccessorMap = new int[cfg.getNumBasicBlocks()]; this.locationWhereValueBecomesNullSet = new HashSet<LocationWhereValueBecomesNull>(); // For each basic block, calculate the number of non-exception successors. Iterator<Edge> i = cfg.edgeIterator(); while (i.hasNext()) { Edge edge = i.next(); if (edge.isExceptionEdge()) continue; int srcBlockId = edge.getSource().getId(); numNonExceptionSuccessorMap[srcBlockId]++; } } public void setClassAndMethod(JavaClassAndMethod classAndMethod) { this.classAndMethod = classAndMethod; } public JavaClassAndMethod getClassAndMethod( ) { return classAndMethod; } public IsNullValueFrame createFact() { return new IsNullValueFrame(methodGen.getMaxLocals(), trackValueNumbers); } public void initEntryFact(IsNullValueFrame result) { if (cachedEntryFact == null) { cachedEntryFact = createFact(); cachedEntryFact.setValid(); int numLocals = methodGen.getMaxLocals(); boolean instanceMethod = !methodGen.isStatic(); XMethod xm = XFactory.createXMethod(methodGen.getClassName(), methodGen.getName(), methodGen.getSignature(), methodGen.isStatic()); NullnessAnnotationDatabase db = AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase(); int paramShift = instanceMethod ? 1 : 0; for (int i = 0; i < numLocals; ++i) { IsNullValue value; int paramIndex = i - paramShift; if (instanceMethod && i == 0) { value = IsNullValue.nonNullValue(); } else if (paramIndex >= methodGen.getArgumentTypes().length) { value = IsNullValue.nonReportingNotNullValue(); } else { XMethodParameter methodParameter = new XMethodParameter(xm, paramIndex); NullnessAnnotation n = db.getResolvedAnnotation(methodParameter, false); if (n == NullnessAnnotation.CHECK_FOR_NULL) // Parameter declared @CheckForNull value = IsNullValue.parameterMarkedAsMightBeNull(methodParameter); else if (n == NullnessAnnotation.NONNULL) // Parameter declared @NonNull // TODO: label this so we don't report defensive programming value = IsNullValue.nonNullValue(); else // Don't know; use default value, normally non-reporting nonnull value = IsNullValue.nonReportingNotNullValue(); } cachedEntryFact.setValue(i, value); } } copy(cachedEntryFact, result); } @Override public void transfer(BasicBlock basicBlock, InstructionHandle end, IsNullValueFrame start, IsNullValueFrame result) throws DataflowAnalysisException { startTransfer(); super.transfer(basicBlock, end, start, result); endTransfer(basicBlock, end, result); } public void startTransfer() throws DataflowAnalysisException { lastFrame = null; instanceOfFrame = null; } public void endTransfer(BasicBlock basicBlock, InstructionHandle end, IsNullValueFrame result) throws DataflowAnalysisException { // Determine if this basic block ends in a redundant branch. if (end == null) { if (lastFrame == null) result.setDecision(null); else { IsNullConditionDecision decision = getDecision(basicBlock, lastFrame); //if (DEBUG) System.out.println("Decision=" + decision); result.setDecision(decision); } } lastFrame = null; instanceOfFrame = null; } @Override public void transferInstruction(InstructionHandle handle, BasicBlock basicBlock, IsNullValueFrame fact) throws DataflowAnalysisException { // If this is the last instruction in the block, // save the result immediately before the instruction. if (handle == basicBlock.getLastInstruction()) { lastFrame = createFact(); lastFrame.copyFrom(fact); } if (handle.getInstruction().getOpcode() == Constants.INSTANCEOF) { instanceOfFrame = createFact(); instanceOfFrame.copyFrom(fact); } // Model the instruction visitor.setFrameAndLocation(fact, new Location(handle, basicBlock)); Instruction ins = handle.getInstruction(); visitor.analyzeInstruction(ins); // Special case: // The instruction may have produced previously seen values // about which new is-null information is known. // If any other instances of the produced values exist, // update their is-null information. // Also, make a note of any newly-produced null values. int numProduced = ins.produceStack(methodGen.getConstantPool()); if (numProduced == Constants.UNPREDICTABLE) throw new DataflowAnalysisException("Unpredictable stack production", methodGen, handle); int start = fact.getNumSlots() - numProduced; Location location = new Location(handle, basicBlock); ValueNumberFrame vnaFrameAfter = vnaDataflow.getFactAfterLocation(location); for (int i = start; i < fact.getNumSlots(); ++i) { ValueNumber value = vnaFrameAfter.getValue(i); IsNullValue isNullValue = fact.getValue(i); for (int j = 0; j < start; ++j) { ValueNumber otherValue = vnaFrameAfter.getValue(j); if (value.equals(otherValue)) { // Same value is in both slots. // Update the is-null information to match // the new information. fact.setValue(j, isNullValue); } } } if (visitor.getSlotContainingNewNullValue() >= 0) { ValueNumber newNullValue = vnaFrameAfter.getValue(visitor.getSlotContainingNewNullValue()); addLocationWhereValueBecomesNull(new LocationWhereValueBecomesNull( location, newNullValue //handle )); } } private static final BitSet nullComparisonInstructionSet = new BitSet(); static { nullComparisonInstructionSet.set(Constants.IFNULL); nullComparisonInstructionSet.set(Constants.IFNONNULL); nullComparisonInstructionSet.set(Constants.IF_ACMPEQ); nullComparisonInstructionSet.set(Constants.IF_ACMPNE); } public void meetInto(IsNullValueFrame fact, Edge edge, IsNullValueFrame result) throws DataflowAnalysisException { if (fact.isValid()) { IsNullValueFrame tmpFact = null; final int numSlots = fact.getNumSlots(); if (!NO_SPLIT_DOWNGRADE_NSP) { // Downgrade NSP to DNR on non-exception control splits if (!edge.isExceptionEdge() && numNonExceptionSuccessorMap[edge.getSource().getId()] > 1) { tmpFact = modifyFrame(fact, tmpFact); tmpFact.downgradeOnControlSplit(); } } if (!NO_SWITCH_DEFAULT_AS_EXCEPTION) { if (edge.getType() == SWITCH_DEFAULT_EDGE) { tmpFact = modifyFrame(fact, tmpFact); tmpFact.toExceptionValues(); } } final BasicBlock destBlock = edge.getTarget(); if (destBlock.isExceptionHandler()) { // Exception handler - clear stack and push a non-null value // to represent the exception. tmpFact = modifyFrame(fact, tmpFact); tmpFact.clearStack(); // Downgrade NULL and NSP to DNR if the handler is for // CloneNotSupportedException or InterruptedException if (false) { CodeExceptionGen handler = destBlock.getExceptionGen(); ObjectType catchType = handler.getCatchType(); if (catchType != null) { String catchClass = catchType.getClassName(); if (catchClass.equals("java.lang.CloneNotSupportedException") || catchClass.equals("java.lang.InterruptedException")) { for (int i = 0; i < tmpFact.getNumSlots(); ++i) { IsNullValue value = tmpFact.getValue(i); if (value.isDefinitelyNull() || value.isNullOnSomePath()) tmpFact.setValue(i, IsNullValue.nullOnComplexPathValue()); } } } } // Mark all values as having occurred on an exception path tmpFact.toExceptionValues(); // Push the exception value tmpFact.pushValue(IsNullValue.nonNullValue()); } else { final int edgeType = edge.getType(); final BasicBlock sourceBlock = edge.getSource(); final BasicBlock targetBlock = edge.getTarget(); final ValueNumberFrame targetVnaFrame = vnaDataflow.getStartFact(destBlock); assert targetVnaFrame != null; // Determine if the edge conveys any information about the // null/non-null status of operands in the incoming frame. if (edgeType == IFCMP_EDGE || edgeType == FALL_THROUGH_EDGE) { IsNullConditionDecision decision = getResultFact(edge.getSource()).getDecision(); if (decision != null) { if (!decision.isEdgeFeasible(edgeType)) { // The incoming edge is infeasible; just use TOP // as the start fact for this block. tmpFact = createFact(); tmpFact.setTop(); } else if (decision.getValue() != null) { // A value has been determined for this edge. // Use the value to update the is-null information in // the start fact for this block. final Location atIf = new Location(sourceBlock.getLastInstruction(), sourceBlock); // TODO: prevIsNullValueFrame is not used final IsNullValueFrame prevIsNullValueFrame = getFactAtLocation(atIf); final ValueNumberFrame prevVnaFrame = vnaDataflow.getFactAtLocation(atIf); IsNullValue decisionValue = decision.getDecision(edgeType); if (decisionValue != null && decisionValue.isDefinitelyNull()) { // Make a note of the value that has become null // due to the if comparison. addLocationWhereValueBecomesNull(new LocationWhereValueBecomesNull( atIf, decision.getValue() )); } tmpFact = replaceValues(fact, tmpFact, decision.getValue(), prevVnaFrame, targetVnaFrame, decisionValue); } } } // If this is a fall-through edge from a null check, // then we know the value checked is not null. if (sourceBlock.isNullCheck() && edgeType == FALL_THROUGH_EDGE) { ValueNumberFrame vnaFrame = vnaDataflow.getStartFact(destBlock); if (vnaFrame == null) throw new IllegalStateException("no vna frame at block entry?"); Instruction firstInDest = edge.getTarget().getFirstInstruction().getInstruction(); IsNullValue instance = fact.getInstance(firstInDest, methodGen.getConstantPool()); if (instance.isDefinitelyNull()) { // If we know the variable is null, this edge is infeasible tmpFact = createFact(); tmpFact.setTop(); } else if (!instance.isDefinitelyNotNull()) { // If we're not sure that the instance is definitely non-null, // update the is-null information for the dereferenced value. InstructionHandle kaBoomLocation = targetBlock.getFirstInstruction(); ValueNumber replaceMe = vnaFrame.getInstance(firstInDest, methodGen.getConstantPool()); tmpFact = replaceValues(fact, tmpFact, replaceMe, vnaFrame, targetVnaFrame, IsNullValue.noKaboomNonNullValue( new Location(kaBoomLocation, targetBlock) )); } } } if (tmpFact != null) fact = tmpFact; } // Normal dataflow merge mergeInto(fact, result); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.ba.FrameDataflowAnalysis#mergeInto(edu.umd.cs.findbugs.ba.Frame, edu.umd.cs.findbugs.ba.Frame) */ @Override protected void mergeInto(IsNullValueFrame other, IsNullValueFrame result) throws DataflowAnalysisException { super.mergeInto(other, result); if (trackValueNumbers) { result.mergeKnownValuesWith(other); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.ba.AbstractDataflowAnalysis#startIteration() */ @Override public void startIteration() { // At the beginning of each iteration, clear the set of locations // where values become null. That way, after the final iteration // of dataflow analysis the set should be as accurate as possible. locationWhereValueBecomesNullSet.clear(); } public void addLocationWhereValueBecomesNull(LocationWhereValueBecomesNull locationWhereValueBecomesNull) { // System.out.println("Location becomes null: " + locationWhereValueBecomesNull ); locationWhereValueBecomesNullSet.add(locationWhereValueBecomesNull); } public Set<LocationWhereValueBecomesNull> getLocationWhereValueBecomesNullSet() { return locationWhereValueBecomesNullSet; } @Override protected void mergeValues(IsNullValueFrame otherFrame, IsNullValueFrame resultFrame, int slot) throws DataflowAnalysisException { IsNullValue value = IsNullValue.merge(resultFrame.getValue(slot), otherFrame.getValue(slot)); resultFrame.setValue(slot, value); } /** * Determine if the given basic block ends in a redundant * null comparison. * * @param basicBlock the basic block * @param lastFrame the IsNullValueFrame representing values at the final instruction * of the block * @return an IsNullConditionDecision object representing the * is-null information gained about the compared value, * or null if no information is gained */ private IsNullConditionDecision getDecision(BasicBlock basicBlock, IsNullValueFrame lastFrame) throws DataflowAnalysisException { assert lastFrame != null; final InstructionHandle lastInSourceHandle = basicBlock.getLastInstruction(); if (lastInSourceHandle == null) return null; // doesn't end in null comparison final short lastInSourceOpcode = lastInSourceHandle.getInstruction().getOpcode(); // System.out.println("last opcode: " + Constants.OPCODE_NAMES[lastInSourceOpcode]); if (lastInSourceOpcode == Constants.IFEQ || lastInSourceOpcode == Constants.IFNE ) { InstructionHandle prev = lastInSourceHandle.getPrev(); if (prev == null) return null; short secondToLastOpcode = prev.getInstruction().getOpcode(); // System.out.println("Second last opcode: " + Constants.OPCODE_NAMES[secondToLastOpcode]); if (secondToLastOpcode != Constants.INSTANCEOF) return null; IsNullValue tos = instanceOfFrame.getTopValue(); boolean isNotInstanceOf = (lastInSourceOpcode != Constants.IFNE); Location atInstanceOf = new Location(prev, basicBlock); ValueNumberFrame instanceOfVnaFrame = vnaDataflow.getFactAtLocation(atInstanceOf); // Initially, assume neither branch is feasible. IsNullValue ifcmpDecision = null; IsNullValue fallThroughDecision = null; if (tos.isDefinitelyNull()) { // Predetermined comparison - one branch is infeasible if (isNotInstanceOf) ifcmpDecision =tos; else // ifnonnull fallThroughDecision = tos; } else if (tos.isDefinitelyNotNull()) { return null; } else { // As far as we know, both branches feasible ifcmpDecision = isNotInstanceOf ? tos : IsNullValue.pathSensitiveNonNullValue(); fallThroughDecision = isNotInstanceOf ? IsNullValue.pathSensitiveNonNullValue() : tos; } if (DEBUG) System.out.println("Checking..." + tos + " -> " + ifcmpDecision + " or " + fallThroughDecision); return new IsNullConditionDecision(instanceOfVnaFrame.getTopValue(), ifcmpDecision, fallThroughDecision); } if (!nullComparisonInstructionSet.get(lastInSourceOpcode)) return null; // doesn't end in null comparison Location atIf = new Location(lastInSourceHandle, basicBlock); ValueNumberFrame prevVnaFrame = vnaDataflow.getFactAtLocation(atIf); switch (lastInSourceOpcode) { case Constants.IFNULL: case Constants.IFNONNULL: { IsNullValue tos = lastFrame.getTopValue(); boolean ifnull = (lastInSourceOpcode == Constants.IFNULL); // Initially, assume neither branch is feasible. IsNullValue ifcmpDecision = null; IsNullValue fallThroughDecision = null; if (tos.isDefinitelyNull()) { // Predetermined comparison - one branch is infeasible if (ifnull) ifcmpDecision = IsNullValue.pathSensitiveNullValue(); else // ifnonnull fallThroughDecision = IsNullValue.pathSensitiveNullValue(); } else if (tos.isDefinitelyNotNull()) { // Predetermined comparison - one branch is infeasible if (ifnull) fallThroughDecision = IsNullValue.pathSensitiveNonNullValue(); else // ifnonnull ifcmpDecision = IsNullValue.pathSensitiveNonNullValue(); } else { // As far as we know, both branches feasible ifcmpDecision = ifnull ? IsNullValue.pathSensitiveNullValue() : IsNullValue.pathSensitiveNonNullValue(); fallThroughDecision = ifnull ? IsNullValue.pathSensitiveNonNullValue() : IsNullValue.pathSensitiveNullValue(); } return new IsNullConditionDecision(prevVnaFrame.getTopValue(), ifcmpDecision, fallThroughDecision); } case Constants.IF_ACMPEQ: case Constants.IF_ACMPNE: { IsNullValue tos = lastFrame.getStackValue(0); IsNullValue nextToTos = lastFrame.getStackValue(1); boolean tosNull = tos.isDefinitelyNull(); boolean nextToTosNull = nextToTos.isDefinitelyNull(); boolean cmpeq = (lastInSourceOpcode == Constants.IF_ACMPEQ); // Initially, assume neither branch is feasible. IsNullValue ifcmpDecision = null; IsNullValue fallThroughDecision = null; ValueNumber value; if (tosNull && nextToTosNull) { // Redundant comparision: both values are null, only one branch is feasible value = null; // no value will be replaced - just want to indicate that one of the branches is infeasible if (cmpeq) ifcmpDecision = IsNullValue.pathSensitiveNullValue(); else // cmpne fallThroughDecision = IsNullValue.pathSensitiveNullValue(); } else if (tosNull || nextToTosNull) { // We have updated information about whichever value is not null; // both branches are feasible value = prevVnaFrame.getStackValue(tosNull ? 1 : 0); ifcmpDecision = cmpeq ? IsNullValue.pathSensitiveNullValue() : IsNullValue.pathSensitiveNonNullValue(); fallThroughDecision = cmpeq ? IsNullValue.pathSensitiveNonNullValue() : IsNullValue.pathSensitiveNullValue(); } else if (tos.isDefinitelyNotNull() && !nextToTos.isDefinitelyNotNull()) { // learn that nextToTos is definitely non null on one branch value = prevVnaFrame.getStackValue(1); if (cmpeq) { ifcmpDecision = tos; fallThroughDecision = nextToTos; } else { fallThroughDecision = tos; ifcmpDecision = nextToTos; } } else if (!tos.isDefinitelyNotNull() && nextToTos.isDefinitelyNotNull()) { // learn that tos is definitely non null on one branch value = prevVnaFrame.getStackValue(0); if (cmpeq) { ifcmpDecision = nextToTos; fallThroughDecision = tos; } else { fallThroughDecision = nextToTos; ifcmpDecision = tos; } } else { // No information gained break; } return new IsNullConditionDecision(value, ifcmpDecision, fallThroughDecision); } default: throw new IllegalStateException(); } return null; // no information gained } /** * Update is-null information at a branch target based on information gained at a * null comparison branch. * * @param origFrame the original is-null frame at entry to basic block * @param frame the modified version of the is-null entry frame; * null if the entry frame has not been modified yet * @param replaceMe the ValueNumber in the value number frame at the if comparison * whose is-null information will be updated * @param prevVnaFrame the ValueNumberFrame at the if comparison * @param targetVnaFrame the ValueNumberFrame at entry to the basic block * @param replacementValue the IsNullValue representing the updated * is-null information * @return a modified IsNullValueFrame with updated is-null information */ private IsNullValueFrame replaceValues(IsNullValueFrame origFrame, IsNullValueFrame frame, ValueNumber replaceMe, ValueNumberFrame prevVnaFrame, ValueNumberFrame targetVnaFrame, IsNullValue replacementValue) { // If required, make a copy of the frame frame = modifyFrame(origFrame, frame); assert frame.getNumSlots() == targetVnaFrame.getNumSlots(); // The VNA frame may have more slots than the IsNullValueFrame // if it was produced by an IF comparison (whose operand or operands // are subsequently popped off the stack). final int targetNumSlots = targetVnaFrame.getNumSlots(); final int prefixNumSlots = Math.min(frame.getNumSlots(), prevVnaFrame.getNumSlots()); if (trackValueNumbers) { frame.setKnownValue(replaceMe, replacementValue); } // Here's the deal: // - "replaceMe" is the value number from the previous frame (at the if branch) // which indicates a value that we have updated is-null information about // - in the target value number frame (at entry to the target block), // we find the value number in the stack slot corresponding to the "replaceMe" // value; this is the "corresponding" value // - all instances of the "corresponding" value in the target frame have // their is-null information updated to "replacementValue" // This should thoroughly make use of the updated information. for (int i = 0; i < prefixNumSlots; ++i) { if (prevVnaFrame.getValue(i).equals(replaceMe)) { ValueNumber corresponding = targetVnaFrame.getValue(i); for (int j = 0; j < targetNumSlots; ++j) { if (targetVnaFrame.getValue(j).equals(corresponding)) frame.setValue(j, replacementValue); } } } return frame; } /** * Test driver. */ public static void main(String[] argv) throws Exception { if (argv.length != 1) { System.err.println("Usage: " + IsNullValueAnalysis.class.getName() + " <class file>"); System.exit(1); } DataflowTestDriver<IsNullValueFrame, IsNullValueAnalysis> driver = new DataflowTestDriver<IsNullValueFrame, IsNullValueAnalysis>() { @Override public Dataflow<IsNullValueFrame, IsNullValueAnalysis> createDataflow(ClassContext classContext, Method method) throws CFGBuilderException, DataflowAnalysisException { return classContext.getIsNullValueDataflow(method); } }; driver.execute(argv[0]); } } // vim:ts=4
package edu.umd.cs.findbugs.visitclass; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.InnerClass; import org.apache.bcel.classfile.InnerClasses; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LineNumber; import org.apache.bcel.classfile.LineNumberTable; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.Method; public abstract class PreorderVisitor extends BetterVisitor implements Constants2 { // Available when visiting a class private ConstantPool constantPool; private JavaClass thisClass; private String className = "none"; private String dottedClassName = "none"; private String packageName = "none"; private String sourceFile = "none"; private String superclassName = "none"; private String dottedSuperclassName = "none"; // Available when visiting a method private boolean visitingMethod = false; private String methodSig = "none"; private String dottedMethodSig = "none"; private Method method = null; private String methodName = "none"; private String fullyQualifiedMethodName = "none"; // Available when visiting a field private Field field; private boolean visitingField = false; private String fullyQualifiedFieldName = "none"; private String fieldName = "none"; private String fieldSig = "none"; private String dottedFieldSig = "none"; private boolean fieldIsStatic; // Available when visiting a Code private Code code; protected String getStringFromIndex(int i) { ConstantUtf8 name = (ConstantUtf8) constantPool.getConstant(i); return name.getBytes(); } protected int asUnsignedByte(byte b) { return 0xff & b; } /** * Return the current Code attribute; assuming one is being visited * @return current code attribute */ public Code getCode() { if (code == null) throw new IllegalStateException("Not visiting Code"); return code; } /** * Get lines of code in try block that surround pc * @param pc * @return number of lines of code in try block */ public int getSizeOfSurroundingTryBlock(int pc) { if (code == null) throw new IllegalStateException("Not visiting Code"); int size = Integer.MAX_VALUE; int tightStartPC = 0; int tightEndPC = Integer.MAX_VALUE; if (code.getExceptionTable() == null) return size; for (CodeException catchBlock : code.getExceptionTable()) { int startPC = catchBlock.getStartPC(); int endPC = catchBlock.getEndPC(); if (pc >= startPC && pc <= endPC) { int thisSize = endPC - startPC; if (size > thisSize) { size = thisSize; tightStartPC = startPC; tightEndPC = endPC; } } } if (size < Integer.MAX_VALUE) { if (code.getLineNumberTable() == null) return size; int firstLineNumber = code.getLineNumberTable().getSourceLine(tightStartPC); int lastLineNumber = code.getLineNumberTable().getSourceLine(tightEndPC); int diff = lastLineNumber - firstLineNumber + 1; if (diff >= size && diff <= size/8) return diff; } return size / 8; } // Attributes public void visitCode(Code obj) { code = obj; super.visitCode(obj); CodeException[] exceptions = obj.getExceptionTable(); for (CodeException exception : exceptions) exception.accept(this); Attribute[] attributes = obj.getAttributes(); for (Attribute attribute : attributes) attribute.accept(this); code = null; } // Constants public void visitConstantPool(ConstantPool obj) { super.visitConstantPool(obj); Constant[] constant_pool = obj.getConstantPool(); for (int i = 1; i < constant_pool.length; i++) { constant_pool[i].accept(this); byte tag = constant_pool[i].getTag(); if ((tag == CONSTANT_Double) || (tag == CONSTANT_Long)) i++; } } private void doVisitField(Field field) { if (visitingField) throw new IllegalStateException("visitField called when already visiting a field"); visitingField = true; this.field = field; try { fieldName = getStringFromIndex(field.getNameIndex()); fieldSig = getStringFromIndex(field.getSignatureIndex()); dottedFieldSig = fieldSig.replace('/', '.'); fullyQualifiedFieldName = dottedClassName + "." + fieldName + " : " + dottedFieldSig; fieldIsStatic = field.isStatic(); field.accept(this); Attribute[] attributes = field.getAttributes(); for (Attribute attribute : attributes) attribute.accept(this); } finally { visitingField = false; this.field = null; } } public void doVisitMethod(Method method) { if (visitingMethod) throw new IllegalStateException("doVisitMethod called when already visiting a method"); visitingMethod = true; try { this.method = method; methodName = getStringFromIndex(method.getNameIndex()); methodSig = getStringFromIndex(method.getSignatureIndex()); dottedMethodSig = methodSig.replace('/', '.'); StringBuffer ref = new StringBuffer(5 + dottedClassName.length() + methodName.length() + dottedMethodSig.length()); ref.append(dottedClassName) .append(".") .append(methodName) .append(" : ") .append(dottedMethodSig); fullyQualifiedMethodName = ref.toString(); this.method.accept(this); Attribute[] attributes = method.getAttributes(); for (Attribute attribute : attributes) attribute.accept(this); } finally { visitingMethod = false; } } // Extra classes (i.e. leaves in this context) public void visitInnerClasses(InnerClasses obj) { super.visitInnerClasses(obj); InnerClass[] inner_classes = obj.getInnerClasses(); for (InnerClass inner_class : inner_classes) inner_class.accept(this); } public void visitAfter(JavaClass obj) { } // General classes public void visitJavaClass(JavaClass obj) { setupVisitorForClass(obj); constantPool.accept(this); Field[] fields = obj.getFields(); Method[] methods = obj.getMethods(); Attribute[] attributes = obj.getAttributes(); for (Field field : fields) doVisitField(field); for (Method method1 : methods) doVisitMethod(method1); for (Attribute attribute : attributes) attribute.accept(this); visitAfter(obj); } public void setupVisitorForClass(JavaClass obj) { constantPool = obj.getConstantPool(); thisClass = obj; ConstantClass c = (ConstantClass) constantPool.getConstant(obj.getClassNameIndex()); className = getStringFromIndex(c.getNameIndex()); dottedClassName = className.replace('/', '.'); packageName = obj.getPackageName(); sourceFile = obj.getSourceFileName(); superclassName = obj.getSuperclassName(); dottedSuperclassName = superclassName.replace('/', '.'); super.visitJavaClass(obj); } public void visitLineNumberTable(LineNumberTable obj) { super.visitLineNumberTable(obj); LineNumber[] line_number_table = obj.getLineNumberTable(); for (LineNumber aLine_number_table : line_number_table) aLine_number_table.accept(this); } public void visitLocalVariableTable(LocalVariableTable obj) { super.visitLocalVariableTable(obj); LocalVariable[] local_variable_table = obj.getLocalVariableTable(); for (LocalVariable aLocal_variable_table : local_variable_table) aLocal_variable_table.accept(this); } // Accessors /** Get the constant pool for the current or most recently visited class */ public ConstantPool getConstantPool() { return constantPool; } /** Get the slash-formatted class name for the current or most recently visited class */ public String getClassName() { return className; } /** Get the dotted class name for the current or most recently visited class */ public String getDottedClassName() { return dottedClassName; } /** Get the (slash-formatted?) package name for the current or most recently visited class */ public String getPackageName() { return packageName; } /** Get the source file name for the current or most recently visited class */ public String getSourceFile() { return sourceFile; } /** Get the slash-formatted superclass name for the current or most recently visited class */ public String getSuperclassName() { return superclassName; } /** Get the dotted superclass name for the current or most recently visited class */ public String getDottedSuperclassName() { return dottedSuperclassName; } /** Get the JavaClass object for the current or most recently visited class */ public JavaClass getThisClass() { return thisClass; } /** If currently visiting a method, get the method's fully qualified name */ public String getFullyQualifiedMethodName() { if (!visitingMethod) throw new IllegalStateException("getFullyQualifiedMethodName called while not visiting method"); return fullyQualifiedMethodName; } /** * is the visitor currently visiting a method? */ public boolean visitingMethod() { return visitingMethod; } /** * is the visitor currently visiting a field? */ public boolean visitingField() { return visitingField; } /** If currently visiting a method, get the method's Method object */ public Field getField() { if (!visitingField) throw new IllegalStateException("getField called while not visiting method"); return field; } /** If currently visiting a method, get the method's Method object */ public Method getMethod() { if (!visitingMethod) throw new IllegalStateException("getMethod called while not visiting method"); return method; } /** If currently visiting a method, get the method's name */ public String getMethodName() { if (!visitingMethod) throw new IllegalStateException("getMethodName called while not visiting method"); return methodName; } /** If currently visiting a method, get the method's slash-formatted signature */ public String getMethodSig() { if (!visitingMethod) throw new IllegalStateException("getMethodSig called while not visiting method"); return methodSig; } /** If currently visiting a method, get the method's dotted method signature */ public String getDottedMethodSig() { if (!visitingMethod) throw new IllegalStateException("getDottedMethodSig called while not visiting method"); return dottedMethodSig; } /** If currently visiting a field, get the field's name */ public String getFieldName() { if (!visitingField) throw new IllegalStateException("getFieldName called while not visiting field"); return fieldName; } /** If currently visiting a field, get the field's slash-formatted signature */ public String getFieldSig() { if (!visitingField) throw new IllegalStateException("getFieldSig called while not visiting field"); return fieldSig; } /** If currently visiting a field, return whether or not the field is static */ public boolean getFieldIsStatic() { if (!visitingField) throw new IllegalStateException("getFieldIsStatic called while not visiting field"); return fieldIsStatic; } /** If currently visiting a field, get the field's fully qualified name */ public String getFullyQualifiedFieldName() { if (!visitingField) throw new IllegalStateException("getFullyQualifiedFieldName called while not visiting field"); return fullyQualifiedFieldName; } /** If currently visiting a field, get the field's dot-formatted signature */ public String getDottedFieldSig() { if (!visitingField) throw new IllegalStateException("getDottedFieldSig called while not visiting field"); return dottedFieldSig; } }
package io.spine.server; import com.google.cloud.firestore.CollectionReference; import com.google.cloud.firestore.DocumentReference; import com.google.cloud.firestore.Firestore; import io.grpc.stub.StreamObserver; import io.spine.client.EntityStateUpdate; import io.spine.client.Subscription; import io.spine.client.SubscriptionUpdate; import io.spine.client.Target; import io.spine.client.Topic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import static com.google.common.base.Preconditions.checkNotNull; import static java.lang.String.format; public final class FirebaseEndpoint { private final Firestore database; private final SubscriptionService subscriptionService; private FirebaseEndpoint(Builder builder) { this.database = builder.database; this.subscriptionService = builder.subscriptionService; } /** * Subscribes this {@code FirebaseEndpoint} to the given {@link Topic}. * * <p>After this method invocation the underlying {@link Firestore} (eventually) starts * receiving the entity state updates for the given {@code topic}. * * <p>See <a href="#protocol">class level doc</a> for the description of the storage protocol. * * @param topic the topic to subscribe to */ public void subscribe(Topic topic) { checkNotNull(topic); final Target target = topic.getTarget(); final String type = target.getType(); final CollectionReference collectionReference = database.collection(type); final StreamObserver<SubscriptionUpdate> updateObserver = new SubscriptionToFirebaseAdapter(collectionReference); final StreamObserver<Subscription> subscriptionObserver = new SubscriptionObserver(subscriptionService, updateObserver); subscriptionService.subscribe(topic, subscriptionObserver); } /** * Creates a new instance of {@code Builder} for {@code FirebaseEndpoint} instances. * * @return new instance of {@code Builder} */ public static Builder newBuilder() { return new Builder(); } /** * A builder for the {@code FirebaseEndpoint} instances. */ public static final class Builder { private SubscriptionService subscriptionService; private Firestore database; private Builder() { // Prevent direct instantiation. } public Builder setSubscriptionService(SubscriptionService subscriptionService) { this.subscriptionService = checkNotNull(subscriptionService); return this; } public Builder setDatabase(Firestore database) { this.database = checkNotNull(database); return this; } /** * Creates a new instance of {@code FirebaseEndpoint}. * * @return new instance of {@code FirebaseEndpoint} with the given * parameters */ public FirebaseEndpoint build() { checkNotNull(database); checkNotNull(subscriptionService); return new FirebaseEndpoint(this); } } /** * The {@link StreamObserver} implementation which * {@linkplain SubscriptionService#activate activates} all the received {@link Subscription}s. * * <p>After activation the given {@code dataObserver} starts receiving the Entity state * updates. * * <p>The implementation throws a {@link RuntimeException} upon any * {@linkplain StreamObserver#onError error} and handles the * {@linkplain StreamObserver#onCompleted() successful completion} silently. */ private static class SubscriptionObserver implements StreamObserver<Subscription> { private final SubscriptionService subscriptionService; private final StreamObserver<SubscriptionUpdate> dataObserver; private SubscriptionObserver(SubscriptionService service, StreamObserver<SubscriptionUpdate> dataObserver) { this.subscriptionService = service; this.dataObserver = dataObserver; } @Override public void onNext(Subscription subscription) { subscriptionService.activate(subscription, dataObserver); } @Override public void onError(Throwable t) { throw new RuntimeException(t); } @Override public void onCompleted() { // NoOp } } /** * An implementation of {@link StreamObserver} publishing the received * {@link SubscriptionUpdate}s to the given * {@link CollectionReference Cloud Firestore location}. * * <p>The implementation logs a message upon either * {@linkplain StreamObserver#onCompleted() successful} or * {@linkplain StreamObserver#onError faulty} stream completion. * * @see FirestoreEntityStateUpdatePublisher */ private static class SubscriptionToFirebaseAdapter implements StreamObserver<SubscriptionUpdate> { private final CollectionReference target; private final FirestoreEntityStateUpdatePublisher publisher; private SubscriptionToFirebaseAdapter(CollectionReference target) { this.target = target; this.publisher = new FirestoreEntityStateUpdatePublisher(target); } @Override public void onNext(SubscriptionUpdate value) { final Collection<EntityStateUpdate> payload = value.getEntityStateUpdatesList(); publisher.publish(payload); } @Override public void onError(Throwable error) { log().error(format("Subscription with target `%s` has been completed with an error.", target.getPath()), error); } @Override public void onCompleted() { log().info("Subscription with target `{}` has been completed.", target.getPath()); } } private static Logger log() { return LogSingleton.INSTANCE.value; } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = LoggerFactory.getLogger(FirebaseEndpoint.class); } }
package burp; import java.util.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.awt.Toolkit; import javax.swing.JMenuItem; public class BurpExtender implements IBurpExtender, IContextMenuFactory, ClipboardOwner { private IExtensionHelpers helpers; private final static String NAME = "Copy as requests"; private final static String[] PYTHON_ESCAPE = new String[256]; static { for (int i = 0x00; i <= 0xFF; i++) PYTHON_ESCAPE[i] = String.format("\\x%02x", i); for (int i = 0x20; i < 0x80; i++) PYTHON_ESCAPE[i] = String.valueOf((char)i); PYTHON_ESCAPE['\n'] = "\\n"; PYTHON_ESCAPE['\r'] = "\\r"; PYTHON_ESCAPE['\t'] = "\\t"; PYTHON_ESCAPE['"'] = "\\\""; PYTHON_ESCAPE['\\'] = "\\\\"; } @Override public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) { helpers = callbacks.getHelpers(); callbacks.setExtensionName(NAME); callbacks.registerContextMenuFactory(this); } @Override public List<JMenuItem> createMenuItems(IContextMenuInvocation invocation) { final IHttpRequestResponse[] messages = invocation.getSelectedMessages(); if (messages == null || messages.length == 0) return null; JMenuItem i = new JMenuItem(NAME); i.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyMessages(messages); } }); return Collections.singletonList(i); } private void copyMessages(IHttpRequestResponse[] messages) { StringBuilder py = new StringBuilder("import requests\n"); for (IHttpRequestResponse message : messages) { IRequestInfo ri = helpers.analyzeRequest(message); byte[] req = message.getRequest(); py.append("\nrequests."); py.append(ri.getMethod().toLowerCase()); py.append("(\""); py.append(escapeQuotes(ri.getUrl().toString())); py.append("\", headers={"); processHeaders(py, ri.getHeaders()); py.append('}'); processBody(py, req, ri); py.append(')'); } Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(new StringSelection(py.toString()), this); } private static void processHeaders(StringBuilder py, List<String> headers) { boolean firstHeader = true; for (String header : headers) { if (header.toLowerCase().startsWith("host:")) continue; header = escapeQuotes(header); int colonPos = header.indexOf(':'); if (colonPos == -1) continue; if (firstHeader) { firstHeader = false; py.append('"'); } else { py.append(", \""); } py.append(header, 0, colonPos); py.append("\": \""); py.append(header, colonPos + 2, header.length()); py.append('"'); } } private void processBody(StringBuilder py, byte[] req, IRequestInfo ri) { int bo = ri.getBodyOffset(); if (bo == req.length - 1) return; py.append(", data="); if (ri.getContentType() == IRequestInfo.CONTENT_TYPE_URL_ENCODED) { py.append('{'); boolean firstKey = true; int keyStart = bo, keyEnd = -1; for (int pos = bo; pos < req.length; pos++) { byte b = req[pos]; if (keyEnd == -1) { if (b == (byte)'=') { if (pos == req.length - 1) { if (!firstKey) py.append(", "); escapeUrlEncodedBytes(req, py, keyStart, pos); py.append(": ''"); } else { keyEnd = pos; } } } else if (b == (byte)'&' || pos == req.length - 1) { if (firstKey) firstKey = false; else py.append(", "); escapeUrlEncodedBytes(req, py, keyStart, keyEnd); py.append(": "); escapeUrlEncodedBytes(req, py, keyEnd + 1, pos == req.length - 1 ? req.length : pos); keyEnd = -1; keyStart = pos + 1; } } py.append('}'); } else { escapeBytes(req, py, bo, req.length); } } private static String escapeQuotes(String value) { return value.replace("\\", "\\\\").replace("\"", "\\\"") .replace("\n", "\\n").replace("\r", "\\r"); } private void escapeUrlEncodedBytes(byte[] input, StringBuilder output, int start, int end) { if (end > start) { byte[] dec = helpers.urlDecode(Arrays.copyOfRange(input, start, end)); escapeBytes(dec, output, 0, dec.length); } else { output.append("''"); } } private static void escapeBytes(byte[] input, StringBuilder output, int start, int end) { output.append('"'); for (int pos = start; pos < end; pos++) { output.append(PYTHON_ESCAPE[input[pos] & 0xFF]); } output.append('"'); } @Override public void lostOwnership(Clipboard aClipboard, Transferable aContents) {} }
package ru.linachan.pushbullet; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.linachan.pushbullet.objects.PushBulletDevice; import ru.linachan.pushbullet.objects.PushBulletDeviceIcon; import ru.linachan.pushbullet.objects.PushBulletPush; import ru.linachan.pushbullet.objects.PushBulletPushType; import ru.linachan.yggdrasil.YggdrasilCore; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; @SuppressWarnings("unchecked") public class PushBulletClient { private YggdrasilCore core; private final String API_KEY; private final String API_VERSION = "v2"; private PushBulletDevice device; private static Logger logger = LoggerFactory.getLogger(PushBulletClient.class); public PushBulletClient(YggdrasilCore yggdrasilCore, String apiKey) { core = yggdrasilCore; API_KEY = apiKey; } private URL buildURL(String endpoint) throws MalformedURLException { return new URL("https://api.pushbullet.com/" + API_VERSION + "/" + endpoint); } private JSONObject callAPI(PushBulletRequestType method, String endpoint, JSONObject data) { try { HttpURLConnection apiConnection = (HttpURLConnection) buildURL(endpoint).openConnection(); apiConnection.setRequestMethod(method.name()); apiConnection.setRequestProperty("Access-Token", API_KEY); switch (method) { case GET: case DELETE: break; case PUT: case POST: apiConnection.setRequestProperty("Content-Type", "application/json"); apiConnection.setDoOutput(true); DataOutputStream output = new DataOutputStream(apiConnection.getOutputStream()); output.writeBytes(data.toJSONString()); output.flush(); output.close(); break; } return (JSONObject) new JSONParser().parse(new InputStreamReader(apiConnection.getInputStream())); } catch (IOException | ParseException e) { logger.trace("Unable to call PushBullet API", e); } return null; } public List<PushBulletDevice> listDevices() { JSONObject response = callAPI(PushBulletRequestType.GET, "devices", null); List<PushBulletDevice> devices = new ArrayList<>(); if (response != null) { for (Object device : (JSONArray) response.get("devices")) { devices.add(new PushBulletDevice((JSONObject) device)); } } return devices; } public PushBulletDevice getDevice(String nickName) { for (PushBulletDevice device: listDevices()) { if (device.getNickName().equals(nickName)) { return device; } } return null; } public PushBulletDevice createDevice(JSONObject deviceData) { JSONObject response = callAPI(PushBulletRequestType.POST, "devices", deviceData); return new PushBulletDevice(response); } public PushBulletDevice createDevice(String nickName, String model, String manufacturer, String pushToken, int version, PushBulletDeviceIcon icon, boolean hasSMS) { JSONObject deviceData = new JSONObject(); deviceData.put("nickname", nickName); deviceData.put("model", model); deviceData.put("manufacturer", manufacturer); deviceData.put("push_token", pushToken); deviceData.put("app_version", version); deviceData.put("icon", icon.toString().toLowerCase()); deviceData.put("has_sms", hasSMS); return createDevice(deviceData); } public void setUpDevice(String deviceName) { device = getDevice(deviceName); device = (device != null) ? device : createDevice( deviceName, "PushBullet Plugin", "linaDevel Team", null, 1, PushBulletDeviceIcon.SYSTEM, false ); } public List<PushBulletPush> listPushes() { JSONObject response = callAPI(PushBulletRequestType.GET, "pushes", null); List<PushBulletPush> pushes = new ArrayList<>(); if (response != null) { for (Object push : (JSONArray) response.get("pushes")) { pushes.add(new PushBulletPush((JSONObject) push)); } } return pushes; } public PushBulletPush getPush(String iden) { for (PushBulletPush push: listPushes()) { if (push.getIden().equals(iden)) { return push; } } return null; } public PushBulletPush createPush(JSONObject pushData) { JSONObject response = callAPI(PushBulletRequestType.POST, "pushes", pushData); return new PushBulletPush(response); } public PushBulletPush createPush(PushBulletPushType type, JSONObject pushData) { JSONObject pushObject = new JSONObject(); if (device != null) { pushObject.put("device_iden", device.getIden()); } pushObject.put("type", type.toString().toLowerCase()); switch (type) { case NOTE: pushObject.put("title", pushData.get("title")); pushObject.put("body", pushData.get("body")); break; case LINK: pushObject.put("title", pushData.get("title")); pushObject.put("body", pushData.get("body")); pushObject.put("url", pushData.get("url")); break; case FILE: pushObject.put("body", pushData.get("body")); pushObject.put("file_name", pushData.get("file_name")); pushObject.put("file_type", pushData.get("file_type")); pushObject.put("file_url", pushData.get("file_url")); break; } return createPush(pushObject); } public PushBulletPush createNotePush(String title, String body) { JSONObject pushData = new JSONObject(); pushData.put("title", title); pushData.put("body", body); return createPush(PushBulletPushType.NOTE, pushData); } public PushBulletPush createLinkPush(String title, String body, String url) { JSONObject pushData = new JSONObject(); pushData.put("title", title); pushData.put("body", body); pushData.put("url", url); return createPush(PushBulletPushType.NOTE, pushData); } }
package se.raddo.raddose3D.tests; import org.mockito.InOrder; import org.testng.annotations.*; import se.raddo.raddose3D.Beam; import se.raddo.raddose3D.Crystal; import se.raddo.raddose3D.Experiment; import se.raddo.raddose3D.ExperimentDummy; import se.raddo.raddose3D.Output; import se.raddo.raddose3D.Wedge; import static org.mockito.Mockito.*; public class ExperimentTest { private final Crystal c = mock(Crystal.class); private final Wedge w = mock(Wedge.class); private final Beam b = mock(Beam.class); @Test public void testExperimentWithCrystalAndNullValues() { Experiment e = new Experiment(); Output testsubscriber = mock(Output.class); e.addObserver(testsubscriber); // No message sent yet verify(testsubscriber, never()).publishCrystal(any(Crystal.class)); verify(testsubscriber, never()).publishBeam(any(Beam.class)); verify(testsubscriber, never()).publishWedge(any(Wedge.class)); e.setCrystal(c); // Null values should be handled gracefully and ignored e.setBeam(null); e.setCrystal(null); e.exposeWedge(null); // One object sent verify(testsubscriber, times(1)).publishCrystal(any(Crystal.class)); verify(testsubscriber, times(1)).publishCrystal(c); verify(testsubscriber, never()).publishBeam(any(Beam.class)); verify(testsubscriber, never()).publishWedge(any(Wedge.class)); verify(testsubscriber, never()).close(); e.close(); // And closed verify(testsubscriber, times(1)).publishCrystal(any(Crystal.class)); verify(testsubscriber, never()).publishBeam(any(Beam.class)); verify(testsubscriber, never()).publishWedge(any(Wedge.class)); verify(testsubscriber, times(1)).close(); } @Test public void testExperimentWithCrystalAndNullValuesSimpler() { // arrange Experiment e = new Experiment(); Output testsubscriber = mock(Output.class); // act e.addObserver(testsubscriber); e.setCrystal(c); e.setBeam(null); e.setCrystal(null); e.exposeWedge(null); e.close(); // assert InOrder inOrder = inOrder(testsubscriber); inOrder.verify(testsubscriber).close(); inOrder.verify(testsubscriber).publishCrystal(c); verify(testsubscriber, times(1)).publishCrystal(any(Crystal.class)); verify(testsubscriber, never()).publishBeam(any(Beam.class)); verify(testsubscriber, never()).publishWedge(any(Wedge.class)); verify(testsubscriber, times(1)).close(); } /* This may be a bit overspecified... */ @Test public void testExperimentWithTwoSubscribers() { Output testsubscriberOne = mock(Output.class); Output testsubscriberTwo = mock(Output.class); Output testsubscriberThree = mock(Output.class); Experiment e = new ExperimentDummy(); e.addObserver(testsubscriberOne); e.setCrystal(c); e.addObserver(testsubscriberTwo); // One object sent to first subscriber, none to second verify(testsubscriberOne, times(1)).publishCrystal(any(Crystal.class)); verify(testsubscriberOne, times(1)).publishCrystal(c); verify(testsubscriberOne, never()).publishWedge(any(Wedge.class)); verify(testsubscriberTwo, never()).publishWedge(any(Wedge.class)); e.exposeWedge(w); // Null values should be handled gracefully and ignored e.setBeam(null); e.setCrystal(null); e.exposeWedge(null); // Two objects sent to first subscriber, one to second verify(testsubscriberOne, never()).publishBeam(any(Beam.class)); verify(testsubscriberOne, times(1)).publishWedge(any(Wedge.class)); verify(testsubscriberOne, times(1)).publishWedge(w); verify(testsubscriberTwo, never()).publishBeam(any(Beam.class)); verify(testsubscriberTwo, times(1)).publishWedge(any(Wedge.class)); verify(testsubscriberTwo, times(1)).publishWedge(w); // Subscribe third listener e.addObserver(testsubscriberThree); e.setBeam(b); // Check subscriber status verify(testsubscriberOne, times(1)).publishBeam(any(Beam.class)); verify(testsubscriberOne, times(1)).publishBeam(b); verify(testsubscriberOne, times(1)).publishWedge(any(Wedge.class)); verify(testsubscriberOne, never()).close(); verify(testsubscriberTwo, times(1)).publishBeam(any(Beam.class)); verify(testsubscriberTwo, times(1)).publishBeam(b); verify(testsubscriberTwo, times(1)).publishWedge(any(Wedge.class)); verify(testsubscriberTwo, never()).close(); verify(testsubscriberThree, times(1)).publishBeam(any(Beam.class)); verify(testsubscriberThree, times(1)).publishBeam(b); verify(testsubscriberThree, never()).publishWedge(any(Wedge.class)); verify(testsubscriberThree, never()).close(); e.close(); // Check subscriber status verify(testsubscriberOne, times(1)).publishCrystal(any(Crystal.class)); verify(testsubscriberOne, times(1)).publishBeam(any(Beam.class)); verify(testsubscriberOne, times(1)).publishWedge(any(Wedge.class)); verify(testsubscriberOne, times(1)).close(); verify(testsubscriberTwo, never()).publishCrystal(any(Crystal.class)); verify(testsubscriberTwo, times(1)).publishBeam(any(Beam.class)); verify(testsubscriberTwo, times(1)).publishWedge(any(Wedge.class)); verify(testsubscriberTwo, times(1)).close(); verify(testsubscriberThree, never()).publishCrystal(any(Crystal.class)); verify(testsubscriberThree, times(1)).publishBeam(any(Beam.class)); verify(testsubscriberThree, never()).publishWedge(any(Wedge.class)); verify(testsubscriberThree, times(1)).close(); } }
package com.androidyuan; import static com.androidyuan.Helper.ClsHelper.isClassOfType; import static javax.lang.model.element.Modifier.ABSTRACT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static javax.tools.Diagnostic.Kind.ERROR; import com.androidyuan.generator.AnnotatedClass; import com.androidyuan.generator.CodeGenerator; import com.androidyuan.generator.ParcelableGenerator; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.TypeSpec; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.tools.Diagnostic; public class GeneratorProcessor extends AbstractProcessor { private static final String ANNOTATION = "@" + SimpleGenerator.class.getSimpleName(); private Messager messager; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); messager = processingEnv.getMessager(); } @Override public Set<String> getSupportedAnnotationTypes() { return Collections.singleton(SimpleGenerator.class.getCanonicalName()); } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { List<AnnotatedClass> annotatedClasses = new ArrayList<>(); for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(SimpleGenerator.class)) { if (annotatedElement.getKind() == ElementKind.CLASS) { //ElementTypeElement // if (annotatedElement instanceof TypeElement) { // Our annotation is defined with @Target(value=TYPE) TypeElement element = (TypeElement) annotatedElement; if (!isValidClass(element)) { return true; } try { AnnotatedClass annotatedClass = buildAnnotatedClass(element, roundEnv); annotatedClasses.add(annotatedClass); } catch (Exception e) { String message = String.format( "Couldn't process class %s: %s", element, e.getMessage() ); messager.printMessage(ERROR, message, annotatedElement); } } } try { generate(annotatedClasses); } catch (NoPackageNameException | IOException e) { messager.printMessage(ERROR, "Couldn't generate class"); } Messager messager = processingEnv.getMessager(); for (TypeElement te : annotations) { for (Element e : roundEnv.getElementsAnnotatedWith(te)) { messager.printMessage( Diagnostic.Kind.NOTE, "Processor Printing: " + e.toString() ); } } return true; } // @SimpleGenerator private AnnotatedClass buildAnnotatedClass(TypeElement typeElement, RoundEnvironment roundEnv) throws NoPackageNameException, IOException, ClassNotFoundException { HashMap<String, TypeMirror> variableMap = new HashMap<>(); HashMap<String, ArrayList<AnnotationSpec>> variableAnooMap = new HashMap<>(); ArrayList<String> variableNames = new ArrayList<>(); for (Element element : typeElement.getEnclosedElements()) { // Element if (!(element instanceof VariableElement)) { continue; } // static final if (element.getModifiers().contains(STATIC) || element.getModifiers().contains(FINAL)) { continue; } VariableElement variableElement = (VariableElement) element; variableNames.add(variableElement.getSimpleName().toString()); variableMap.put( variableElement.getSimpleName().toString(), variableElement.asType() ); /** * messager.printMessage( * Diagnostic.Kind.ERROR, * String.format(i + element.getKind().toString(), this), * element); * messageelment * Error:(10, 17) : 0CONSTRUCTOR * Error:(13, 17) : 1FIELD * Error:(15, 19) : 2FIELD * Error:(17, 16) : 3FIELD * Error:(19, 25) : 4FIELD */ List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors(); if (element.getKind() != ElementKind.CONSTRUCTOR) { ArrayList<AnnotationSpec> annotationSpecs = new ArrayList<>(); for (int i = 0; i < annotationMirrors.size(); i++) { DeclaredType declaredType = annotationMirrors.get(i).getAnnotationType(); //asElement() //getEnclosingType() NONE NoType //getTypeArguments() ElementKind elementKind = declaredType.asElement().getKind(); String simpleName = null; if (elementKind == ElementKind.ANNOTATION_TYPE) { simpleName = declaredType.asElement().toString(); } Map<? extends ExecutableElement, ? extends AnnotationValue> map = annotationMirrors.get(i).getElementValues(); // // key // String key = map.keySet().iterator().next().getSimpleName().toString(); // //value()Collection // String value = (String) map.values().iterator().next().getValue(); // Class clazz = Class.forName(simpleName); // AnnotationSpec annotationSpec = AnnotationSpec.builder(clazz).addMember(key, "$S", value).build(); // annotationSpecs.add(annotationSpec); // messager.printMessage( // Diagnostic.Kind.ERROR, // String.format("" + simpleName + " key" + key + " " + value, this), // element); // for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : map.entrySet()) { // messager.printMessage( // Diagnostic.Kind.ERROR, // String.format(" map:"+map.entrySet()+" key:" + entry.getKey() + " value:" + entry.getValue(), this), // element); Class clazz = Class.forName(simpleName); AnnotationSpec.Builder annotationBuilder = AnnotationSpec.builder(clazz); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : map.entrySet()) { //key String key = entry.getKey().getSimpleName().toString(); //value()Collection Object value = entry.getValue().getValue(); if (value instanceof String) { annotationBuilder.addMember(key, "$S", value); } else { annotationBuilder.addMember(key, "$L", value); } messager.printMessage( Diagnostic.Kind.ERROR, String.format("" + simpleName + " key" + key + " " + value, this), element); } //new AnnotationSpec annotationSpec = annotationBuilder.build(); annotationSpecs.add(annotationSpec); } variableAnooMap.put( variableElement.getSimpleName().toString(), annotationSpecs ); } } // parcelable if (isParcelable(typeElement)) { String message = String.format("Classes %s is parceleble.", ANNOTATION); //messager.printMessage(Diagnostic.Kind.OTHER, message, typeElement); } return new AnnotatedClass(typeElement, variableNames, variableMap, variableAnooMap, isParcelable(typeElement)); } private void generate(List<AnnotatedClass> list) throws NoPackageNameException, IOException { if (list.size() == 0) { return; } for (AnnotatedClass annotatedClass : list) { // debug String message = annotatedClass.annotatedClassName + " / " + annotatedClass.typeElement + " / " + Arrays.toString(annotatedClass.variableNames.toArray()); //messager.printMessage(Diagnostic.Kind.NOTE, message, annotatedClass.typeElement);// build runrun } String packageName = getPackageName(processingEnv.getElementUtils(), list.get(0).typeElement); for (AnnotatedClass anno : list) { TypeSpec generatedClass; if (anno.isParcelable()) { generatedClass = new ParcelableGenerator(anno, processingEnv).generateClass(); } else { generatedClass = new CodeGenerator(anno, processingEnv).generateClass(); } JavaFile javaFile = JavaFile.builder(packageName, generatedClass) .build(); // app module/build/generated/source/apt javaFile.writeTo(processingEnv.getFiler()); } } private boolean isPublic(TypeElement element) { return element.getModifiers().contains(PUBLIC); } private boolean isAbstract(TypeElement element) { return element.getModifiers().contains(ABSTRACT); } private boolean isValidClass(TypeElement element) { if (!isPublic(element)) { String message = String.format("Classes annotated with %s must be public.", ANNOTATION); messager.printMessage(Diagnostic.Kind.ERROR, message, element); return false; } if (!isAbstract(element)) { String message = String.format("Classes annotated with %s must be abstract.", ANNOTATION); messager.printMessage(Diagnostic.Kind.ERROR, message, element); return false; } return true; } private String getPackageName(Elements elements, TypeElement typeElement) throws NoPackageNameException { PackageElement pkg = elements.getPackageOf(typeElement); if (pkg.isUnnamed()) { throw new NoPackageNameException(typeElement); } return pkg.getQualifiedName().toString(); } public boolean isParcelable(TypeElement typeElement) { TypeElement parcelable = processingEnv.getElementUtils().getTypeElement( "android.os.Parcelable"); TypeMirror cls = typeElement.asType(); return isClassOfType( processingEnv.getTypeUtils(), parcelable.asType(), cls); } }
package org.jboss.windup.graph; import java.io.File; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.io.FileUtils; import org.jboss.windup.graph.typedgraph.GraphTypeRegistry; import com.thinkaurelius.titan.core.TitanFactory; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.TitanKey; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.wrappers.batch.BatchGraph; import com.tinkerpop.frames.FramedGraph; import com.tinkerpop.frames.FramedGraphConfiguration; import com.tinkerpop.frames.FramedGraphFactory; import com.tinkerpop.frames.modules.FrameClassLoaderResolver; import com.tinkerpop.frames.modules.Module; import com.tinkerpop.frames.modules.gremlingroovy.GremlinGroovyModule; import com.tinkerpop.frames.modules.javahandler.JavaHandlerModule; import java.util.Arrays; public class GraphContextImpl implements GraphContext { private GraphApiCompositeClassLoaderProvider classLoaderProvider; private TitanGraph graph; private BatchGraph<TitanGraph> batch; private FramedGraph<TitanGraph> framed; private GraphTypeRegistry graphTypeRegistry; private File diskCacheDir; public TitanGraph getGraph() { return graph; } @Override public GraphTypeRegistry getGraphTypeRegistry() { return graphTypeRegistry; } public BatchGraph<TitanGraph> getBatch() { return batch; } public FramedGraph<TitanGraph> getFramed() { return framed; } public GraphContextImpl(File diskCache, GraphTypeRegistry graphTypeRegistry, GraphApiCompositeClassLoaderProvider classLoaderProvider) { this.graphTypeRegistry = graphTypeRegistry; this.classLoaderProvider = classLoaderProvider; FileUtils.deleteQuietly(diskCache); this.diskCacheDir = diskCache; File lucene = new File(diskCache, "graphsearch"); File berkley = new File(diskCache, "graph"); // TODO: Externalize this. Configuration conf = new BaseConfiguration(); conf.setProperty("storage.directory", berkley.getAbsolutePath()); conf.setProperty("storage.backend", "berkeleyje"); conf.setProperty("storage.index.search.backend", "lucene"); conf.setProperty("storage.index.search.directory", lucene.getAbsolutePath()); conf.setProperty("storage.index.search.client-only", "false"); conf.setProperty("storage.index.search.local-mode", "true"); graph = TitanFactory.open(conf); // TODO: This has to load dynamically. // E.g. get all Model classes and look for @Indexed - org.jboss.windup.graph.api.model.anno. String[] keys = new String[]{"namespaceURI", "schemaLocation", "publicId", "rootTagName", "systemId", "qualifiedName", "archiveEntry", "type", "filePath", "mavenIdentifier"}; for( String key : keys ) { graph.makeKey(key).dataType(String.class).indexed(Vertex.class).make(); } batch = new BatchGraph<TitanGraph>(graph, 1000L); // Composite classloader final ClassLoader compositeClassLoader = classLoaderProvider.getCompositeClassLoader(); final FrameClassLoaderResolver fclr = new FrameClassLoaderResolver() { public ClassLoader resolveClassLoader(Class<?> frameType) { return compositeClassLoader; } }; final Module fclrModule = new Module() { @Override public Graph configure(Graph baseGraph, FramedGraphConfiguration config) { config.setFrameClassLoaderResolver( fclr ); return baseGraph; } }; // Frames with all the features. FramedGraphFactory factory = new FramedGraphFactory( fclrModule, // Composite classloader new JavaHandlerModule(), // @JavaHandler graphTypeRegistry.build(), // Model classes new GremlinGroovyModule() // @Gremlin ); framed = factory.create(graph); } @Override public File getDiskCacheDirectory() { return diskCacheDir; } }
package apostov; import static apostov.Suit.CLUBS; import static apostov.Suit.DIAMONDS; import static apostov.Suit.HEARTS; import static apostov.Suit.SPADES; import static apostov.Value.FIVE; import static apostov.Value.FOUR; import static apostov.Value.KING; import static apostov.Value.QUEEN; import static apostov.Value.JACK; import static apostov.Value.TWO; import static apostov.Value.NINE; import static apostov.Value.SEVEN; import static apostov.Value.SIX; import static apostov.Value.TEN; import static apostov.Value.ACE; import static com.google.common.collect.ImmutableSet.copyOf; import static com.google.common.collect.Iterables.concat; import static org.junit.Assert.*; import static strength.PokerHandKind.PAIR; import static strength.PokerHandKind.HIGH_CARD; import org.junit.Test; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableSet; import strength.HighCardRanking; import strength.PairRanking; import strength.PokerHandRanking; public class ShowdownEvaluatorTest { @Test public void selectBestCombinationWithTwoKings() { final Card seven = new Card(SEVEN, SPADES); final ImmutableCollection<Card> holeCards = ImmutableSet.of( seven, new Card(KING, CLUBS)); final Card queen = new Card(QUEEN, CLUBS); final Card six = new Card(SIX, DIAMONDS); final ImmutableCollection<Card> board = ImmutableSet.of( new Card(FIVE, CLUBS), new Card(KING, DIAMONDS), new Card(FOUR, HEARTS), queen, six); final ShowdownEvaluator evaluator = new ShowdownEvaluator(); final PokerHandRanking handStrength = evaluator.selectBestCombination(copyOf(concat(holeCards, board))); assertSame(PAIR, handStrength.handKind); final PairRanking pairRanking = (PairRanking) handStrength; assertSame(KING, pairRanking.pairValue); assertEquals( ImmutableSet.of(CLUBS, DIAMONDS), ImmutableSet.of(pairRanking.firstSuit, pairRanking.secondSuit)); assertEquals(queen, pairRanking.firstKicker); assertEquals(seven, pairRanking.secondKicker); assertEquals(six, pairRanking.thirdKicker); } @Test public void selectBestCombinationWithNothing() { final Card jack = new Card(JACK, HEARTS); final Card nine = new Card(NINE, DIAMONDS); final ImmutableCollection<Card> holeCards = ImmutableSet.of( jack, nine); final Card ace = new Card(ACE, HEARTS); final Card queen = new Card(QUEEN, SPADES); final Card ten = new Card(TEN, HEARTS); final ImmutableCollection<Card> board = ImmutableSet.of( new Card(TWO, DIAMONDS), new Card(SIX, SPADES), queen, ten, ace); final ShowdownEvaluator evaluator = new ShowdownEvaluator(); final PokerHandRanking handStrength = evaluator.selectBestCombination(copyOf(concat(holeCards, board))); assertSame(HIGH_CARD, handStrength.handKind); final HighCardRanking highCardRanking = (HighCardRanking) handStrength; assertEquals(ace, highCardRanking.highestCard); assertEquals(queen, highCardRanking.secondHighestCard); assertEquals(jack, highCardRanking.middleCard); assertEquals(ten, highCardRanking.fourthCard); assertEquals(nine, highCardRanking.bottomCard); } }
package guitests; import javafx.application.Platform; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import org.eclipse.egit.github.core.RepositoryId; import org.junit.Test; import org.loadui.testfx.utils.FXTestUtils; import prefs.PanelInfo; import prefs.Preferences; import ui.TestController; import ui.UI; import ui.components.FilterTextField; import ui.components.KeyboardShortcuts; import ui.issuepanel.FilterPanel; import ui.issuepanel.PanelControl; import util.PlatformEx; import util.events.ShowRenamePanelEvent; import java.io.File; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class UseGlobalConfigsTest extends UITest { @Override public void launchApp() { // isTestMode in UI checks for testconfig too so we don't need to specify --test=true here. FXTestUtils.launchApp(TestUI.class, "--testconfig=true"); } @Test public void useGlobalConfigTest() { // Override setupMethod() if you want to do stuff to the JSON beforehand UI ui = TestController.getUI(); PanelControl panels = ui.getPanelControl(); selectAll(); type("dummy"); pushKeys(KeyCode.TAB); type("dummy"); pushKeys(KeyCode.TAB); type("test"); pushKeys(KeyCode.TAB); type("test"); click("Sign in"); ComboBox<String> repositorySelector = findOrWaitFor("#repositorySelector"); waitForValue(repositorySelector); assertEquals("dummy/dummy", repositorySelector.getValue()); pushKeys(KeyboardShortcuts.MAXIMIZE_WINDOW); // Make a new board click("Boards"); click("Save as"); // Somehow the text field cannot be populated by typing on the CI, use setText instead. // TODO find out why ((TextField) find("#boardnameinput")).setText("Empty Board"); click("OK"); PlatformEx.runAndWait(() -> UI.events.triggerEvent(new ShowRenamePanelEvent(0))); type("Renamed panel"); push(KeyCode.ENTER); FilterPanel filterPanel0 = (FilterPanel) panels.getPanel(0); assertEquals("Renamed panel", filterPanel0.getNameText().getText()); FilterTextField filterTextField0 = filterPanel0.getFilterTextField(); waitUntilNodeAppears(filterTextField0); Platform.runLater(filterTextField0::requestFocus); PlatformEx.waitOnFxThread(); type("is"); pushKeys(KeyCode.SHIFT, KeyCode.SEMICOLON); type("issue"); push(KeyCode.ENTER); // Load dummy2/dummy2 too pushKeys(KeyboardShortcuts.CREATE_RIGHT_PANEL); PlatformEx.waitOnFxThread(); FilterPanel filterPanel1 = (FilterPanel) panels.getPanel(1); FilterTextField filterTextField1 = filterPanel1.getFilterTextField(); waitUntilNodeAppears(filterTextField1); Platform.runLater(filterTextField1::requestFocus); PlatformEx.waitOnFxThread(); type("repo"); pushKeys(KeyCode.SHIFT, KeyCode.SEMICOLON); type("dummy2/dummy2"); pushKeys(KeyCode.ENTER); Label renameButton1 = filterPanel1.getRenameButton(); click(renameButton1); type("Dummy 2 panel"); push(KeyCode.ENTER); assertEquals("Dummy 2 panel", filterPanel1.getNameText().getText()); pushKeys(KeyboardShortcuts.CREATE_LEFT_PANEL); PlatformEx.waitOnFxThread(); sleep(500); FilterPanel filterPanel2 = (FilterPanel) panels.getPanel(0); FilterTextField filterTextField2 = filterPanel2.getFilterTextField(); Platform.runLater(filterTextField2::requestFocus); PlatformEx.waitOnFxThread(); type("is"); pushKeys(KeyCode.SHIFT, KeyCode.SEMICOLON); type("open"); assertEquals("is:open", filterTextField2.getText()); pushKeys(KeyCode.ENTER); PlatformEx.runAndWait(() -> UI.events.triggerEvent(new ShowRenamePanelEvent(0))); type("Open issues"); push(KeyCode.ENTER); assertEquals("Open issues", filterPanel2.getNameText().getText()); // Make a new board click("Boards"); click("Save as"); // Text field cannot be populated by typing on the CI, use setText instead ((TextField) find("#boardnameinput")).setText("Dummy Board"); click("OK"); // Then exit program... click("File"); click("Quit"); // ...and check if the test JSON is still there... File testConfig = new File(Preferences.DIRECTORY, Preferences.TEST_CONFIG_FILE); if (!(testConfig.exists() && testConfig.isFile())) { fail(); } // ...then check that the JSON file contents are correct. Preferences testPref = TestController.loadTestPreferences(); // Credentials assertEquals("test", testPref.getLastLoginUsername()); assertEquals("test", testPref.getLastLoginPassword()); // Last viewed repository RepositoryId lastViewedRepository = testPref.getLastViewedRepository().get(); assertEquals("dummy/dummy", lastViewedRepository.generateId()); // Boards Map<String, List<PanelInfo>> boards = testPref.getAllBoards(); List<PanelInfo> emptyBoard = boards.get("Empty Board"); assertEquals(1, emptyBoard.size()); assertEquals("", emptyBoard.get(0).getPanelFilter()); assertEquals("Panel", emptyBoard.get(0).getPanelName()); List<PanelInfo> dummyBoard = boards.get("Dummy Board"); assertEquals(3, dummyBoard.size()); assertEquals("is:open", dummyBoard.get(0).getPanelFilter()); assertEquals("is:issue", dummyBoard.get(1).getPanelFilter()); assertEquals("repo:dummy2/dummy2", dummyBoard.get(2).getPanelFilter()); assertEquals("Open issues", dummyBoard.get(0).getPanelName()); assertEquals("Renamed panel", dummyBoard.get(1).getPanelName()); assertEquals("Dummy 2 panel", dummyBoard.get(2).getPanelName()); // Panels List<String> lastOpenFilters = testPref.getLastOpenFilters(); List<String> lastOpenPanelNames = testPref.getPanelNames(); assertEquals("is:open", lastOpenFilters.get(0)); assertEquals("is:issue", lastOpenFilters.get(1)); assertEquals("repo:dummy2/dummy2", lastOpenFilters.get(2)); assertEquals("Open issues", lastOpenPanelNames.get(0)); assertEquals("Renamed panel", lastOpenPanelNames.get(1)); assertEquals("Dummy 2 panel", lastOpenPanelNames.get(2)); } }
package me.coley.recaf.util; import me.coley.recaf.Recaf; import me.coley.recaf.control.Controller; import me.coley.recaf.control.headless.HeadlessController; import me.coley.recaf.workspace.JavaResource; import me.coley.recaf.workspace.Workspace; import java.io.IOException; import java.lang.reflect.Field; import static org.junit.jupiter.api.Assertions.fail; /** * Some common utilities. */ public class TestUtils { /** * Set the current controller to a wrapper of the given resource. * * @param resource * Resource to wrap in a headless controller. * * @return Controller instance. * * @throws IOException * When the config cannot be initialized. */ public static Controller setupController(JavaResource resource) throws IOException { // Ensure recaf home is set if (System.getProperty("recaf.home") == null) System.setProperty("recaf.home", Recaf.getDirectory().normalize().toString()); // Set up the controller Controller controller = new HeadlessController(null, null); controller.setWorkspace(new Workspace(resource)); controller.config().initialize(); return controller; } /** * Used reflection to remove the controller... */ public static void removeController() { try { // In "Recaf.java" we prevent setting the controller twice... // I swear I'm taking crazy pills, because the surefire config should be isolating tests... // That means each test should get a separate JVM. But clearly something is wrong. Field f = Recaf.class.getDeclaredField("currentController"); f.setAccessible(true); f.set(null, null); } catch(Exception ex) { fail("Failed to reset"); } } }
package no.cantara.jau; import com.fasterxml.jackson.databind.ObjectMapper; import jdk.nashorn.internal.ir.annotations.Ignore; import no.cantara.jau.serviceconfig.client.ConfigServiceClient; import no.cantara.jau.serviceconfig.client.ConfigurationStoreUtil; import no.cantara.jau.serviceconfig.client.DownloadUtil; import no.cantara.jau.serviceconfig.dto.ServiceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertFalse; import java.io.File; import java.util.Properties; import java.util.Scanner; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class JAUProcessTest { private static final ObjectMapper mapper = new ObjectMapper(); private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); ScheduledFuture<?> restarterHandle; private ApplicationProcess processHolder; private static final Logger log = LoggerFactory.getLogger(JAUProcessTest.class); @BeforeClass public void startServer() throws InterruptedException { processHolder = new ApplicationProcess(); } @AfterClass public void stop() { processHolder.startProcess(); restarterHandle.cancel(true); } @Ignore @Test public void testProcessDownloadStartupAndRunning() throws Exception { String jsonResponse = new Scanner( new File("config1.serviceconfig") ).useDelimiter("\\A").next(); // let us type a configuration the quick way.. ServiceConfig serviceConfig = mapper.readValue(jsonResponse, ServiceConfig.class); // Process stuff ApplicationProcess processHolder= new ApplicationProcess(); processHolder.setWorkingDirectory(new File("./")); String workingDirectory = processHolder.getWorkingDirectory().getAbsolutePath(); // Download stuff DownloadUtil.downloadAllFiles(serviceConfig.getDownloadItems(), workingDirectory); ConfigurationStoreUtil.toFiles(serviceConfig.getConfigurationStores(), workingDirectory); // Lets try to start String initialCommand = serviceConfig.getStartServiceScript(); int updateInterval=100; System.out.println("Initial command: "+initialCommand); processHolder.setWorkingDirectory(new File(workingDirectory)); processHolder.setCommand(initialCommand.split("\\s+")); processHolder.startProcess(); restarterHandle = scheduler.scheduleAtFixedRate( () -> { try { // Restart, whatever the reason the process is not running. if (!processHolder.processIsrunning()) { log.debug("Process is not running - restarting... clientId={}, lastChanged={}, command={}", processHolder.getClientId(), processHolder.getLastChangedTimestamp(), processHolder.getCommand()); processHolder.startProcess(); } } catch (Exception e) { log.debug("Error thrown from scheduled lambda.", e); } }, 1, updateInterval, MILLISECONDS ); Thread.sleep(4000); assertTrue(processHolder.processIsrunning(), "First check"); Thread.sleep(1000); assertTrue(processHolder.processIsrunning(), "Second check"); processHolder.stopProcess(); assertFalse(processHolder.processIsrunning(), "Seventh check"); Thread.sleep(4000); assertTrue(processHolder.processIsrunning(), "Eigth check"); } private static String getStringProperty(final Properties properties, String propertyKey, String defaultValue) { String property = properties.getProperty(propertyKey, defaultValue); if (property == null) { //-Dconfigservice.url= property = System.getProperty(propertyKey); } return property; } }
package org.json.junit; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.json.CDL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONPointerException; import org.json.XML; import org.junit.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; /** * JSONObject, along with JSONArray, are the central classes of the reference app. * All of the other classes interact with them, and JSON functionality would * otherwise be impossible. */ public class JSONObjectTest { /** * JSONObject built from a bean, but only using a null value. * Nothing good is expected to happen. * Expects NullPointerException */ @Test(expected=NullPointerException.class) public void jsonObjectByNullBean() { MyBean myBean = null; new JSONObject(myBean); } /** * A JSONObject can be created with no content */ @Test public void emptyJsonObject() { JSONObject jsonObject = new JSONObject(); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** * A JSONObject can be created from another JSONObject plus a list of names. * In this test, some of the starting JSONObject keys are not in the * names list. */ @Test public void jsonObjectByNames() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"nullKey\":null,"+ "\"stringKey\":\"hello world!\","+ "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ "\"intKey\":42,"+ "\"doubleKey\":-23.45e67"+ "}"; String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"}; JSONObject jsonObject = new JSONObject(str); // validate JSON JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString()); assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4); assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey"))); assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey"))); assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey"))); assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObjectByName.query("/doubleKey"))); } /** * JSONObjects can be built from a Map<String, Object>. * In this test the map is null. * the JSONObject(JsonTokener) ctor is not tested directly since it already * has full coverage from other tests. */ @Test public void jsonObjectByNullMap() { Map<String, Object> map = null; JSONObject jsonObject = new JSONObject(map); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** * JSONObjects can be built from a Map<String, Object>. * In this test all of the map entries are valid JSON types. */ @Test public void jsonObjectByMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("trueKey", new Boolean(true)); map.put("falseKey", new Boolean(false)); map.put("stringKey", "hello world!"); map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); map.put("intKey", new Long(42)); map.put("doubleKey", new Double(-23.45e67)); JSONObject jsonObject = new JSONObject(map); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6); assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); } /** * Verifies that the constructor has backwards compatability with RAW types pre-java5. */ @Test public void verifyConstructor() { final JSONObject expected = new JSONObject("{\"myKey\":10}"); @SuppressWarnings("rawtypes") Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); JSONObject jaRaw = new JSONObject(myRawC); Map<String, Object> myCStrObj = Collections.singletonMap("myKey", (Object) Integer.valueOf(10)); JSONObject jaStrObj = new JSONObject(myCStrObj); Map<String, Integer> myCStrInt = Collections.singletonMap("myKey", Integer.valueOf(10)); JSONObject jaStrInt = new JSONObject(myCStrInt); Map<?, ?> myCObjObj = Collections.singletonMap((Object) "myKey", (Object) Integer.valueOf(10)); JSONObject jaObjObj = new JSONObject(myCObjObj); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaRaw)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaStrObj)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaStrInt)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaObjObj)); } /** * Verifies that the put Collection has backwards compatability with RAW types pre-java5. */ @Test public void verifyPutCollection() { final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); @SuppressWarnings("rawtypes") Collection myRawC = Collections.singleton(Integer.valueOf(10)); JSONObject jaRaw = new JSONObject(); jaRaw.put("myCollection", myRawC); Collection<Object> myCObj = Collections.singleton((Object) Integer .valueOf(10)); JSONObject jaObj = new JSONObject(); jaObj.put("myCollection", myCObj); Collection<Integer> myCInt = Collections.singleton(Integer .valueOf(10)); JSONObject jaInt = new JSONObject(); jaInt.put("myCollection", myCInt); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaRaw)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaObj)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaInt)); } /** * Verifies that the put Map has backwards compatability with RAW types pre-java5. */ @Test public void verifyPutMap() { final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); @SuppressWarnings("rawtypes") Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); JSONObject jaRaw = new JSONObject(); jaRaw.put("myMap", myRawC); Map<String, Object> myCStrObj = Collections.singletonMap("myKey", (Object) Integer.valueOf(10)); JSONObject jaStrObj = new JSONObject(); jaStrObj.put("myMap", myCStrObj); Map<String, Integer> myCStrInt = Collections.singletonMap("myKey", Integer.valueOf(10)); JSONObject jaStrInt = new JSONObject(); jaStrInt.put("myMap", myCStrInt); Map<?, ?> myCObjObj = Collections.singletonMap((Object) "myKey", (Object) Integer.valueOf(10)); JSONObject jaObjObj = new JSONObject(); jaObjObj.put("myMap", myCObjObj); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaRaw)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaStrObj)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaStrInt)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaObjObj)); } /** * JSONObjects can be built from a Map<String, Object>. * In this test the map entries are not valid JSON types. * The actual conversion is kind of interesting. */ @Test public void jsonObjectByMapWithUnsupportedValues() { Map<String, Object> jsonMap = new HashMap<String, Object>(); // Just insert some random objects jsonMap.put("key1", new CDL()); jsonMap.put("key2", new Exception()); JSONObject jsonObject = new JSONObject(jsonMap); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected 0 key1 items", ((Map<?,?>)(JsonPath.read(doc, "$.key1"))).size() == 0); assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2"))); } /** * JSONObjects can be built from a Map<String, Object>. * In this test one of the map values is null */ @Test public void jsonObjectByMapWithNullValue() { Map<String, Object> map = new HashMap<String, Object>(); map.put("trueKey", new Boolean(true)); map.put("falseKey", new Boolean(false)); map.put("stringKey", "hello world!"); map.put("nullKey", null); map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); map.put("intKey", new Long(42)); map.put("doubleKey", new Double(-23.45e67)); JSONObject jsonObject = new JSONObject(map); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6); assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); assertTrue("expected \"intKey\":42", Long.valueOf("42").equals(jsonObject.query("/intKey"))); assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); } /** * JSONObject built from a bean. In this case all but one of the * bean getters return valid JSON types */ @Test public void jsonObjectByBean() { /** * Default access classes have to be mocked since JSONObject, which is * not in the same package, cannot call MyBean methods by reflection. */ MyBean myBean = mock(MyBean.class); when(myBean.getDoubleKey()).thenReturn(-23.45e7); when(myBean.getIntKey()).thenReturn(42); when(myBean.getStringKey()).thenReturn("hello world!"); when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!"); when(myBean.isTrueKey()).thenReturn(true); when(myBean.isFalseKey()).thenReturn(false); when(myBean.getStringReaderKey()).thenReturn( new StringReader("") { }); JSONObject jsonObject = new JSONObject(myBean); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 8 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 8); assertTrue("expected 0 items in stringReaderKey", ((Map<?, ?>) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected hello world!","hello world!".equals(jsonObject.query("/stringKey"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); assertTrue("expected 42", Integer.valueOf("42").equals(jsonObject.query("/intKey"))); assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(jsonObject.query("/doubleKey"))); // sorry, mockito artifact assertTrue("expected 2 callbacks items", ((List<?>)(JsonPath.read(doc, "$.callbacks"))).size() == 2); assertTrue("expected 0 handler items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0); assertTrue("expected 0 callbacks[1] items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0); } /** * A bean is also an object. But in order to test the JSONObject * ctor that takes an object and a list of names, * this particular bean needs some public * data members, which have been added to the class. */ @Test public void jsonObjectByObjectAndNames() { String[] keys = {"publicString", "publicInt"}; // just need a class that has public data members MyPublicClass myPublicClass = new MyPublicClass(); JSONObject jsonObject = new JSONObject(myPublicClass, keys); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString"))); assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt"))); } /** * Exercise the JSONObject from resource bundle functionality. * The test resource bundle is uncomplicated, but provides adequate test coverage. */ @Test public void jsonObjectByResourceBundle() { JSONObject jsonObject = new JSONObject("org.json.junit.StringsResourceBundle", Locale.getDefault()); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected 2 greetings items", ((Map<?,?>)(JsonPath.read(doc, "$.greetings"))).size() == 2); assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(jsonObject.query("/greetings/hello"))); assertTrue("expected \"world\":\"World!\"", "World!".equals(jsonObject.query("/greetings/world"))); assertTrue("expected 2 farewells items", ((Map<?,?>)(JsonPath.read(doc, "$.farewells"))).size() == 2); assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later"))); assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator"))); } /** * Exercise the JSONObject.accumulate() method */ @Test public void jsonObjectAccumulate() { JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("myArray", true); jsonObject.accumulate("myArray", false); jsonObject.accumulate("myArray", "hello world!"); jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); jsonObject.accumulate("myArray", 42); jsonObject.accumulate("myArray", -23.45e7); // include an unsupported object for coverage try { jsonObject.accumulate("myArray", Double.NaN); assertTrue("Expected exception", false); } catch (JSONException ignored) {} // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 6 myArray items", ((List<?>)(JsonPath.read(doc, "$.myArray"))).size() == 6); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1"))); assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); } /** * Exercise the JSONObject append() functionality */ @Test public void jsonObjectAppend() { JSONObject jsonObject = new JSONObject(); jsonObject.append("myArray", true); jsonObject.append("myArray", false); jsonObject.append("myArray", "hello world!"); jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); jsonObject.append("myArray", 42); jsonObject.append("myArray", -23.45e7); // include an unsupported object for coverage try { jsonObject.append("myArray", Double.NaN); assertTrue("Expected exception", false); } catch (JSONException ignored) {} // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 6 myArray items", ((List<?>)(JsonPath.read(doc, "$.myArray"))).size() == 6); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1/"))); assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); } /** * Exercise the JSONObject doubleToString() method */ @Test public void jsonObjectDoubleToString() { String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" }; Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, Double.NaN, Double.NEGATIVE_INFINITY }; for (int i = 0; i < expectedStrs.length; ++i) { String actualStr = JSONObject.doubleToString(doubles[i]); assertTrue("value expected ["+expectedStrs[i]+ "] found ["+actualStr+ "]", expectedStrs[i].equals(actualStr)); } } /** * Exercise some JSONObject get[type] and opt[type] methods */ @Test public void jsonObjectValues() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"trueStrKey\":\"true\","+ "\"falseStrKey\":\"false\","+ "\"stringKey\":\"hello world!\","+ "\"intKey\":42,"+ "\"intStrKey\":\"43\","+ "\"longKey\":1234567890123456789,"+ "\"longStrKey\":\"987654321098765432\","+ "\"doubleKey\":-23.45e7,"+ "\"doubleStrKey\":\"00001.000\","+ "\"arrayKey\":[0,1,2],"+ "\"objectKey\":{\"myKey\":\"myVal\"}"+ "}"; JSONObject jsonObject = new JSONObject(str); assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey")); assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); assertTrue("stringKey should be string", jsonObject.getString("stringKey").equals("hello world!")); assertTrue("doubleKey should be double", jsonObject.getDouble("doubleKey") == -23.45e7); assertTrue("doubleStrKey should be double", jsonObject.getDouble("doubleStrKey") == 1); assertTrue("opt doubleKey should be double", jsonObject.optDouble("doubleKey") == -23.45e7); assertTrue("opt doubleKey with Default should be double", jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); assertTrue("intKey should be int", jsonObject.optInt("intKey") == 42); assertTrue("opt intKey should be int", jsonObject.optInt("intKey", 0) == 42); assertTrue("opt intKey with default should be int", jsonObject.getInt("intKey") == 42); assertTrue("intStrKey should be int", jsonObject.getInt("intStrKey") == 43); assertTrue("longKey should be long", jsonObject.getLong("longKey") == 1234567890123456789L); assertTrue("opt longKey should be long", jsonObject.optLong("longKey") == 1234567890123456789L); assertTrue("opt longKey with default should be long", jsonObject.optLong("longKey", 0) == 1234567890123456789L); assertTrue("longStrKey should be long", jsonObject.getLong("longStrKey") == 987654321098765432L); assertTrue("xKey should not exist", jsonObject.isNull("xKey")); assertTrue("stringKey should exist", jsonObject.has("stringKey")); assertTrue("opt stringKey should string", jsonObject.optString("stringKey").equals("hello world!")); assertTrue("opt stringKey with default should string", jsonObject.optString("stringKey", "not found").equals("hello world!")); JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); assertTrue("arrayKey should be JSONArray", jsonArray.getInt(0) == 0 && jsonArray.getInt(1) == 1 && jsonArray.getInt(2) == 2); jsonArray = jsonObject.optJSONArray("arrayKey"); assertTrue("opt arrayKey should be JSONArray", jsonArray.getInt(0) == 0 && jsonArray.getInt(1) == 1 && jsonArray.getInt(2) == 2); JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); assertTrue("objectKey should be JSONObject", jsonObjectInner.get("myKey").equals("myVal")); } /** * Check whether JSONObject handles large or high precision numbers correctly */ @Test public void stringToValueNumbersTest() { assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0") instanceof Double); assertTrue("-0.0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double); assertTrue("'-' Should be a String!",JSONObject.stringToValue("-") instanceof String); assertTrue( "0.2 should be a Double!", JSONObject.stringToValue( "0.2" ) instanceof Double ); assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!", JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof Double ); /** * This test documents a need for BigDecimal conversion. */ Object obj = JSONObject.stringToValue( "299792.457999999984" ); assertTrue( "evaluates to 299792.458 doubld instead of 299792.457999999984 BigDecimal!", obj.equals(new Double(299792.458)) ); assertTrue( "1 should be an Integer!", JSONObject.stringToValue( "1" ) instanceof Integer ); assertTrue( "Integer.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer ); assertTrue( "Large integers should be a Long!", JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); assertTrue( "Long.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); String str = new BigInteger( new Long( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString(); assertTrue( "Really large integers currently evaluate to string", JSONObject.stringToValue(str).equals("9223372036854775808")); } /** * This test documents numeric values which could be numerically * handled as BigDecimal or BigInteger. It helps determine what outputs * will change if those types are supported. */ @Test public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { // Valid JSON Numbers, probably should return BigDecimal or BigInteger objects String str = "{"+ "\"numberWithDecimals\":299792.457999999984,"+ "\"largeNumber\":12345678901234567890,"+ "\"preciseNumber\":0.2000000000000000111,"+ "\"largeExponent\":-23.45e2327"+ "}"; JSONObject jsonObject = new JSONObject(str); // Comes back as a double, but loses precision assertTrue( "numberWithDecimals currently evaluates to double 299792.458", jsonObject.get( "numberWithDecimals" ).equals( new Double( "299792.458" ) ) ); Object obj = jsonObject.get( "largeNumber" ); assertTrue("largeNumber currently evaluates to string", "12345678901234567890".equals(obj)); // comes back as a double but loses precision assertTrue( "preciseNumber currently evaluates to double 0.2", jsonObject.get( "preciseNumber" ).equals(new Double(0.2))); obj = jsonObject.get( "largeExponent" ); assertTrue("largeExponent should currently evaluates as a string", "-23.45e2327".equals(obj)); } /** * This test documents how JSON-Java handles invalid numeric input. */ @Test public void jsonInvalidNumberValues() { // Number-notations supported by Java and invalid as JSON String str = "{"+ "\"hexNumber\":-0x123,"+ "\"tooManyZeros\":00,"+ "\"negativeInfinite\":-Infinity,"+ "\"negativeNaN\":-NaN,"+ "\"negativeFraction\":-.01,"+ "\"tooManyZerosFraction\":00.001,"+ "\"negativeHexFloat\":-0x1.fffp1,"+ "\"hexFloat\":0x1.0P-1074,"+ "\"floatIdentifier\":0.1f,"+ "\"doubleIdentifier\":0.1d"+ "}"; JSONObject jsonObject = new JSONObject(str); Object obj; obj = jsonObject.get( "hexNumber" ); assertFalse( "hexNumber must not be a number (should throw exception!?)", obj instanceof Number ); assertTrue("hexNumber currently evaluates to string", obj.equals("-0x123")); assertTrue( "tooManyZeros currently evaluates to string", jsonObject.get( "tooManyZeros" ).equals("00")); obj = jsonObject.get("negativeInfinite"); assertTrue( "negativeInfinite currently evaluates to string", obj.equals("-Infinity")); obj = jsonObject.get("negativeNaN"); assertTrue( "negativeNaN currently evaluates to string", obj.equals("-NaN")); assertTrue( "negativeFraction currently evaluates to double -0.01", jsonObject.get( "negativeFraction" ).equals(new Double(-0.01))); assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", jsonObject.get( "tooManyZerosFraction" ).equals(new Double(0.001))); assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875", jsonObject.get( "negativeHexFloat" ).equals(new Double(-3.99951171875))); assertTrue("hexFloat currently evaluates to double 4.9E-324", jsonObject.get("hexFloat").equals(new Double(4.9E-324))); assertTrue("floatIdentifier currently evaluates to double 0.1", jsonObject.get("floatIdentifier").equals(new Double(0.1))); assertTrue("doubleIdentifier currently evaluates to double 0.1", jsonObject.get("doubleIdentifier").equals(new Double(0.1))); } /** * Tests how JSONObject get[type] handles incorrect types */ @Test public void jsonObjectNonAndWrongValues() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"trueStrKey\":\"true\","+ "\"falseStrKey\":\"false\","+ "\"stringKey\":\"hello world!\","+ "\"intKey\":42,"+ "\"intStrKey\":\"43\","+ "\"longKey\":1234567890123456789,"+ "\"longStrKey\":\"987654321098765432\","+ "\"doubleKey\":-23.45e7,"+ "\"doubleStrKey\":\"00001.000\","+ "\"arrayKey\":[0,1,2],"+ "\"objectKey\":{\"myKey\":\"myVal\"}"+ "}"; JSONObject jsonObject = new JSONObject(str); try { jsonObject.getBoolean("nonKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("expecting an exception message", "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); } try { jsonObject.getBoolean("stringKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a Boolean.". equals(e.getMessage())); } try { jsonObject.getString("nonKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getString("trueKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"trueKey\"] not a string.". equals(e.getMessage())); } try { jsonObject.getDouble("nonKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getDouble("stringKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a number.". equals(e.getMessage())); } try { jsonObject.getInt("nonKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getInt("stringKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not an int.". equals(e.getMessage())); } try { jsonObject.getLong("nonKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getLong("stringKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a long.". equals(e.getMessage())); } try { jsonObject.getJSONArray("nonKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getJSONArray("stringKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a JSONArray.". equals(e.getMessage())); } try { jsonObject.getJSONObject("nonKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getJSONObject("stringKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a JSONObject.". equals(e.getMessage())); } } /** * This test documents an unexpected numeric behavior. * A double that ends with .0 is parsed, serialized, then * parsed again. On the second parse, it has become an int. */ @Test public void unexpectedDoubleToIntConversion() { String key30 = "key30"; String key31 = "key31"; JSONObject jsonObject = new JSONObject(); jsonObject.put(key30, new Double(3.0)); jsonObject.put(key31, new Double(3.1)); assertTrue("3.0 should remain a double", jsonObject.getDouble(key30) == 3); assertTrue("3.1 should remain a double", jsonObject.getDouble(key31) == 3.1); // turns 3.0 into 3. String serializedString = jsonObject.toString(); JSONObject deserialized = new JSONObject(serializedString); assertTrue("3.0 is now an int", deserialized.get(key30) instanceof Integer); assertTrue("3.0 can still be interpreted as a double", deserialized.getDouble(key30) == 3.0); assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); } /** * Document behaviors of big numbers. Includes both JSONObject * and JSONArray tests */ @Test public void bigNumberOperations() { /** * JSONObject tries to parse BigInteger as a bean, but it only has * one getter, getLowestBitSet(). The value is lost and an unhelpful * value is stored. This should be fixed. */ BigInteger bigInteger = new BigInteger("123456789012345678901234567890"); JSONObject jsonObject = new JSONObject(bigInteger); Object obj = jsonObject.get("lowestSetBit"); assertTrue("JSONObject only has 1 value", jsonObject.length() == 1); assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet", obj instanceof Integer); assertTrue("this bigInteger lowestBitSet happens to be 1", obj.equals(1)); /** * JSONObject tries to parse BigDecimal as a bean, but it has * no getters, The value is lost and no value is stored. * This should be fixed. */ BigDecimal bigDecimal = new BigDecimal( "123456789012345678901234567890.12345678901234567890123456789"); jsonObject = new JSONObject(bigDecimal); assertTrue("large bigDecimal is not stored", jsonObject.length() == 0); /** * JSONObject put(String, Object) method stores and serializes * bigInt and bigDec correctly. Nothing needs to change. */ jsonObject = new JSONObject(); jsonObject.put("bigInt", bigInteger); assertTrue("jsonObject.put() handles bigInt correctly", jsonObject.get("bigInt").equals(bigInteger)); assertTrue("jsonObject.getBigInteger() handles bigInt correctly", jsonObject.getBigInteger("bigInt").equals(bigInteger)); assertTrue("jsonObject.optBigInteger() handles bigInt correctly", jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); assertTrue("jsonObject serializes bigInt correctly", jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}")); jsonObject = new JSONObject(); jsonObject.put("bigDec", bigDecimal); assertTrue("jsonObject.put() handles bigDec correctly", jsonObject.get("bigDec").equals(bigDecimal)); assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); assertTrue("jsonObject serializes bigDec correctly", jsonObject.toString().equals( "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); /** * exercise some exceptions */ try { jsonObject.getBigDecimal("bigInt"); assertTrue("expected an exeption", false); } catch (JSONException ignored) {} obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE); assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); try { jsonObject.getBigInteger("bigDec"); assertTrue("expected an exeption", false); } catch (JSONException ignored) {} jsonObject.put("stringKey", "abc"); try { jsonObject.getBigDecimal("stringKey"); assertTrue("expected an exeption", false); } catch (JSONException ignored) {} obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); assertTrue("expected BigInteger", obj.equals(BigInteger.ONE)); /** * JSONObject.numberToString() works correctly, nothing to change. */ String str = JSONObject.numberToString(bigInteger); assertTrue("numberToString() handles bigInteger correctly", str.equals("123456789012345678901234567890")); str = JSONObject.numberToString(bigDecimal); assertTrue("numberToString() handles bigDecimal correctly", str.equals("123456789012345678901234567890.12345678901234567890123456789")); /** * JSONObject.stringToValue() turns bigInt into an accurate string, * and rounds bigDec. This incorrect, but users may have come to * expect this behavior. Change would be marginally better, but * might inconvenience users. */ obj = JSONObject.stringToValue(bigInteger.toString()); assertTrue("stringToValue() turns bigInteger string into string", obj instanceof String); obj = JSONObject.stringToValue(bigDecimal.toString()); assertTrue("stringToValue() changes bigDecimal string", !obj.toString().equals(bigDecimal.toString())); /** * wrap() vs put() big number behavior is now the same. */ // bigInt map ctor Map<String, Object> map = new HashMap<String, Object>(); map.put("bigInt", bigInteger); jsonObject = new JSONObject(map); String actualFromMapStr = jsonObject.toString(); assertTrue("bigInt in map (or array or bean) is a string", actualFromMapStr.equals( "{\"bigInt\":123456789012345678901234567890}")); // bigInt put jsonObject = new JSONObject(); jsonObject.put("bigInt", bigInteger); String actualFromPutStr = jsonObject.toString(); assertTrue("bigInt from put is a number", actualFromPutStr.equals( "{\"bigInt\":123456789012345678901234567890}")); // bigDec map ctor map = new HashMap<String, Object>(); map.put("bigDec", bigDecimal); jsonObject = new JSONObject(map); actualFromMapStr = jsonObject.toString(); assertTrue("bigDec in map (or array or bean) is a bigDec", actualFromMapStr.equals( "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); // bigDec put jsonObject = new JSONObject(); jsonObject.put("bigDec", bigDecimal); actualFromPutStr = jsonObject.toString(); assertTrue("bigDec from put is a number", actualFromPutStr.equals( "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); // bigInt,bigDec put JSONArray jsonArray = new JSONArray(); jsonArray.put(bigInteger); jsonArray.put(bigDecimal); actualFromPutStr = jsonArray.toString(); assertTrue("bigInt, bigDec from put is a number", actualFromPutStr.equals( "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger)); assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal)); assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); jsonArray.put(Boolean.TRUE); try { jsonArray.getBigInteger(2); assertTrue("should not be able to get big int", false); } catch (Exception ignored) {} try { jsonArray.getBigDecimal(2); assertTrue("should not be able to get big dec", false); } catch (Exception ignored) {} assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE)); assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE)); // bigInt,bigDec list ctor List<Object> list = new ArrayList<Object>(); list.add(bigInteger); list.add(bigDecimal); jsonArray = new JSONArray(list); String actualFromListStr = jsonArray.toString(); assertTrue("bigInt, bigDec in list is a bigInt, bigDec", actualFromListStr.equals( "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); // bigInt bean ctor MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890")); jsonObject = new JSONObject(myBigNumberBean); String actualFromBeanStr = jsonObject.toString(); // can't do a full string compare because mockery adds an extra key/value assertTrue("bigInt from bean ctor is a bigInt", actualFromBeanStr.contains("123456789012345678901234567890")); // bigDec bean ctor myBigNumberBean = mock(MyBigNumberBean.class); when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789")); jsonObject = new JSONObject(myBigNumberBean); actualFromBeanStr = jsonObject.toString(); // can't do a full string compare because mockery adds an extra key/value assertTrue("bigDec from bean ctor is a bigDec", actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789")); // bigInt,bigDec wrap() obj = JSONObject.wrap(bigInteger); assertTrue("wrap() returns big num",obj.equals(bigInteger)); obj = JSONObject.wrap(bigDecimal); assertTrue("wrap() returns string",obj.equals(bigDecimal)); } /** * The purpose for the static method getNames() methods are not clear. * This method is not called from within JSON-Java. Most likely * uses are to prep names arrays for: * JSONObject(JSONObject jo, String[] names) * JSONObject(Object object, String names[]), */ @Test public void jsonObjectNames() { JSONObject jsonObject; // getNames() from null JSONObject assertTrue("null names from null Object", null == JSONObject.getNames((Object)null)); // getNames() from object with no fields assertTrue("null names from Object with no fields", null == JSONObject.getNames(new MyJsonString())); // getNames from new JSONOjbect jsonObject = new JSONObject(); String [] names = JSONObject.getNames(jsonObject); assertTrue("names should be null", names == null); // getNames() from empty JSONObject String emptyStr = "{}"; jsonObject = new JSONObject(emptyStr); assertTrue("empty JSONObject should have null names", null == JSONObject.getNames(jsonObject)); // getNames() from JSONObject String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"stringKey\":\"hello world!\","+ "}"; jsonObject = new JSONObject(str); names = JSONObject.getNames(jsonObject); JSONArray jsonArray = new JSONArray(names); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonArray.toString()); List<?> docList = JsonPath.read(doc, "$"); assertTrue("expected 3 items", docList.size() == 3); assertTrue( "expected to find trueKey", ((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); assertTrue( "expected to find falseKey", ((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); assertTrue( "expected to find stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); /** * getNames() from an enum with properties has an interesting result. * It returns the enum values, not the selected enum properties */ MyEnumField myEnumField = MyEnumField.VAL1; names = JSONObject.getNames(myEnumField); // validate JSON jsonArray = new JSONArray(names); doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonArray.toString()); docList = JsonPath.read(doc, "$"); assertTrue("expected 3 items", docList.size() == 3); assertTrue( "expected to find VAL1", ((List<?>) JsonPath.read(doc, "$[?(@=='VAL1')]")).size() == 1); assertTrue( "expected to find VAL2", ((List<?>) JsonPath.read(doc, "$[?(@=='VAL2')]")).size() == 1); assertTrue( "expected to find VAL3", ((List<?>) JsonPath.read(doc, "$[?(@=='VAL3')]")).size() == 1); /** * A bean is also an object. But in order to test the static * method getNames(), this particular bean needs some public * data members. */ MyPublicClass myPublicClass = new MyPublicClass(); names = JSONObject.getNames(myPublicClass); // validate JSON jsonArray = new JSONArray(names); doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonArray.toString()); docList = JsonPath.read(doc, "$"); assertTrue("expected 2 items", docList.size() == 2); assertTrue( "expected to find publicString", ((List<?>) JsonPath.read(doc, "$[?(@=='publicString')]")).size() == 1); assertTrue( "expected to find publicInt", ((List<?>) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1); } /** * Populate a JSONArray from an empty JSONObject names() method. * It should be empty. */ @Test public void emptyJsonObjectNamesToJsonAray() { JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = jsonObject.names(); assertTrue("jsonArray should be null", jsonArray == null); } /** * Populate a JSONArray from a JSONObject names() method. * Confirm that it contains the expected names. */ @Test public void jsonObjectNamesToJsonAray() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"stringKey\":\"hello world!\","+ "}"; JSONObject jsonObject = new JSONObject(str); JSONArray jsonArray = jsonObject.names(); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected to find trueKey", ((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); assertTrue("expected to find falseKey", ((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); assertTrue("expected to find stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); } /** * Exercise the JSONObject increment() method. */ @Test public void jsonObjectIncrement() { String str = "{"+ "\"keyLong\":9999999991,"+ "\"keyDouble\":1.1"+ "}"; JSONObject jsonObject = new JSONObject(str); jsonObject.increment("keyInt"); jsonObject.increment("keyInt"); jsonObject.increment("keyLong"); jsonObject.increment("keyDouble"); jsonObject.increment("keyInt"); jsonObject.increment("keyLong"); jsonObject.increment("keyDouble"); /** * JSONObject constructor won't handle these types correctly, but * adding them via put works. */ jsonObject.put("keyFloat", new Float(1.1)); jsonObject.put("keyBigInt", new BigInteger("123456789123456789123456789123456780")); jsonObject.put("keyBigDec", new BigDecimal("123456789123456789123456789123456780.1")); jsonObject.increment("keyFloat"); jsonObject.increment("keyFloat"); jsonObject.increment("keyBigInt"); jsonObject.increment("keyBigDec"); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6); assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/keyInt"))); assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(jsonObject.query("/keyLong"))); assertTrue("expected 3.1", Double.valueOf(3.1).equals(jsonObject.query("/keyDouble"))); assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(jsonObject.query("/keyBigInt"))); assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(jsonObject.query("/keyBigDec"))); assertTrue("expected 3.0999999046325684", Double.valueOf(3.0999999046325684).equals(jsonObject.query("/keyFloat"))); /** * float f = 3.1f; double df = (double) f; double d = 3.1d; * System.out.println * (Integer.toBinaryString(Float.floatToRawIntBits(f))); * System.out.println * (Long.toBinaryString(Double.doubleToRawLongBits(df))); * System.out.println * (Long.toBinaryString(Double.doubleToRawLongBits(d))); * * - Float: * seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm * 1000000010001100110011001100110 * - Double * seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * 10000000 10001100110011001100110 * 100000000001000110011001100110011000000000000000000000000000000 * 100000000001000110011001100110011001100110011001100110011001101 */ /** * Examples of well documented but probably unexpected behavior in * java / with 32-bit float to 64-bit float conversion. */ assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d ); assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d ); Double d1 = new Double( 1.1f ); Double d2 = new Double( "1.1f" ); assertFalse( "Document implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) ); assertTrue( "Correctly converting float to double via base10 (string) representation!", new Double( 3.1d ).equals( new Double( new Float( 3.1f ).toString() ) ) ); // Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject JSONObject jo = new JSONObject(); jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) ); JSONObject inc = new JSONObject(); inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float ); inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double! // this.put(key, (Float) value + 1); // 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done. // 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects! // 3. A float+float operation will be performed and results into a float primitive. // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Double ); // correct implementation (with change of behavior) would be: // this.put(key, new Float((Float) value + 1)); // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not // really in the the scope of a JSON-library (IMHO.) } /** * Exercise JSONObject numberToString() method */ @Test public void jsonObjectNumberToString() { String str; Double dVal; Integer iVal = 1; str = JSONObject.numberToString(iVal); assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str)); dVal = 12.34; str = JSONObject.numberToString(dVal); assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); dVal = 12.34e27; str = JSONObject.numberToString(dVal); assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); // trailing .0 is truncated, so it doesn't quite match toString() dVal = 5000000.0000000; str = JSONObject.numberToString(dVal); assertTrue("expected 5000000 actual "+str, str.equals("5000000")); } /** * Exercise JSONObject put() and similar() methods */ @Test public void jsonObjectPut() { String expectedStr = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"arrayKey\":[0,1,2],"+ "\"objectKey\":{"+ "\"myKey1\":\"myVal1\","+ "\"myKey2\":\"myVal2\","+ "\"myKey3\":\"myVal3\","+ "\"myKey4\":\"myVal4\""+ "}"+ "}"; JSONObject jsonObject = new JSONObject(); jsonObject.put("trueKey", true); jsonObject.put("falseKey", false); Integer [] intArray = { 0, 1, 2 }; jsonObject.put("arrayKey", Arrays.asList(intArray)); Map<String, Object> myMap = new HashMap<String, Object>(); myMap.put("myKey1", "myVal1"); myMap.put("myKey2", "myVal2"); myMap.put("myKey3", "myVal3"); myMap.put("myKey4", "myVal4"); jsonObject.put("objectKey", myMap); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected 3 arrayKey items", ((List<?>)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); assertTrue("expected 4 objectKey items", ((Map<?,?>)(JsonPath.read(doc, "$.objectKey"))).size() == 4); assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); jsonObject.remove("trueKey"); JSONObject expectedJsonObject = new JSONObject(expectedStr); assertTrue("unequal jsonObjects should not be similar", !jsonObject.similar(expectedJsonObject)); assertTrue("jsonObject should not be similar to jsonArray", !jsonObject.similar(new JSONArray())); String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr); JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr); assertTrue("different values should not be similar", !aCompareValueJsonObject.similar(bCompareValueJsonObject)); String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr); JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr); assertTrue("different nested JSONObjects should not be similar", !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr); JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); assertTrue("different nested JSONArrays should not be similar", !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); } /** * Exercise JSONObject toString() method */ @Test public void jsonObjectToString() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"arrayKey\":[0,1,2],"+ "\"objectKey\":{"+ "\"myKey1\":\"myVal1\","+ "\"myKey2\":\"myVal2\","+ "\"myKey3\":\"myVal3\","+ "\"myKey4\":\"myVal4\""+ "}"+ "}"; JSONObject jsonObject = new JSONObject(str); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected 3 arrayKey items", ((List<?>)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); assertTrue("expected 4 objectKey items", ((Map<?,?>)(JsonPath.read(doc, "$.objectKey"))).size() == 4); assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); } /** * Explores how JSONObject handles maps. Insert a string/string map * as a value in a JSONObject. It will remain a map. Convert the * JSONObject to string, then create a new JSONObject from the string. * In the new JSONObject, the value will be stored as a nested JSONObject. * Confirm that map and nested JSONObject have the same contents. */ @Test public void jsonObjectToStringSuppressWarningOnCastToMap() { JSONObject jsonObject = new JSONObject(); Map<String, String> map = new HashMap<>(); map.put("abc", "def"); jsonObject.put("key", map); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 1 key item", ((Map<?,?>)(JsonPath.read(doc, "$.key"))).size() == 1); assertTrue("expected def", "def".equals(jsonObject.query("/key/abc"))); } /** * Explores how JSONObject handles collections. Insert a string collection * as a value in a JSONObject. It will remain a collection. Convert the * JSONObject to string, then create a new JSONObject from the string. * In the new JSONObject, the value will be stored as a nested JSONArray. * Confirm that collection and nested JSONArray have the same contents. */ @Test public void jsonObjectToStringSuppressWarningOnCastToCollection() { JSONObject jsonObject = new JSONObject(); Collection<String> collection = new ArrayList<String>(); collection.add("abc"); // ArrayList will be added as an object jsonObject.put("key", collection); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 1 key item", ((List<?>)(JsonPath.read(doc, "$.key"))).size() == 1); assertTrue("expected abc", "abc".equals(jsonObject.query("/key/0"))); } /** * Exercises the JSONObject.valueToString() method for various types */ @Test public void valueToString() { assertTrue("null valueToString() incorrect", "null".equals(JSONObject.valueToString(null))); MyJsonString jsonString = new MyJsonString(); assertTrue("jsonstring valueToString() incorrect", "my string".equals(JSONObject.valueToString(jsonString))); assertTrue("boolean valueToString() incorrect", "true".equals(JSONObject.valueToString(Boolean.TRUE))); assertTrue("non-numeric double", "null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY))); String jsonObjectStr = "{"+ "\"key1\":\"val1\","+ "\"key2\":\"val2\","+ "\"key3\":\"val3\""+ "}"; JSONObject jsonObject = new JSONObject(jsonObjectStr); assertTrue("jsonObject valueToString() incorrect", JSONObject.valueToString(jsonObject).equals(jsonObject.toString())); String jsonArrayStr = "[1,2,3]"; JSONArray jsonArray = new JSONArray(jsonArrayStr); assertTrue("jsonArra valueToString() incorrect", JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); Map<String, String> map = new HashMap<String, String>(); map.put("key1", "val1"); map.put("key2", "val2"); map.put("key3", "val3"); assertTrue("map valueToString() incorrect", jsonObject.toString().equals(JSONObject.valueToString(map))); Collection<Integer> collection = new ArrayList<Integer>(); collection.add(new Integer(1)); collection.add(new Integer(2)); collection.add(new Integer(3)); assertTrue("collection valueToString() expected: "+ jsonArray.toString()+ " actual: "+ JSONObject.valueToString(collection), jsonArray.toString().equals(JSONObject.valueToString(collection))); Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; assertTrue("array valueToString() incorrect", jsonArray.toString().equals(JSONObject.valueToString(array))); } @Test public void valueToStringConfirmException() { Map<Integer, String> myMap = new HashMap<Integer, String>(); myMap.put(1, "myValue"); // this is the test, it should not throw an exception String str = JSONObject.valueToString(myMap); // confirm result, just in case Object doc = Configuration.defaultConfiguration().jsonProvider().parse(str); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected myValue", "myValue".equals(JsonPath.read(doc, "$.1"))); } /** * Exercise the JSONObject wrap() method. Sometimes wrap() will change * the object being wrapped, other times not. The purpose of wrap() is * to ensure the value is packaged in a way that is compatible with how * a JSONObject value or JSONArray value is supposed to be stored. */ @Test public void wrapObject() { // wrap(null) returns NULL assertTrue("null wrap() incorrect", JSONObject.NULL == JSONObject.wrap(null)); // wrap(Integer) returns Integer Integer in = new Integer(1); assertTrue("Integer wrap() incorrect", in == JSONObject.wrap(in)); /** * This test is to document the preferred behavior if BigDecimal is * supported. Previously bd returned as a string, since it * is recognized as being a Java package class. Now with explicit * support for big numbers, it remains a BigDecimal */ Object bdWrap = JSONObject.wrap(BigDecimal.ONE); assertTrue("BigDecimal.ONE evaluates to ONE", bdWrap.equals(BigDecimal.ONE)); // wrap JSONObject returns JSONObject String jsonObjectStr = "{"+ "\"key1\":\"val1\","+ "\"key2\":\"val2\","+ "\"key3\":\"val3\""+ "}"; JSONObject jsonObject = new JSONObject(jsonObjectStr); assertTrue("JSONObject wrap() incorrect", jsonObject == JSONObject.wrap(jsonObject)); // wrap collection returns JSONArray Collection<Integer> collection = new ArrayList<Integer>(); collection.add(new Integer(1)); collection.add(new Integer(2)); collection.add(new Integer(3)); JSONArray jsonArray = (JSONArray) (JSONObject.wrap(collection)); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); // wrap Array returns JSONArray Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(integerArrayJsonArray.toString()); assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); // wrap map returns JSONObject Map<String, String> map = new HashMap<String, String>(); map.put("key1", "val1"); map.put("key2", "val2"); map.put("key3", "val3"); JSONObject mapJsonObject = (JSONObject) (JSONObject.wrap(map)); // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(mapJsonObject.toString()); assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected val1", "val1".equals(mapJsonObject.query("/key1"))); assertTrue("expected val2", "val2".equals(mapJsonObject.query("/key2"))); assertTrue("expected val3", "val3".equals(mapJsonObject.query("/key3"))); } /** * RFC 7159 defines control characters to be U+0000 through U+001F. This test verifies that the parser is checking for these in expected ways. */ @Test public void jsonObjectParseControlCharacters(){ for(int i = 0;i<=0x001f;i++){ final String charString = String.valueOf((char)i); final String source = "{\"key\":\""+charString+"\"}"; try { JSONObject jo = new JSONObject(source); assertTrue("Expected "+charString+"("+i+") in the JSON Object but did not find it.",charString.equals(jo.getString("key"))); } catch (JSONException ex) { assertTrue("Only \\0 (U+0000), \\n (U+000A), and \\r (U+000D) should cause an error. Instead "+charString+"("+i+") caused an error", i=='\0' || i=='\n' || i=='\r' ); } } } /** * Explore how JSONObject handles parsing errors. */ @Test public void jsonObjectParsingErrors() { try { // does not start with '{' String str = "abc"; new JSONObject(str); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "A JSONObject text must begin with '{' at 1 [character 2 line 1]". equals(e.getMessage())); } try { // does not end with '}' String str = "{"; new JSONObject(str); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "A JSONObject text must end with '}' at 2 [character 3 line 1]". equals(e.getMessage())); } try { // key with no ':' String str = "{\"myKey\" = true}"; new JSONObject(str); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "Expected a ':' after a key at 10 [character 11 line 1]". equals(e.getMessage())); } try { // entries with no ',' separator String str = "{\"myKey\":true \"myOtherKey\":false}"; new JSONObject(str); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "Expected a ',' or '}' at 15 [character 16 line 1]". equals(e.getMessage())); } try { // append to wrong key String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.append("myKey", "hello"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[myKey] is not a JSONArray.". equals(e.getMessage())); } try { // increment wrong key String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.increment("myKey"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "Unable to increment [\"myKey\"].". equals(e.getMessage())); } try { // invalid key String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.get(null); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "Null key.". equals(e.getMessage())); } try { // invalid numberToString() JSONObject.numberToString((Number)null); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "Null pointer". equals(e.getMessage())); } try { // null put key JSONObject jsonObject = new JSONObject("{}"); jsonObject.put(null, 0); assertTrue("Expected an exception", false); } catch (NullPointerException ignored) { } try { // multiple putOnce key JSONObject jsonObject = new JSONObject("{}"); jsonObject.putOnce("hello", "world"); jsonObject.putOnce("hello", "world!"); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("", true); } try { // test validity of invalid double JSONObject.testValidity(Double.NaN); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("", true); } try { // test validity of invalid float JSONObject.testValidity(Float.NEGATIVE_INFINITY); assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("", true); } } /** * Confirm behavior when putOnce() is called with null parameters */ @Test public void jsonObjectPutOnceNull() { JSONObject jsonObject = new JSONObject(); jsonObject.putOnce(null, null); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** * Exercise JSONObject opt(key, default) method. */ @Test public void jsonObjectOptDefault() { String str = "{\"myKey\": \"myval\", \"hiKey\": null}"; JSONObject jsonObject = new JSONObject(str); assertTrue("optBigDecimal() should return default BigDecimal", BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); assertTrue("optBigInteger() should return default BigInteger", BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); assertTrue("optBoolean() should return default boolean", jsonObject.optBoolean("myKey", true)); assertTrue("optInt() should return default int", 42 == jsonObject.optInt("myKey", 42)); assertTrue("optEnum() should return default Enum", MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); assertTrue("optJSONArray() should return null ", null==jsonObject.optJSONArray("myKey")); assertTrue("optJSONObject() should return null ", null==jsonObject.optJSONObject("myKey")); assertTrue("optLong() should return default long", 42 == jsonObject.optLong("myKey", 42)); assertTrue("optDouble() should return default double", 42.3 == jsonObject.optDouble("myKey", 42.3)); assertTrue("optString() should return default string", "hi".equals(jsonObject.optString("hiKey", "hi"))); } /** * Exercise JSONObject opt(key, default) method when the key doesn't exist. */ @Test public void jsonObjectOptNoKey() { JSONObject jsonObject = new JSONObject(); assertTrue("optBigDecimal() should return default BigDecimal", BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); assertTrue("optBigInteger() should return default BigInteger", BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); assertTrue("optBoolean() should return default boolean", jsonObject.optBoolean("myKey", true)); assertTrue("optInt() should return default int", 42 == jsonObject.optInt("myKey", 42)); assertTrue("optEnum() should return default Enum", MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); assertTrue("optJSONArray() should return null ", null==jsonObject.optJSONArray("myKey")); assertTrue("optJSONObject() should return null ", null==jsonObject.optJSONObject("myKey")); assertTrue("optLong() should return default long", 42 == jsonObject.optLong("myKey", 42)); assertTrue("optDouble() should return default double", 42.3 == jsonObject.optDouble("myKey", 42.3)); assertTrue("optString() should return default string", "hi".equals(jsonObject.optString("hiKey", "hi"))); } /** * Verifies that the opt methods properly convert string values. */ @Test public void jsonObjectOptStringConversion() { JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\"}"); assertTrue("unexpected optBoolean value",jo.optBoolean("true",false)==true); assertTrue("unexpected optBoolean value",jo.optBoolean("false",true)==false); assertTrue("unexpected optInt value",jo.optInt("int",0)==123); assertTrue("unexpected optLong value",jo.optLong("int",0)==123); assertTrue("unexpected optDouble value",jo.optDouble("int",0.0)==123.0); assertTrue("unexpected optBigInteger value",jo.optBigInteger("int",BigInteger.ZERO).compareTo(new BigInteger("123"))==0); assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); } /** * Confirm behavior when JSONObject put(key, null object) is called */ @Test public void jsonObjectputNull() { // put null should remove the item. String str = "{\"myKey\": \"myval\"}"; JSONObject jsonObjectRemove = new JSONObject(str); jsonObjectRemove.remove("myKey"); JSONObject jsonObjectPutNull = new JSONObject(str); jsonObjectPutNull.put("myKey", (Object) null); // validate JSON assertTrue("jsonObject should be empty", jsonObjectRemove.length() == 0 && jsonObjectPutNull.length() == 0); } /** * Exercise JSONObject quote() method * This purpose of quote() is to ensure that for strings with embedded * quotes, the quotes are properly escaped. */ @Test public void jsonObjectQuote() { String str; str = ""; String quotedStr; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped quotes, found "+quotedStr, "\"\"".equals(quotedStr)); str = "\"\""; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped quotes, found "+quotedStr, "\"\\\"\\\"\"".equals(quotedStr)); str = "</"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped frontslash, found "+quotedStr, "\"<\\/\"".equals(quotedStr)); str = "AB\bC"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped backspace, found "+quotedStr, "\"AB\\bC\"".equals(quotedStr)); str = "ABC\n"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped newline, found "+quotedStr, "\"ABC\\n\"".equals(quotedStr)); str = "AB\fC"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped formfeed, found "+quotedStr, "\"AB\\fC\"".equals(quotedStr)); str = "\r"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped return, found "+quotedStr, "\"\\r\"".equals(quotedStr)); str = "\u1234\u0088"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped unicode, found "+quotedStr, "\"\u1234\\u0088\"".equals(quotedStr)); } /** * Confirm behavior when JSONObject stringToValue() is called for an * empty string */ @Test public void stringToValue() { String str = ""; String valueStr = (String)(JSONObject.stringToValue(str)); assertTrue("stringToValue() expected empty String, found "+valueStr, "".equals(valueStr)); } /** * Confirm behavior when toJSONArray is called with a null value */ @Test public void toJSONArray() { assertTrue("toJSONArray() with null names should be null", null == new JSONObject().toJSONArray(null)); } /** * Exercise the JSONObject write() method */ @Test public void write() { String str = "{\"key\":\"value\"}"; String expectedStr = str; JSONObject jsonObject = new JSONObject(str); StringWriter stringWriter = new StringWriter(); Writer writer = jsonObject.write(stringWriter); String actualStr = writer.toString(); assertTrue("write() expected " +expectedStr+ "but found " +actualStr, expectedStr.equals(actualStr)); } /** * Exercise the JSONObject equals() method */ @Test public void equals() { String str = "{\"key\":\"value\"}"; JSONObject aJsonObject = new JSONObject(str); assertTrue("Same JSONObject should be equal to itself", aJsonObject.equals(aJsonObject)); } /** * JSON null is not the same as Java null. This test examines the differences * in how they are handled by JSON-java. */ @Test public void jsonObjectNullOperations() { /** * The Javadoc for JSONObject.NULL states: * "JSONObject.NULL is equivalent to the value that JavaScript calls null, * whilst Java's null is equivalent to the value that JavaScript calls * undefined." * * Standard ECMA-262 6th Edition / June 2015 (included to help explain the javadoc): * undefined value: primitive value used when a variable has not been assigned a value * Undefined type: type whose sole value is the undefined value * null value: primitive value that represents the intentional absence of any object value * Null type: type whose sole value is the null value * Java SE8 language spec (included to help explain the javadoc): * The Kinds of Types and Values ... * There is also a special null type, the type of the expression null, which has no name. * Because the null type has no name, it is impossible to declare a variable of the null * type or to cast to the null type. The null reference is the only possible value of an * expression of null type. The null reference can always be assigned or cast to any reference type. * In practice, the programmer can ignore the null type and just pretend that null is merely * a special literal that can be of any reference type. * Extensible Markup Language (XML) 1.0 Fifth Edition / 26 November 2008 * No mention of null * ECMA-404 1st Edition / October 2013: * JSON Text ... * These are three literal name tokens: ... * null * * There seems to be no best practice to follow, it's all about what we * want the code to do. */ // add JSONObject.NULL then convert to string in the manner of XML.toString() JSONObject jsonObjectJONull = new JSONObject(); Object obj = JSONObject.NULL; jsonObjectJONull.put("key", obj); Object value = jsonObjectJONull.opt("key"); assertTrue("opt() JSONObject.NULL should find JSONObject.NULL", obj.equals(value)); value = jsonObjectJONull.get("key"); assertTrue("get() JSONObject.NULL should find JSONObject.NULL", obj.equals(value)); if (value == null) { value = ""; } String string = value instanceof String ? (String)value : null; assertTrue("XML toString() should convert JSONObject.NULL to null", string == null); // now try it with null JSONObject jsonObjectNull = new JSONObject(); obj = null; jsonObjectNull.put("key", obj); value = jsonObjectNull.opt("key"); assertTrue("opt() null should find null", value == null); if (value == null) { value = ""; } string = value instanceof String ? (String)value : null; assertTrue("should convert null to empty string", "".equals(string)); try { value = jsonObjectNull.get("key"); assertTrue("get() null should throw exception", false); } catch (Exception ignored) {} /** * XML.toString() then goes on to do something with the value * if the key val is "content", then value.toString() will be * called. This will evaluate to "null" for JSONObject.NULL, * and the empty string for null. * But if the key is anything else, then JSONObject.NULL will be emitted * as <key>null</key> and null will be emitted as "" */ String sJONull = XML.toString(jsonObjectJONull); assertTrue("JSONObject.NULL should emit a null value", "<key>null</key>".equals(sJONull)); String sNull = XML.toString(jsonObjectNull); assertTrue("null should emit an empty string", "".equals(sNull)); } @Test(expected = JSONPointerException.class) public void queryWithNoResult() { new JSONObject().query("/a/b"); } @Test public void optQueryWithNoResult() { assertNull(new JSONObject().optQuery("/a/b")); } @Test(expected = IllegalArgumentException.class) public void optQueryWithSyntaxError() { new JSONObject().optQuery("invalid"); } @Test(expected = JSONException.class) public void invalidEscapeSequence() { String json = "{ \"\\url\": \"value\" }"; new JSONObject(json); } }
package org.json.junit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.json.CDL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONPointerException; import org.json.XML; import org.json.junit.data.BrokenToString; import org.json.junit.data.ExceptionalBean; import org.json.junit.data.Fraction; import org.json.junit.data.GenericBean; import org.json.junit.data.GenericBeanInt; import org.json.junit.data.MyBean; import org.json.junit.data.MyBigNumberBean; import org.json.junit.data.MyEnum; import org.json.junit.data.MyEnumField; import org.json.junit.data.MyJsonString; import org.json.junit.data.MyNumber; import org.json.junit.data.MyNumberContainer; import org.json.junit.data.MyPublicClass; import org.json.junit.data.Singleton; import org.json.junit.data.SingletonEnum; import org.json.junit.data.WeirdList; import org.junit.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; /** * JSONObject, along with JSONArray, are the central classes of the reference app. * All of the other classes interact with them, and JSON functionality would * otherwise be impossible. */ public class JSONObjectTest { /** * JSONObject built from a bean, but only using a null value. * Nothing good is expected to happen. * Expects NullPointerException */ @Test(expected=NullPointerException.class) public void jsonObjectByNullBean() { assertNull("Expected an exception",new JSONObject((MyBean)null)); } /** * The JSON parser is permissive of unambiguous unquoted keys and values. * Such JSON text should be allowed, even if it does not strictly conform * to the spec. However, after being parsed, toString() should emit strictly * conforming JSON text. */ @Test public void unquotedText() { String str = "{key1:value1, key2:42}"; JSONObject jsonObject = new JSONObject(str); String textStr = jsonObject.toString(); assertTrue("expected key1", textStr.contains("\"key1\"")); assertTrue("expected value1", textStr.contains("\"value1\"")); assertTrue("expected key2", textStr.contains("\"key2\"")); assertTrue("expected 42", textStr.contains("42")); } @Test public void testLongFromString(){ String str = "26315000000253009"; JSONObject json = new JSONObject(); json.put("key", str); final Object actualKey = json.opt("key"); assert str.equals(actualKey) : "Incorrect key value. Got " + actualKey + " expected " + str; final long actualLong = json.optLong("key"); assert actualLong != 0 : "Unable to extract long value for string " + str; assert 26315000000253009L == actualLong : "Incorrect key value. Got " + actualLong + " expected " + str; final String actualString = json.optString("key"); assert str.equals(actualString) : "Incorrect key value. Got " + actualString + " expected " + str; } /** * A JSONObject can be created with no content */ @Test public void emptyJsonObject() { JSONObject jsonObject = new JSONObject(); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** * A JSONObject can be created from another JSONObject plus a list of names. * In this test, some of the starting JSONObject keys are not in the * names list. */ @Test public void jsonObjectByNames() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"nullKey\":null,"+ "\"stringKey\":\"hello world!\","+ "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ "\"intKey\":42,"+ "\"doubleKey\":-23.45e67"+ "}"; String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"}; JSONObject jsonObject = new JSONObject(str); // validate JSON JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString()); assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4); assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey"))); assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey"))); assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey"))); assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObjectByName.query("/doubleKey"))); } /** * JSONObjects can be built from a Map<String, Object>. * In this test the map is null. * the JSONObject(JsonTokener) ctor is not tested directly since it already * has full coverage from other tests. */ @Test public void jsonObjectByNullMap() { Map<String, Object> map = null; JSONObject jsonObject = new JSONObject(map); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** * JSONObjects can be built from a Map<String, Object>. * In this test all of the map entries are valid JSON types. */ @Test public void jsonObjectByMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("trueKey", new Boolean(true)); map.put("falseKey", new Boolean(false)); map.put("stringKey", "hello world!"); map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); map.put("intKey", new Long(42)); map.put("doubleKey", new Double(-23.45e67)); JSONObject jsonObject = new JSONObject(map); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6); assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); } /** * Verifies that the constructor has backwards compatability with RAW types pre-java5. */ @Test public void verifyConstructor() { final JSONObject expected = new JSONObject("{\"myKey\":10}"); @SuppressWarnings("rawtypes") Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); JSONObject jaRaw = new JSONObject(myRawC); Map<String, Object> myCStrObj = Collections.singletonMap("myKey", (Object) Integer.valueOf(10)); JSONObject jaStrObj = new JSONObject(myCStrObj); Map<String, Integer> myCStrInt = Collections.singletonMap("myKey", Integer.valueOf(10)); JSONObject jaStrInt = new JSONObject(myCStrInt); Map<?, ?> myCObjObj = Collections.singletonMap((Object) "myKey", (Object) Integer.valueOf(10)); JSONObject jaObjObj = new JSONObject(myCObjObj); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaRaw)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaStrObj)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaStrInt)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaObjObj)); } /** * Tests Number serialization. */ @Test public void verifyNumberOutput(){ /** * MyNumberContainer is a POJO, so call JSONObject(bean), * which builds a map of getter names/values * The only getter is getMyNumber (key=myNumber), * whose return value is MyNumber. MyNumber extends Number, * but is not recognized as such by wrap() per current * implementation, so wrap() returns the default new JSONObject(bean). * The only getter is getNumber (key=number), whose return value is * BigDecimal(42). */ JSONObject jsonObject = new JSONObject(new MyNumberContainer()); String actual = jsonObject.toString(); String expected = "{\"myNumber\":{\"number\":42}}"; assertEquals("Not Equal", expected , actual); /** * JSONObject.put() handles objects differently than the * bean constructor. Where the bean ctor wraps objects before * placing them in the map, put() inserts the object without wrapping. * In this case, a MyNumber instance is the value. * The MyNumber.toString() method is responsible for * returning a reasonable value: the string '42'. */ jsonObject = new JSONObject(); jsonObject.put("myNumber", new MyNumber()); actual = jsonObject.toString(); expected = "{\"myNumber\":42}"; assertEquals("Not Equal", expected , actual); /** * Calls the JSONObject(Map) ctor, which calls wrap() for values. * AtomicInteger is a Number, but is not recognized by wrap(), per * current implementation. However, the type is * 'java.util.concurrent.atomic', so due to the 'java' prefix, * wrap() inserts the value as a string. That is why 42 comes back * wrapped in quotes. */ jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42))); actual = jsonObject.toString(); expected = "{\"myNumber\":\"42\"}"; assertEquals("Not Equal", expected , actual); /** * JSONObject.put() inserts the AtomicInteger directly into the * map not calling wrap(). In toString()->write()->writeValue(), * AtomicInteger is recognized as a Number, and converted via * numberToString() into the unquoted string '42'. */ jsonObject = new JSONObject(); jsonObject.put("myNumber", new AtomicInteger(42)); actual = jsonObject.toString(); expected = "{\"myNumber\":42}"; assertEquals("Not Equal", expected , actual); /** * Calls the JSONObject(Map) ctor, which calls wrap() for values. * Fraction is a Number, but is not recognized by wrap(), per * current implementation. As a POJO, Fraction is handled as a * bean and inserted into a contained JSONObject. It has 2 getters, * for numerator and denominator. */ jsonObject = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2))); assertEquals(1, jsonObject.length()); assertEquals(2, ((JSONObject)(jsonObject.get("myNumber"))).length()); assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject.query("/myNumber/numerator")); assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject.query("/myNumber/denominator")); /** * JSONObject.put() inserts the Fraction directly into the * map not calling wrap(). In toString()->write()->writeValue(), * Fraction is recognized as a Number, and converted via * numberToString() into the unquoted string '4/2'. But the * BigDecimal sanity check fails, so writeValue() defaults * to returning a safe JSON quoted string. Pretty slick! */ jsonObject = new JSONObject(); jsonObject.put("myNumber", new Fraction(4,2)); actual = jsonObject.toString(); expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed assertEquals("Not Equal", expected , actual); } /** * Verifies that the put Collection has backwards compatibility with RAW types pre-java5. */ @Test public void verifyPutCollection() { final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); @SuppressWarnings("rawtypes") Collection myRawC = Collections.singleton(Integer.valueOf(10)); JSONObject jaRaw = new JSONObject(); jaRaw.put("myCollection", myRawC); Collection<Object> myCObj = Collections.singleton((Object) Integer .valueOf(10)); JSONObject jaObj = new JSONObject(); jaObj.put("myCollection", myCObj); Collection<Integer> myCInt = Collections.singleton(Integer .valueOf(10)); JSONObject jaInt = new JSONObject(); jaInt.put("myCollection", myCInt); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaRaw)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaObj)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaInt)); } /** * Verifies that the put Map has backwards compatability with RAW types pre-java5. */ @Test public void verifyPutMap() { final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); @SuppressWarnings("rawtypes") Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); JSONObject jaRaw = new JSONObject(); jaRaw.put("myMap", myRawC); Map<String, Object> myCStrObj = Collections.singletonMap("myKey", (Object) Integer.valueOf(10)); JSONObject jaStrObj = new JSONObject(); jaStrObj.put("myMap", myCStrObj); Map<String, Integer> myCStrInt = Collections.singletonMap("myKey", Integer.valueOf(10)); JSONObject jaStrInt = new JSONObject(); jaStrInt.put("myMap", myCStrInt); Map<?, ?> myCObjObj = Collections.singletonMap((Object) "myKey", (Object) Integer.valueOf(10)); JSONObject jaObjObj = new JSONObject(); jaObjObj.put("myMap", myCObjObj); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaRaw)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaStrObj)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaStrInt)); assertTrue( "The RAW Collection should give me the same as the Typed Collection", expected.similar(jaObjObj)); } /** * JSONObjects can be built from a Map<String, Object>. * In this test the map entries are not valid JSON types. * The actual conversion is kind of interesting. */ @Test public void jsonObjectByMapWithUnsupportedValues() { Map<String, Object> jsonMap = new HashMap<String, Object>(); // Just insert some random objects jsonMap.put("key1", new CDL()); jsonMap.put("key2", new Exception()); JSONObject jsonObject = new JSONObject(jsonMap); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected 0 key1 items", ((Map<?,?>)(JsonPath.read(doc, "$.key1"))).size() == 0); assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2"))); } /** * JSONObjects can be built from a Map<String, Object>. * In this test one of the map values is null */ @Test public void jsonObjectByMapWithNullValue() { Map<String, Object> map = new HashMap<String, Object>(); map.put("trueKey", new Boolean(true)); map.put("falseKey", new Boolean(false)); map.put("stringKey", "hello world!"); map.put("nullKey", null); map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); map.put("intKey", new Long(42)); map.put("doubleKey", new Double(-23.45e67)); JSONObject jsonObject = new JSONObject(map); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6); assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); assertTrue("expected \"intKey\":42", Long.valueOf("42").equals(jsonObject.query("/intKey"))); assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); } /** * JSONObject built from a bean. In this case all but one of the * bean getters return valid JSON types */ @SuppressWarnings("boxing") @Test public void jsonObjectByBean() { /** * Default access classes have to be mocked since JSONObject, which is * not in the same package, cannot call MyBean methods by reflection. */ MyBean myBean = mock(MyBean.class); when(myBean.getDoubleKey()).thenReturn(-23.45e7); when(myBean.getIntKey()).thenReturn(42); when(myBean.getStringKey()).thenReturn("hello world!"); when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!"); when(myBean.isTrueKey()).thenReturn(true); when(myBean.isFalseKey()).thenReturn(false); when(myBean.getStringReaderKey()).thenReturn( new StringReader("") { }); JSONObject jsonObject = new JSONObject(myBean); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 8 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 8); assertTrue("expected 0 items in stringReaderKey", ((Map<?, ?>) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected hello world!","hello world!".equals(jsonObject.query("/stringKey"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); assertTrue("expected 42", Integer.valueOf("42").equals(jsonObject.query("/intKey"))); assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(jsonObject.query("/doubleKey"))); // sorry, mockito artifact assertTrue("expected 2 callbacks items", ((List<?>)(JsonPath.read(doc, "$.callbacks"))).size() == 2); assertTrue("expected 0 handler items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0); assertTrue("expected 0 callbacks[1] items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0); } /** * A bean is also an object. But in order to test the JSONObject * ctor that takes an object and a list of names, * this particular bean needs some public * data members, which have been added to the class. */ @Test public void jsonObjectByObjectAndNames() { String[] keys = {"publicString", "publicInt"}; // just need a class that has public data members MyPublicClass myPublicClass = new MyPublicClass(); JSONObject jsonObject = new JSONObject(myPublicClass, keys); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString"))); assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt"))); } /** * Exercise the JSONObject from resource bundle functionality. * The test resource bundle is uncomplicated, but provides adequate test coverage. */ @Test public void jsonObjectByResourceBundle() { JSONObject jsonObject = new JSONObject("org.json.junit.data.StringsResourceBundle", Locale.getDefault()); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected 2 greetings items", ((Map<?,?>)(JsonPath.read(doc, "$.greetings"))).size() == 2); assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(jsonObject.query("/greetings/hello"))); assertTrue("expected \"world\":\"World!\"", "World!".equals(jsonObject.query("/greetings/world"))); assertTrue("expected 2 farewells items", ((Map<?,?>)(JsonPath.read(doc, "$.farewells"))).size() == 2); assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later"))); assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator"))); } /** * Exercise the JSONObject.accumulate() method */ @SuppressWarnings("boxing") @Test public void jsonObjectAccumulate() { JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("myArray", true); jsonObject.accumulate("myArray", false); jsonObject.accumulate("myArray", "hello world!"); jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); jsonObject.accumulate("myArray", 42); jsonObject.accumulate("myArray", -23.45e7); // include an unsupported object for coverage try { jsonObject.accumulate("myArray", Double.NaN); fail("Expected exception"); } catch (JSONException ignored) {} // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 6 myArray items", ((List<?>)(JsonPath.read(doc, "$.myArray"))).size() == 6); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1"))); assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); } /** * Exercise the JSONObject append() functionality */ @SuppressWarnings("boxing") @Test public void jsonObjectAppend() { JSONObject jsonObject = new JSONObject(); jsonObject.append("myArray", true); jsonObject.append("myArray", false); jsonObject.append("myArray", "hello world!"); jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); jsonObject.append("myArray", 42); jsonObject.append("myArray", -23.45e7); // include an unsupported object for coverage try { jsonObject.append("myArray", Double.NaN); fail("Expected exception"); } catch (JSONException ignored) {} // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 6 myArray items", ((List<?>)(JsonPath.read(doc, "$.myArray"))).size() == 6); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1/"))); assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); } /** * Exercise the JSONObject doubleToString() method */ @SuppressWarnings("boxing") @Test public void jsonObjectDoubleToString() { String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" }; Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, Double.NaN, Double.NEGATIVE_INFINITY }; for (int i = 0; i < expectedStrs.length; ++i) { String actualStr = JSONObject.doubleToString(doubles[i]); assertTrue("value expected ["+expectedStrs[i]+ "] found ["+actualStr+ "]", expectedStrs[i].equals(actualStr)); } } /** * Exercise some JSONObject get[type] and opt[type] methods */ @Test public void jsonObjectValues() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"trueStrKey\":\"true\","+ "\"falseStrKey\":\"false\","+ "\"stringKey\":\"hello world!\","+ "\"intKey\":42,"+ "\"intStrKey\":\"43\","+ "\"longKey\":1234567890123456789,"+ "\"longStrKey\":\"987654321098765432\","+ "\"doubleKey\":-23.45e7,"+ "\"doubleStrKey\":\"00001.000\","+ "\"BigDecimalStrKey\":\"19007199254740993.35481234487103587486413587843213584\","+ "\"negZeroKey\":-0.0,"+ "\"negZeroStrKey\":\"-0.0\","+ "\"arrayKey\":[0,1,2],"+ "\"objectKey\":{\"myKey\":\"myVal\"}"+ "}"; JSONObject jsonObject = new JSONObject(str); assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey")); assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); assertTrue("stringKey should be string", jsonObject.getString("stringKey").equals("hello world!")); assertTrue("doubleKey should be double", jsonObject.getDouble("doubleKey") == -23.45e7); assertTrue("doubleStrKey should be double", jsonObject.getDouble("doubleStrKey") == 1); assertTrue("doubleKey can be float", jsonObject.getFloat("doubleKey") == -23.45e7f); assertTrue("doubleStrKey can be float", jsonObject.getFloat("doubleStrKey") == 1f); assertTrue("opt doubleKey should be double", jsonObject.optDouble("doubleKey") == -23.45e7); assertTrue("opt doubleKey with Default should be double", jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); assertTrue("opt negZeroKey should be double", Double.compare(jsonObject.optDouble("negZeroKey"), -0.0d) == 0); assertTrue("opt negZeroStrKey with Default should be double", Double.compare(jsonObject.optDouble("negZeroStrKey"), -0.0d) == 0); assertTrue("optNumber negZeroKey should return Double", jsonObject.optNumber("negZeroKey") instanceof Double); assertTrue("optNumber negZeroStrKey should return Double", jsonObject.optNumber("negZeroStrKey") instanceof Double); assertTrue("optNumber negZeroKey should be -0.0", Double.compare(jsonObject.optNumber("negZeroKey").doubleValue(), -0.0d) == 0); assertTrue("optNumber negZeroStrKey should be -0.0", Double.compare(jsonObject.optNumber("negZeroStrKey").doubleValue(), -0.0d) == 0); assertTrue("optFloat doubleKey should be float", jsonObject.optFloat("doubleKey") == -23.45e7f); assertTrue("optFloat doubleKey with Default should be float", jsonObject.optFloat("doubleStrKey", Float.NaN) == 1f); assertTrue("intKey should be int", jsonObject.optInt("intKey") == 42); assertTrue("opt intKey should be int", jsonObject.optInt("intKey", 0) == 42); assertTrue("opt intKey with default should be int", jsonObject.getInt("intKey") == 42); assertTrue("intStrKey should be int", jsonObject.getInt("intStrKey") == 43); assertTrue("longKey should be long", jsonObject.getLong("longKey") == 1234567890123456789L); assertTrue("opt longKey should be long", jsonObject.optLong("longKey") == 1234567890123456789L); assertTrue("opt longKey with default should be long", jsonObject.optLong("longKey", 0) == 1234567890123456789L); assertTrue("longStrKey should be long", jsonObject.getLong("longStrKey") == 987654321098765432L); assertTrue("optNumber int should return Integer", jsonObject.optNumber("intKey") instanceof Integer); assertTrue("optNumber long should return Long", jsonObject.optNumber("longKey") instanceof Long); assertTrue("optNumber double should return Double", jsonObject.optNumber("doubleKey") instanceof Double); assertTrue("optNumber Str int should return Integer", jsonObject.optNumber("intStrKey") instanceof Integer); assertTrue("optNumber Str long should return Long", jsonObject.optNumber("longStrKey") instanceof Long); assertTrue("optNumber Str double should return Double", jsonObject.optNumber("doubleStrKey") instanceof Double); assertTrue("optNumber BigDecimalStrKey should return BigDecimal", jsonObject.optNumber("BigDecimalStrKey") instanceof BigDecimal); assertTrue("xKey should not exist", jsonObject.isNull("xKey")); assertTrue("stringKey should exist", jsonObject.has("stringKey")); assertTrue("opt stringKey should string", jsonObject.optString("stringKey").equals("hello world!")); assertTrue("opt stringKey with default should string", jsonObject.optString("stringKey", "not found").equals("hello world!")); JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); assertTrue("arrayKey should be JSONArray", jsonArray.getInt(0) == 0 && jsonArray.getInt(1) == 1 && jsonArray.getInt(2) == 2); jsonArray = jsonObject.optJSONArray("arrayKey"); assertTrue("opt arrayKey should be JSONArray", jsonArray.getInt(0) == 0 && jsonArray.getInt(1) == 1 && jsonArray.getInt(2) == 2); JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); assertTrue("objectKey should be JSONObject", jsonObjectInner.get("myKey").equals("myVal")); } /** * Check whether JSONObject handles large or high precision numbers correctly */ @Test public void stringToValueNumbersTest() { assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0") instanceof Double); assertTrue("-0.0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double); assertTrue("'-' Should be a String!",JSONObject.stringToValue("-") instanceof String); assertTrue( "0.2 should be a Double!", JSONObject.stringToValue( "0.2" ) instanceof Double ); assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!", JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof Double ); /** * This test documents a need for BigDecimal conversion. */ Object obj = JSONObject.stringToValue( "299792.457999999984" ); assertTrue( "evaluates to 299792.458 double instead of 299792.457999999984 BigDecimal!", obj.equals(new Double(299792.458)) ); assertTrue( "1 should be an Integer!", JSONObject.stringToValue( "1" ) instanceof Integer ); assertTrue( "Integer.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer ); assertTrue( "Large integers should be a Long!", JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); assertTrue( "Long.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); String str = new BigInteger( new Long( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString(); assertTrue( "Really large integers currently evaluate to string", JSONObject.stringToValue(str).equals("9223372036854775808")); } /** * This test documents numeric values which could be numerically * handled as BigDecimal or BigInteger. It helps determine what outputs * will change if those types are supported. */ @Test public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { // Valid JSON Numbers, probably should return BigDecimal or BigInteger objects String str = "{"+ "\"numberWithDecimals\":299792.457999999984,"+ "\"largeNumber\":12345678901234567890,"+ "\"preciseNumber\":0.2000000000000000111,"+ "\"largeExponent\":-23.45e2327"+ "}"; JSONObject jsonObject = new JSONObject(str); // Comes back as a double, but loses precision assertTrue( "numberWithDecimals currently evaluates to double 299792.458", jsonObject.get( "numberWithDecimals" ).equals( new Double( "299792.458" ) ) ); Object obj = jsonObject.get( "largeNumber" ); assertTrue("largeNumber currently evaluates to string", "12345678901234567890".equals(obj)); // comes back as a double but loses precision assertTrue( "preciseNumber currently evaluates to double 0.2", jsonObject.get( "preciseNumber" ).equals(new Double(0.2))); obj = jsonObject.get( "largeExponent" ); assertTrue("largeExponent should currently evaluates as a string", "-23.45e2327".equals(obj)); } /** * This test documents how JSON-Java handles invalid numeric input. */ @Test public void jsonInvalidNumberValues() { // Number-notations supported by Java and invalid as JSON String str = "{"+ "\"hexNumber\":-0x123,"+ "\"tooManyZeros\":00,"+ "\"negativeInfinite\":-Infinity,"+ "\"negativeNaN\":-NaN,"+ "\"negativeFraction\":-.01,"+ "\"tooManyZerosFraction\":00.001,"+ "\"negativeHexFloat\":-0x1.fffp1,"+ "\"hexFloat\":0x1.0P-1074,"+ "\"floatIdentifier\":0.1f,"+ "\"doubleIdentifier\":0.1d"+ "}"; JSONObject jsonObject = new JSONObject(str); Object obj; obj = jsonObject.get( "hexNumber" ); assertFalse( "hexNumber must not be a number (should throw exception!?)", obj instanceof Number ); assertTrue("hexNumber currently evaluates to string", obj.equals("-0x123")); assertTrue( "tooManyZeros currently evaluates to string", jsonObject.get( "tooManyZeros" ).equals("00")); obj = jsonObject.get("negativeInfinite"); assertTrue( "negativeInfinite currently evaluates to string", obj.equals("-Infinity")); obj = jsonObject.get("negativeNaN"); assertTrue( "negativeNaN currently evaluates to string", obj.equals("-NaN")); assertTrue( "negativeFraction currently evaluates to double -0.01", jsonObject.get( "negativeFraction" ).equals(new Double(-0.01))); assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", jsonObject.get( "tooManyZerosFraction" ).equals(new Double(0.001))); assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875", jsonObject.get( "negativeHexFloat" ).equals(new Double(-3.99951171875))); assertTrue("hexFloat currently evaluates to double 4.9E-324", jsonObject.get("hexFloat").equals(new Double(4.9E-324))); assertTrue("floatIdentifier currently evaluates to double 0.1", jsonObject.get("floatIdentifier").equals(new Double(0.1))); assertTrue("doubleIdentifier currently evaluates to double 0.1", jsonObject.get("doubleIdentifier").equals(new Double(0.1))); } /** * Tests how JSONObject get[type] handles incorrect types */ @Test public void jsonObjectNonAndWrongValues() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"trueStrKey\":\"true\","+ "\"falseStrKey\":\"false\","+ "\"stringKey\":\"hello world!\","+ "\"intKey\":42,"+ "\"intStrKey\":\"43\","+ "\"longKey\":1234567890123456789,"+ "\"longStrKey\":\"987654321098765432\","+ "\"doubleKey\":-23.45e7,"+ "\"doubleStrKey\":\"00001.000\","+ "\"arrayKey\":[0,1,2],"+ "\"objectKey\":{\"myKey\":\"myVal\"}"+ "}"; JSONObject jsonObject = new JSONObject(str); try { jsonObject.getBoolean("nonKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("expecting an exception message", "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); } try { jsonObject.getBoolean("stringKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a Boolean.". equals(e.getMessage())); } try { jsonObject.getString("nonKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getString("trueKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"trueKey\"] not a string.". equals(e.getMessage())); } try { jsonObject.getDouble("nonKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getDouble("stringKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a number.". equals(e.getMessage())); } try { jsonObject.getFloat("nonKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getFloat("stringKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a number.". equals(e.getMessage())); } try { jsonObject.getInt("nonKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getInt("stringKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not an int.". equals(e.getMessage())); } try { jsonObject.getLong("nonKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getLong("stringKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a long.". equals(e.getMessage())); } try { jsonObject.getJSONArray("nonKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getJSONArray("stringKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a JSONArray.". equals(e.getMessage())); } try { jsonObject.getJSONObject("nonKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". equals(e.getMessage())); } try { jsonObject.getJSONObject("stringKey"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a JSONObject.". equals(e.getMessage())); } } /** * This test documents an unexpected numeric behavior. * A double that ends with .0 is parsed, serialized, then * parsed again. On the second parse, it has become an int. */ @Test public void unexpectedDoubleToIntConversion() { String key30 = "key30"; String key31 = "key31"; JSONObject jsonObject = new JSONObject(); jsonObject.put(key30, new Double(3.0)); jsonObject.put(key31, new Double(3.1)); assertTrue("3.0 should remain a double", jsonObject.getDouble(key30) == 3); assertTrue("3.1 should remain a double", jsonObject.getDouble(key31) == 3.1); // turns 3.0 into 3. String serializedString = jsonObject.toString(); JSONObject deserialized = new JSONObject(serializedString); assertTrue("3.0 is now an int", deserialized.get(key30) instanceof Integer); assertTrue("3.0 can still be interpreted as a double", deserialized.getDouble(key30) == 3.0); assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); } /** * Document behaviors of big numbers. Includes both JSONObject * and JSONArray tests */ @SuppressWarnings("boxing") @Test public void bigNumberOperations() { /** * JSONObject tries to parse BigInteger as a bean, but it only has * one getter, getLowestBitSet(). The value is lost and an unhelpful * value is stored. This should be fixed. */ BigInteger bigInteger = new BigInteger("123456789012345678901234567890"); JSONObject jsonObject = new JSONObject(bigInteger); Object obj = jsonObject.get("lowestSetBit"); assertTrue("JSONObject only has 1 value", jsonObject.length() == 1); assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet", obj instanceof Integer); assertTrue("this bigInteger lowestBitSet happens to be 1", obj.equals(1)); /** * JSONObject tries to parse BigDecimal as a bean, but it has * no getters, The value is lost and no value is stored. * This should be fixed. */ BigDecimal bigDecimal = new BigDecimal( "123456789012345678901234567890.12345678901234567890123456789"); jsonObject = new JSONObject(bigDecimal); assertTrue("large bigDecimal is not stored", jsonObject.length() == 0); /** * JSONObject put(String, Object) method stores and serializes * bigInt and bigDec correctly. Nothing needs to change. */ jsonObject = new JSONObject(); jsonObject.put("bigInt", bigInteger); assertTrue("jsonObject.put() handles bigInt correctly", jsonObject.get("bigInt").equals(bigInteger)); assertTrue("jsonObject.getBigInteger() handles bigInt correctly", jsonObject.getBigInteger("bigInt").equals(bigInteger)); assertTrue("jsonObject.optBigInteger() handles bigInt correctly", jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); assertTrue("jsonObject serializes bigInt correctly", jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}")); jsonObject = new JSONObject(); jsonObject.put("bigDec", bigDecimal); assertTrue("jsonObject.put() handles bigDec correctly", jsonObject.get("bigDec").equals(bigDecimal)); assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); assertTrue("jsonObject serializes bigDec correctly", jsonObject.toString().equals( "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); /** * exercise some exceptions */ try { jsonObject.getBigDecimal("bigInt"); fail("expected an exeption"); } catch (JSONException ignored) {} obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE); assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); try { jsonObject.getBigInteger("bigDec"); fail("expected an exeption"); } catch (JSONException ignored) {} jsonObject.put("stringKey", "abc"); try { jsonObject.getBigDecimal("stringKey"); fail("expected an exeption"); } catch (JSONException ignored) {} obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); assertTrue("expected BigInteger", obj instanceof BigInteger); assertEquals(bigDecimal.toBigInteger(), obj); /** * JSONObject.numberToString() works correctly, nothing to change. */ String str = JSONObject.numberToString(bigInteger); assertTrue("numberToString() handles bigInteger correctly", str.equals("123456789012345678901234567890")); str = JSONObject.numberToString(bigDecimal); assertTrue("numberToString() handles bigDecimal correctly", str.equals("123456789012345678901234567890.12345678901234567890123456789")); /** * JSONObject.stringToValue() turns bigInt into an accurate string, * and rounds bigDec. This incorrect, but users may have come to * expect this behavior. Change would be marginally better, but * might inconvenience users. */ obj = JSONObject.stringToValue(bigInteger.toString()); assertTrue("stringToValue() turns bigInteger string into string", obj instanceof String); obj = JSONObject.stringToValue(bigDecimal.toString()); assertTrue("stringToValue() changes bigDecimal string", !obj.toString().equals(bigDecimal.toString())); /** * wrap() vs put() big number behavior is now the same. */ // bigInt map ctor Map<String, Object> map = new HashMap<String, Object>(); map.put("bigInt", bigInteger); jsonObject = new JSONObject(map); String actualFromMapStr = jsonObject.toString(); assertTrue("bigInt in map (or array or bean) is a string", actualFromMapStr.equals( "{\"bigInt\":123456789012345678901234567890}")); // bigInt put jsonObject = new JSONObject(); jsonObject.put("bigInt", bigInteger); String actualFromPutStr = jsonObject.toString(); assertTrue("bigInt from put is a number", actualFromPutStr.equals( "{\"bigInt\":123456789012345678901234567890}")); // bigDec map ctor map = new HashMap<String, Object>(); map.put("bigDec", bigDecimal); jsonObject = new JSONObject(map); actualFromMapStr = jsonObject.toString(); assertTrue("bigDec in map (or array or bean) is a bigDec", actualFromMapStr.equals( "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); // bigDec put jsonObject = new JSONObject(); jsonObject.put("bigDec", bigDecimal); actualFromPutStr = jsonObject.toString(); assertTrue("bigDec from put is a number", actualFromPutStr.equals( "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); // bigInt,bigDec put JSONArray jsonArray = new JSONArray(); jsonArray.put(bigInteger); jsonArray.put(bigDecimal); actualFromPutStr = jsonArray.toString(); assertTrue("bigInt, bigDec from put is a number", actualFromPutStr.equals( "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger)); assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal)); assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); jsonArray.put(Boolean.TRUE); try { jsonArray.getBigInteger(2); fail("should not be able to get big int"); } catch (Exception ignored) {} try { jsonArray.getBigDecimal(2); fail("should not be able to get big dec"); } catch (Exception ignored) {} assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE)); assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE)); // bigInt,bigDec list ctor List<Object> list = new ArrayList<Object>(); list.add(bigInteger); list.add(bigDecimal); jsonArray = new JSONArray(list); String actualFromListStr = jsonArray.toString(); assertTrue("bigInt, bigDec in list is a bigInt, bigDec", actualFromListStr.equals( "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); // bigInt bean ctor MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890")); jsonObject = new JSONObject(myBigNumberBean); String actualFromBeanStr = jsonObject.toString(); // can't do a full string compare because mockery adds an extra key/value assertTrue("bigInt from bean ctor is a bigInt", actualFromBeanStr.contains("123456789012345678901234567890")); // bigDec bean ctor myBigNumberBean = mock(MyBigNumberBean.class); when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789")); jsonObject = new JSONObject(myBigNumberBean); actualFromBeanStr = jsonObject.toString(); // can't do a full string compare because mockery adds an extra key/value assertTrue("bigDec from bean ctor is a bigDec", actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789")); // bigInt,bigDec wrap() obj = JSONObject.wrap(bigInteger); assertTrue("wrap() returns big num",obj.equals(bigInteger)); obj = JSONObject.wrap(bigDecimal); assertTrue("wrap() returns string",obj.equals(bigDecimal)); } /** * The purpose for the static method getNames() methods are not clear. * This method is not called from within JSON-Java. Most likely * uses are to prep names arrays for: * JSONObject(JSONObject jo, String[] names) * JSONObject(Object object, String names[]), */ @Test public void jsonObjectNames() { JSONObject jsonObject; // getNames() from null JSONObject assertTrue("null names from null Object", null == JSONObject.getNames((Object)null)); // getNames() from object with no fields assertTrue("null names from Object with no fields", null == JSONObject.getNames(new MyJsonString())); // getNames from new JSONOjbect jsonObject = new JSONObject(); String [] names = JSONObject.getNames(jsonObject); assertTrue("names should be null", names == null); // getNames() from empty JSONObject String emptyStr = "{}"; jsonObject = new JSONObject(emptyStr); assertTrue("empty JSONObject should have null names", null == JSONObject.getNames(jsonObject)); // getNames() from JSONObject String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"stringKey\":\"hello world!\","+ "}"; jsonObject = new JSONObject(str); names = JSONObject.getNames(jsonObject); JSONArray jsonArray = new JSONArray(names); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonArray.toString()); List<?> docList = JsonPath.read(doc, "$"); assertTrue("expected 3 items", docList.size() == 3); assertTrue( "expected to find trueKey", ((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); assertTrue( "expected to find falseKey", ((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); assertTrue( "expected to find stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); /** * getNames() from an enum with properties has an interesting result. * It returns the enum values, not the selected enum properties */ MyEnumField myEnumField = MyEnumField.VAL1; names = JSONObject.getNames(myEnumField); // validate JSON jsonArray = new JSONArray(names); doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonArray.toString()); docList = JsonPath.read(doc, "$"); assertTrue("expected 3 items", docList.size() == 3); assertTrue( "expected to find VAL1", ((List<?>) JsonPath.read(doc, "$[?(@=='VAL1')]")).size() == 1); assertTrue( "expected to find VAL2", ((List<?>) JsonPath.read(doc, "$[?(@=='VAL2')]")).size() == 1); assertTrue( "expected to find VAL3", ((List<?>) JsonPath.read(doc, "$[?(@=='VAL3')]")).size() == 1); /** * A bean is also an object. But in order to test the static * method getNames(), this particular bean needs some public * data members. */ MyPublicClass myPublicClass = new MyPublicClass(); names = JSONObject.getNames(myPublicClass); // validate JSON jsonArray = new JSONArray(names); doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonArray.toString()); docList = JsonPath.read(doc, "$"); assertTrue("expected 2 items", docList.size() == 2); assertTrue( "expected to find publicString", ((List<?>) JsonPath.read(doc, "$[?(@=='publicString')]")).size() == 1); assertTrue( "expected to find publicInt", ((List<?>) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1); } /** * Populate a JSONArray from an empty JSONObject names() method. * It should be empty. */ @Test public void emptyJsonObjectNamesToJsonAray() { JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = jsonObject.names(); assertTrue("jsonArray should be null", jsonArray == null); } /** * Populate a JSONArray from a JSONObject names() method. * Confirm that it contains the expected names. */ @Test public void jsonObjectNamesToJsonAray() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"stringKey\":\"hello world!\","+ "}"; JSONObject jsonObject = new JSONObject(str); JSONArray jsonArray = jsonObject.names(); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected to find trueKey", ((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); assertTrue("expected to find falseKey", ((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); assertTrue("expected to find stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); } /** * Exercise the JSONObject increment() method. */ @SuppressWarnings("cast") @Test public void jsonObjectIncrement() { String str = "{"+ "\"keyLong\":9999999991,"+ "\"keyDouble\":1.1"+ "}"; JSONObject jsonObject = new JSONObject(str); jsonObject.increment("keyInt"); jsonObject.increment("keyInt"); jsonObject.increment("keyLong"); jsonObject.increment("keyDouble"); jsonObject.increment("keyInt"); jsonObject.increment("keyLong"); jsonObject.increment("keyDouble"); /** * JSONObject constructor won't handle these types correctly, but * adding them via put works. */ jsonObject.put("keyFloat", 1.1f); jsonObject.put("keyBigInt", new BigInteger("123456789123456789123456789123456780")); jsonObject.put("keyBigDec", new BigDecimal("123456789123456789123456789123456780.1")); jsonObject.increment("keyFloat"); jsonObject.increment("keyFloat"); jsonObject.increment("keyBigInt"); jsonObject.increment("keyBigDec"); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6); assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/keyInt"))); assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(jsonObject.query("/keyLong"))); assertTrue("expected 3.1", Double.valueOf(3.1).equals(jsonObject.query("/keyDouble"))); assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(jsonObject.query("/keyBigInt"))); assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(jsonObject.query("/keyBigDec"))); assertEquals(Float.valueOf(3.1f), jsonObject.query("/keyFloat")); /** * float f = 3.1f; double df = (double) f; double d = 3.1d; * System.out.println * (Integer.toBinaryString(Float.floatToRawIntBits(f))); * System.out.println * (Long.toBinaryString(Double.doubleToRawLongBits(df))); * System.out.println * (Long.toBinaryString(Double.doubleToRawLongBits(d))); * * - Float: * seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm * 1000000010001100110011001100110 * - Double * seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * 10000000 10001100110011001100110 * 100000000001000110011001100110011000000000000000000000000000000 * 100000000001000110011001100110011001100110011001100110011001101 */ /** * Examples of well documented but probably unexpected behavior in * java / with 32-bit float to 64-bit float conversion. */ assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d ); assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d ); Double d1 = new Double( 1.1f ); Double d2 = new Double( "1.1f" ); assertFalse( "Document implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) ); assertTrue( "Correctly converting float to double via base10 (string) representation!", new Double( 3.1d ).equals( new Double( new Float( 3.1f ).toString() ) ) ); // Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject JSONObject jo = new JSONObject(); jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) ); JSONObject inc = new JSONObject(); inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float ); inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double! // this.put(key, (Float) value + 1); // 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done. // 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects! // 3. A float+float operation will be performed and results into a float primitive. // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Float ); // correct implementation (with change of behavior) would be: // this.put(key, new Float((Float) value + 1)); // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not // really in the the scope of a JSON-library (IMHO.) } /** * Exercise JSONObject numberToString() method */ @SuppressWarnings("boxing") @Test public void jsonObjectNumberToString() { String str; Double dVal; Integer iVal = 1; str = JSONObject.numberToString(iVal); assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str)); dVal = 12.34; str = JSONObject.numberToString(dVal); assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); dVal = 12.34e27; str = JSONObject.numberToString(dVal); assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); // trailing .0 is truncated, so it doesn't quite match toString() dVal = 5000000.0000000; str = JSONObject.numberToString(dVal); assertTrue("expected 5000000 actual "+str, str.equals("5000000")); } /** * Exercise JSONObject put() and similar() methods */ @SuppressWarnings("boxing") @Test public void jsonObjectPut() { String expectedStr = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"arrayKey\":[0,1,2],"+ "\"objectKey\":{"+ "\"myKey1\":\"myVal1\","+ "\"myKey2\":\"myVal2\","+ "\"myKey3\":\"myVal3\","+ "\"myKey4\":\"myVal4\""+ "}"+ "}"; JSONObject jsonObject = new JSONObject(); jsonObject.put("trueKey", true); jsonObject.put("falseKey", false); Integer [] intArray = { 0, 1, 2 }; jsonObject.put("arrayKey", Arrays.asList(intArray)); Map<String, Object> myMap = new HashMap<String, Object>(); myMap.put("myKey1", "myVal1"); myMap.put("myKey2", "myVal2"); myMap.put("myKey3", "myVal3"); myMap.put("myKey4", "myVal4"); jsonObject.put("objectKey", myMap); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected 3 arrayKey items", ((List<?>)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); assertTrue("expected 4 objectKey items", ((Map<?,?>)(JsonPath.read(doc, "$.objectKey"))).size() == 4); assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); jsonObject.remove("trueKey"); JSONObject expectedJsonObject = new JSONObject(expectedStr); assertTrue("unequal jsonObjects should not be similar", !jsonObject.similar(expectedJsonObject)); assertTrue("jsonObject should not be similar to jsonArray", !jsonObject.similar(new JSONArray())); String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr); JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr); assertTrue("different values should not be similar", !aCompareValueJsonObject.similar(bCompareValueJsonObject)); String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr); JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr); assertTrue("different nested JSONObjects should not be similar", !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr); JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); assertTrue("different nested JSONArrays should not be similar", !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); } /** * Exercise JSONObject toString() method */ @Test public void jsonObjectToString() { String str = "{"+ "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"arrayKey\":[0,1,2],"+ "\"objectKey\":{"+ "\"myKey1\":\"myVal1\","+ "\"myKey2\":\"myVal2\","+ "\"myKey3\":\"myVal3\","+ "\"myKey4\":\"myVal4\""+ "}"+ "}"; JSONObject jsonObject = new JSONObject(str); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected 3 arrayKey items", ((List<?>)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); assertTrue("expected 4 objectKey items", ((Map<?,?>)(JsonPath.read(doc, "$.objectKey"))).size() == 4); assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); } /** * Exercise JSONObject toString() method with various indent levels. */ @Test public void jsonObjectToStringIndent() { String jsonObject0Str = "{"+ "\"key1\":" + "[1,2," + "{\"key3\":true}" + "],"+ "\"key2\":" + "{\"key1\":\"val1\",\"key2\":" + "{\"key2\":\"val2\"}" + "},"+ "\"key3\":" + "[" + "[1,2.1]" + "," + "[null]" + "]"+ "}"; String jsonObject1Str = "{\n" + " \"key1\": [\n" + " 1,\n" + " 2,\n" + " {\"key3\": true}\n" + " ],\n" + " \"key2\": {\n" + " \"key1\": \"val1\",\n" + " \"key2\": {\"key2\": \"val2\"}\n" + " },\n" + " \"key3\": [\n" + " [\n" + " 1,\n" + " 2.1\n" + " ],\n" + " [null]\n" + " ]\n" + "}"; String jsonObject4Str = "{\n" + " \"key1\": [\n" + " 1,\n" + " 2,\n" + " {\"key3\": true}\n" + " ],\n" + " \"key2\": {\n" + " \"key1\": \"val1\",\n" + " \"key2\": {\"key2\": \"val2\"}\n" + " },\n" + " \"key3\": [\n" + " [\n" + " 1,\n" + " 2.1\n" + " ],\n" + " [null]\n" + " ]\n" + "}"; JSONObject jsonObject = new JSONObject(jsonObject0Str); assertEquals("toString()",jsonObject0Str, jsonObject.toString()); assertEquals("toString(0)",jsonObject0Str, jsonObject.toString(0)); assertEquals("toString(1)",jsonObject1Str, jsonObject.toString(1)); assertEquals("toString(4)",jsonObject4Str, jsonObject.toString(4)); JSONObject jo = new JSONObject().put("TABLE", new JSONObject().put("yhoo", new JSONObject())); assertEquals("toString(2)","{\"TABLE\": {\"yhoo\": {}}}", jo.toString(2)); } /** * Explores how JSONObject handles maps. Insert a string/string map * as a value in a JSONObject. It will remain a map. Convert the * JSONObject to string, then create a new JSONObject from the string. * In the new JSONObject, the value will be stored as a nested JSONObject. * Confirm that map and nested JSONObject have the same contents. */ @Test public void jsonObjectToStringSuppressWarningOnCastToMap() { JSONObject jsonObject = new JSONObject(); Map<String, String> map = new HashMap<>(); map.put("abc", "def"); jsonObject.put("key", map); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 1 key item", ((Map<?,?>)(JsonPath.read(doc, "$.key"))).size() == 1); assertTrue("expected def", "def".equals(jsonObject.query("/key/abc"))); } /** * Explores how JSONObject handles collections. Insert a string collection * as a value in a JSONObject. It will remain a collection. Convert the * JSONObject to string, then create a new JSONObject from the string. * In the new JSONObject, the value will be stored as a nested JSONArray. * Confirm that collection and nested JSONArray have the same contents. */ @Test public void jsonObjectToStringSuppressWarningOnCastToCollection() { JSONObject jsonObject = new JSONObject(); Collection<String> collection = new ArrayList<String>(); collection.add("abc"); // ArrayList will be added as an object jsonObject.put("key", collection); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 1 key item", ((List<?>)(JsonPath.read(doc, "$.key"))).size() == 1); assertTrue("expected abc", "abc".equals(jsonObject.query("/key/0"))); } /** * Exercises the JSONObject.valueToString() method for various types */ @Test public void valueToString() { assertTrue("null valueToString() incorrect", "null".equals(JSONObject.valueToString(null))); MyJsonString jsonString = new MyJsonString(); assertTrue("jsonstring valueToString() incorrect", "my string".equals(JSONObject.valueToString(jsonString))); assertTrue("boolean valueToString() incorrect", "true".equals(JSONObject.valueToString(Boolean.TRUE))); assertTrue("non-numeric double", "null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY))); String jsonObjectStr = "{"+ "\"key1\":\"val1\","+ "\"key2\":\"val2\","+ "\"key3\":\"val3\""+ "}"; JSONObject jsonObject = new JSONObject(jsonObjectStr); assertTrue("jsonObject valueToString() incorrect", JSONObject.valueToString(jsonObject).equals(jsonObject.toString())); String jsonArrayStr = "[1,2,3]"; JSONArray jsonArray = new JSONArray(jsonArrayStr); assertTrue("jsonArray valueToString() incorrect", JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); Map<String, String> map = new HashMap<String, String>(); map.put("key1", "val1"); map.put("key2", "val2"); map.put("key3", "val3"); assertTrue("map valueToString() incorrect", jsonObject.toString().equals(JSONObject.valueToString(map))); Collection<Integer> collection = new ArrayList<Integer>(); collection.add(new Integer(1)); collection.add(new Integer(2)); collection.add(new Integer(3)); assertTrue("collection valueToString() expected: "+ jsonArray.toString()+ " actual: "+ JSONObject.valueToString(collection), jsonArray.toString().equals(JSONObject.valueToString(collection))); Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; assertTrue("array valueToString() incorrect", jsonArray.toString().equals(JSONObject.valueToString(array))); } @SuppressWarnings("boxing") @Test public void valueToStringConfirmException() { Map<Integer, String> myMap = new HashMap<Integer, String>(); myMap.put(1, "myValue"); // this is the test, it should not throw an exception String str = JSONObject.valueToString(myMap); // confirm result, just in case Object doc = Configuration.defaultConfiguration().jsonProvider().parse(str); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected myValue", "myValue".equals(JsonPath.read(doc, "$.1"))); } /** * Exercise the JSONObject wrap() method. Sometimes wrap() will change * the object being wrapped, other times not. The purpose of wrap() is * to ensure the value is packaged in a way that is compatible with how * a JSONObject value or JSONArray value is supposed to be stored. */ @Test public void wrapObject() { // wrap(null) returns NULL assertTrue("null wrap() incorrect", JSONObject.NULL == JSONObject.wrap(null)); // wrap(Integer) returns Integer Integer in = new Integer(1); assertTrue("Integer wrap() incorrect", in == JSONObject.wrap(in)); /** * This test is to document the preferred behavior if BigDecimal is * supported. Previously bd returned as a string, since it * is recognized as being a Java package class. Now with explicit * support for big numbers, it remains a BigDecimal */ Object bdWrap = JSONObject.wrap(BigDecimal.ONE); assertTrue("BigDecimal.ONE evaluates to ONE", bdWrap.equals(BigDecimal.ONE)); // wrap JSONObject returns JSONObject String jsonObjectStr = "{"+ "\"key1\":\"val1\","+ "\"key2\":\"val2\","+ "\"key3\":\"val3\""+ "}"; JSONObject jsonObject = new JSONObject(jsonObjectStr); assertTrue("JSONObject wrap() incorrect", jsonObject == JSONObject.wrap(jsonObject)); // wrap collection returns JSONArray Collection<Integer> collection = new ArrayList<Integer>(); collection.add(new Integer(1)); collection.add(new Integer(2)); collection.add(new Integer(3)); JSONArray jsonArray = (JSONArray) (JSONObject.wrap(collection)); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); // wrap Array returns JSONArray Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(integerArrayJsonArray.toString()); assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); // wrap map returns JSONObject Map<String, String> map = new HashMap<String, String>(); map.put("key1", "val1"); map.put("key2", "val2"); map.put("key3", "val3"); JSONObject mapJsonObject = (JSONObject) (JSONObject.wrap(map)); // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(mapJsonObject.toString()); assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected val1", "val1".equals(mapJsonObject.query("/key1"))); assertTrue("expected val2", "val2".equals(mapJsonObject.query("/key2"))); assertTrue("expected val3", "val3".equals(mapJsonObject.query("/key3"))); } /** * RFC 7159 defines control characters to be U+0000 through U+001F. This test verifies that the parser is checking for these in expected ways. */ @Test public void jsonObjectParseControlCharacters(){ for(int i = 0;i<=0x001f;i++){ final String charString = String.valueOf((char)i); final String source = "{\"key\":\""+charString+"\"}"; try { JSONObject jo = new JSONObject(source); assertTrue("Expected "+charString+"("+i+") in the JSON Object but did not find it.",charString.equals(jo.getString("key"))); } catch (JSONException ex) { assertTrue("Only \\0 (U+0000), \\n (U+000A), and \\r (U+000D) should cause an error. Instead "+charString+"("+i+") caused an error", i=='\0' || i=='\n' || i=='\r' ); } } } /** * Explore how JSONObject handles parsing errors. */ @SuppressWarnings("boxing") @Test public void jsonObjectParsingErrors() { try { // does not start with '{' String str = "abc"; assertNull("Expected an exception",new JSONObject(str)); } catch (JSONException e) { assertEquals("Expecting an exception message", "A JSONObject text must begin with '{' at 1 [character 2 line 1]", e.getMessage()); } try { // does not end with '}' String str = "{"; assertNull("Expected an exception",new JSONObject(str)); } catch (JSONException e) { assertEquals("Expecting an exception message", "A JSONObject text must end with '}' at 1 [character 2 line 1]", e.getMessage()); } try { // key with no ':' String str = "{\"myKey\" = true}"; assertNull("Expected an exception",new JSONObject(str)); } catch (JSONException e) { assertEquals("Expecting an exception message", "Expected a ':' after a key at 10 [character 11 line 1]", e.getMessage()); } try { // entries with no ',' separator String str = "{\"myKey\":true \"myOtherKey\":false}"; assertNull("Expected an exception",new JSONObject(str)); } catch (JSONException e) { assertEquals("Expecting an exception message", "Expected a ',' or '}' at 15 [character 16 line 1]", e.getMessage()); } try { // append to wrong key String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.append("myKey", "hello"); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", "JSONObject[myKey] is not a JSONArray.", e.getMessage()); } try { // increment wrong key String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.increment("myKey"); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", "Unable to increment [\"myKey\"].", e.getMessage()); } try { // invalid key String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.get(null); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", "Null key.", e.getMessage()); } try { // invalid numberToString() JSONObject.numberToString((Number)null); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", "Null pointer", e.getMessage()); } try { // null put key JSONObject jsonObject = new JSONObject("{}"); jsonObject.put(null, 0); fail("Expected an exception"); } catch (NullPointerException ignored) { } try { // multiple putOnce key JSONObject jsonObject = new JSONObject("{}"); jsonObject.putOnce("hello", "world"); jsonObject.putOnce("hello", "world!"); fail("Expected an exception"); } catch (JSONException e) { assertTrue("", true); } try { // test validity of invalid double JSONObject.testValidity(Double.NaN); fail("Expected an exception"); } catch (JSONException e) { assertTrue("", true); } try { // test validity of invalid float JSONObject.testValidity(Float.NEGATIVE_INFINITY); fail("Expected an exception"); } catch (JSONException e) { assertTrue("", true); } try { // test exception message when including a duplicate key (level 0) String str = "{\n" +" \"attr01\":\"value-01\",\n" +" \"attr02\":\"value-02\",\n" +" \"attr03\":\"value-03\",\n" +" \"attr03\":\"value-04\"\n" + "}"; new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", "Duplicate key \"attr03\" at 90 [character 13 line 5]", e.getMessage()); } try { // test exception message when including a duplicate key (level 0) holding an object String str = "{\n" +" \"attr01\":\"value-01\",\n" +" \"attr02\":\"value-02\",\n" +" \"attr03\":\"value-03\",\n" +" \"attr03\": {" +" \"attr04-01\":\"value-04-01\",n" +" \"attr04-02\":\"value-04-02\",n" +" \"attr04-03\":\"value-04-03\"n" + " }\n" + "}"; new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", "Duplicate key \"attr03\" at 90 [character 13 line 5]", e.getMessage()); } try { // test exception message when including a duplicate key (level 0) holding an array String str = "{\n" +" \"attr01\":\"value-01\",\n" +" \"attr02\":\"value-02\",\n" +" \"attr03\":\"value-03\",\n" +" \"attr03\": [\n" +" {" +" \"attr04-01\":\"value-04-01\",n" +" \"attr04-02\":\"value-04-02\",n" +" \"attr04-03\":\"value-04-03\"n" +" }\n" + " ]\n" + "}"; new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", "Duplicate key \"attr03\" at 90 [character 13 line 5]", e.getMessage()); } try { // test exception message when including a duplicate key (level 1) String str = "{\n" +" \"attr01\":\"value-01\",\n" +" \"attr02\":\"value-02\",\n" +" \"attr03\":\"value-03\",\n" +" \"attr04\": {\n" +" \"attr04-01\":\"value04-01\",\n" +" \"attr04-02\":\"value04-02\",\n" +" \"attr04-03\":\"value04-03\",\n" +" \"attr04-03\":\"value04-04\"\n" + " }\n" + "}"; new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", e.getMessage()); } try { // test exception message when including a duplicate key (level 1) holding an object String str = "{\n" +" \"attr01\":\"value-01\",\n" +" \"attr02\":\"value-02\",\n" +" \"attr03\":\"value-03\",\n" +" \"attr04\": {\n" +" \"attr04-01\":\"value04-01\",\n" +" \"attr04-02\":\"value04-02\",\n" +" \"attr04-03\":\"value04-03\",\n" +" \"attr04-03\": {\n" +" \"attr04-04-01\":\"value04-04-01\",\n" +" \"attr04-04-02\":\"value04-04-02\",\n" +" \"attr04-04-03\":\"value04-04-03\",\n" +" }\n" +" }\n" + "}"; new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", e.getMessage()); } try { // test exception message when including a duplicate key (level 1) holding an array String str = "{\n" +" \"attr01\":\"value-01\",\n" +" \"attr02\":\"value-02\",\n" +" \"attr03\":\"value-03\",\n" +" \"attr04\": {\n" +" \"attr04-01\":\"value04-01\",\n" +" \"attr04-02\":\"value04-02\",\n" +" \"attr04-03\":\"value04-03\",\n" +" \"attr04-03\": [\n" +" {\n" +" \"attr04-04-01\":\"value04-04-01\",\n" +" \"attr04-04-02\":\"value04-04-02\",\n" +" \"attr04-04-03\":\"value04-04-03\",\n" +" }\n" +" ]\n" +" }\n" + "}"; new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", e.getMessage()); } try { // test exception message when including a duplicate key in object (level 0) within an array String str = "[\n" +" {\n" +" \"attr01\":\"value-01\",\n" +" \"attr02\":\"value-02\"\n" +" },\n" +" {\n" +" \"attr01\":\"value-01\",\n" +" \"attr01\":\"value-02\"\n" +" }\n" + "]"; new JSONArray(str); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", "Duplicate key \"attr01\" at 124 [character 17 line 8]", e.getMessage()); } try { // test exception message when including a duplicate key in object (level 1) within an array String str = "[\n" +" {\n" +" \"attr01\":\"value-01\",\n" +" \"attr02\": {\n" +" \"attr02-01\":\"value-02-01\",\n" +" \"attr02-02\":\"value-02-02\"\n" +" }\n" +" },\n" +" {\n" +" \"attr01\":\"value-01\",\n" +" \"attr02\": {\n" +" \"attr02-01\":\"value-02-01\",\n" +" \"attr02-01\":\"value-02-02\"\n" +" }\n" +" }\n" + "]"; new JSONArray(str); fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", "Duplicate key \"attr02-01\" at 269 [character 24 line 13]", e.getMessage()); } } /** * Confirm behavior when putOnce() is called with null parameters */ @Test public void jsonObjectPutOnceNull() { JSONObject jsonObject = new JSONObject(); jsonObject.putOnce(null, null); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** * Exercise JSONObject opt(key, default) method. */ @Test public void jsonObjectOptDefault() { String str = "{\"myKey\": \"myval\", \"hiKey\": null}"; JSONObject jsonObject = new JSONObject(str); assertTrue("optBigDecimal() should return default BigDecimal", BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); assertTrue("optBigInteger() should return default BigInteger", BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); assertTrue("optBoolean() should return default boolean", jsonObject.optBoolean("myKey", true)); assertTrue("optInt() should return default int", 42 == jsonObject.optInt("myKey", 42)); assertTrue("optEnum() should return default Enum", MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); assertTrue("optJSONArray() should return null ", null==jsonObject.optJSONArray("myKey")); assertTrue("optJSONObject() should return null ", null==jsonObject.optJSONObject("myKey")); assertTrue("optLong() should return default long", 42l == jsonObject.optLong("myKey", 42l)); assertTrue("optDouble() should return default double", 42.3d == jsonObject.optDouble("myKey", 42.3d)); assertTrue("optFloat() should return default float", 42.3f == jsonObject.optFloat("myKey", 42.3f)); assertTrue("optNumber() should return default Number", 42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue()); assertTrue("optString() should return default string", "hi".equals(jsonObject.optString("hiKey", "hi"))); } /** * Exercise JSONObject opt(key, default) method when the key doesn't exist. */ @Test public void jsonObjectOptNoKey() { JSONObject jsonObject = new JSONObject(); assertNull(jsonObject.opt(null)); assertTrue("optBigDecimal() should return default BigDecimal", BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); assertTrue("optBigInteger() should return default BigInteger", BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); assertTrue("optBoolean() should return default boolean", jsonObject.optBoolean("myKey", true)); assertTrue("optInt() should return default int", 42 == jsonObject.optInt("myKey", 42)); assertTrue("optEnum() should return default Enum", MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); assertTrue("optJSONArray() should return null ", null==jsonObject.optJSONArray("myKey")); assertTrue("optJSONObject() should return null ", null==jsonObject.optJSONObject("myKey")); assertTrue("optLong() should return default long", 42l == jsonObject.optLong("myKey", 42l)); assertTrue("optDouble() should return default double", 42.3d == jsonObject.optDouble("myKey", 42.3d)); assertTrue("optFloat() should return default float", 42.3f == jsonObject.optFloat("myKey", 42.3f)); assertTrue("optNumber() should return default Number", 42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue()); assertTrue("optString() should return default string", "hi".equals(jsonObject.optString("hiKey", "hi"))); } /** * Verifies that the opt methods properly convert string values. */ @Test public void jsonObjectOptStringConversion() { JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\"}"); assertTrue("unexpected optBoolean value",jo.optBoolean("true",false)==true); assertTrue("unexpected optBoolean value",jo.optBoolean("false",true)==false); assertTrue("unexpected optInt value",jo.optInt("int",0)==123); assertTrue("unexpected optLong value",jo.optLong("int",0)==123l); assertTrue("unexpected optDouble value",jo.optDouble("int",0.0d)==123.0d); assertTrue("unexpected optFloat value",jo.optFloat("int",0.0f)==123.0f); assertTrue("unexpected optBigInteger value",jo.optBigInteger("int",BigInteger.ZERO).compareTo(new BigInteger("123"))==0); assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); assertTrue("unexpected optNumber value",jo.optNumber("int",BigInteger.ZERO).longValue()==123l); } /** * Verifies that the opt methods properly convert string values to numbers and coerce them consistently. */ @Test public void jsonObjectOptCoercion() { JSONObject jo = new JSONObject("{\"largeNumberStr\":\"19007199254740993.35481234487103587486413587843213584\"}"); // currently the parser doesn't recognize BigDecimal, to we have to put it manually jo.put("largeNumber", new BigDecimal("19007199254740993.35481234487103587486413587843213584")); // Test type coercion from larger to smaller assertEquals(new BigDecimal("19007199254740993.35481234487103587486413587843213584"), jo.optBigDecimal("largeNumber",null)); assertEquals(new BigInteger("19007199254740993"), jo.optBigInteger("largeNumber",null)); assertEquals(1.9007199254740992E16, jo.optDouble("largeNumber"),0.0); assertEquals(1.90071995E16f, jo.optFloat("largeNumber"),0.0f); assertEquals(19007199254740993l, jo.optLong("largeNumber")); assertEquals(1874919425, jo.optInt("largeNumber")); // conversion from a string assertEquals(new BigDecimal("19007199254740993.35481234487103587486413587843213584"), jo.optBigDecimal("largeNumberStr",null)); assertEquals(new BigInteger("19007199254740993"), jo.optBigInteger("largeNumberStr",null)); assertEquals(1.9007199254740992E16, jo.optDouble("largeNumberStr"),0.0); assertEquals(1.90071995E16f, jo.optFloat("largeNumberStr"),0.0f); assertEquals(19007199254740993l, jo.optLong("largeNumberStr")); assertEquals(1874919425, jo.optInt("largeNumberStr")); // the integer portion of the actual value is larger than a double can hold. assertNotEquals((long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optLong("largeNumber")); assertNotEquals((int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optInt("largeNumber")); assertNotEquals((long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optLong("largeNumberStr")); assertNotEquals((int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optInt("largeNumberStr")); assertEquals(19007199254740992l, (long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); assertEquals(2147483647, (int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); } /** * Verifies that the optBigDecimal method properly converts values to BigDecimal and coerce them consistently. */ @Test public void jsonObjectOptBigDecimal() { JSONObject jo = new JSONObject().put("int", 123).put("long", 654L) .put("float", 1.234f).put("double", 2.345d) .put("bigInteger", new BigInteger("1234")) .put("bigDecimal", new BigDecimal("1234.56789")) .put("nullVal", JSONObject.NULL); assertEquals(new BigDecimal("123"),jo.optBigDecimal("int", null)); assertEquals(new BigDecimal("654"),jo.optBigDecimal("long", null)); assertEquals(new BigDecimal(1.234f),jo.optBigDecimal("float", null)); assertEquals(new BigDecimal(2.345d),jo.optBigDecimal("double", null)); assertEquals(new BigDecimal("1234"),jo.optBigDecimal("bigInteger", null)); assertEquals(new BigDecimal("1234.56789"),jo.optBigDecimal("bigDecimal", null)); assertNull(jo.optBigDecimal("nullVal", null)); } /** * Verifies that the optBigDecimal method properly converts values to BigDecimal and coerce them consistently. */ @Test public void jsonObjectOptBigInteger() { JSONObject jo = new JSONObject().put("int", 123).put("long", 654L) .put("float", 1.234f).put("double", 2.345d) .put("bigInteger", new BigInteger("1234")) .put("bigDecimal", new BigDecimal("1234.56789")) .put("nullVal", JSONObject.NULL); assertEquals(new BigInteger("123"),jo.optBigInteger("int", null)); assertEquals(new BigInteger("654"),jo.optBigInteger("long", null)); assertEquals(new BigInteger("1"),jo.optBigInteger("float", null)); assertEquals(new BigInteger("2"),jo.optBigInteger("double", null)); assertEquals(new BigInteger("1234"),jo.optBigInteger("bigInteger", null)); assertEquals(new BigInteger("1234"),jo.optBigInteger("bigDecimal", null)); assertNull(jo.optBigDecimal("nullVal", null)); } /** * Confirm behavior when JSONObject put(key, null object) is called */ @Test public void jsonObjectputNull() { // put null should remove the item. String str = "{\"myKey\": \"myval\"}"; JSONObject jsonObjectRemove = new JSONObject(str); jsonObjectRemove.remove("myKey"); assertEquals("jsonObject should be empty",0 ,jsonObjectRemove.length()); JSONObject jsonObjectPutNull = new JSONObject(str); jsonObjectPutNull.put("myKey", (Object) null); assertEquals("jsonObject should be empty",0 ,jsonObjectPutNull.length()); } /** * Exercise JSONObject quote() method * This purpose of quote() is to ensure that for strings with embedded * quotes, the quotes are properly escaped. */ @Test public void jsonObjectQuote() { String str; str = ""; String quotedStr; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped quotes, found "+quotedStr, "\"\"".equals(quotedStr)); str = "\"\""; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped quotes, found "+quotedStr, "\"\\\"\\\"\"".equals(quotedStr)); str = "</"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped frontslash, found "+quotedStr, "\"<\\/\"".equals(quotedStr)); str = "AB\bC"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped backspace, found "+quotedStr, "\"AB\\bC\"".equals(quotedStr)); str = "ABC\n"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped newline, found "+quotedStr, "\"ABC\\n\"".equals(quotedStr)); str = "AB\fC"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped formfeed, found "+quotedStr, "\"AB\\fC\"".equals(quotedStr)); str = "\r"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped return, found "+quotedStr, "\"\\r\"".equals(quotedStr)); str = "\u1234\u0088"; quotedStr = JSONObject.quote(str); assertTrue("quote() expected escaped unicode, found "+quotedStr, "\"\u1234\\u0088\"".equals(quotedStr)); } /** * Confirm behavior when JSONObject stringToValue() is called for an * empty string */ @Test public void stringToValue() { String str = ""; String valueStr = (String)(JSONObject.stringToValue(str)); assertTrue("stringToValue() expected empty String, found "+valueStr, "".equals(valueStr)); } /** * Confirm behavior when toJSONArray is called with a null value */ @Test public void toJSONArray() { assertTrue("toJSONArray() with null names should be null", null == new JSONObject().toJSONArray(null)); } /** * Exercise the JSONObject write() method */ @Test public void write() throws IOException { String str = "{\"key1\":\"value1\",\"key2\":[1,2,3]}"; String expectedStr = str; JSONObject jsonObject = new JSONObject(str); StringWriter stringWriter = new StringWriter(); try { String actualStr = jsonObject.write(stringWriter).toString(); assertTrue("write() expected " +expectedStr+ " but found " +actualStr, expectedStr.equals(actualStr)); } finally { stringWriter.close(); } } /** * Confirms that exceptions thrown when writing values are wrapped properly. */ @Test public void testJSONWriterException() throws IOException { final JSONObject jsonObject = new JSONObject(); jsonObject.put("someKey",new BrokenToString()); // test single element JSONObject try(StringWriter writer = new StringWriter();) { jsonObject.write(writer).toString(); fail("Expected an exception, got a String value"); } catch (JSONException e) { assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage()); } catch(Exception e) { fail("Expected JSONException"); } //test multiElement jsonObject.put("somethingElse", "a value"); try (StringWriter writer = new StringWriter()) { jsonObject.write(writer).toString(); fail("Expected an exception, got a String value"); } catch (JSONException e) { assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage()); } catch(Exception e) { fail("Expected JSONException"); } // test a more complex object try (StringWriter writer = new StringWriter()) { new JSONObject() .put("somethingElse", "a value") .put("someKey", new JSONArray() .put(new JSONObject().put("key1", new BrokenToString()))) .write(writer).toString(); fail("Expected an exception, got a String value"); } catch (JSONException e) { assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage()); } catch(Exception e) { fail("Expected JSONException"); } // test a more slightly complex object try (StringWriter writer = new StringWriter()) { new JSONObject() .put("somethingElse", "a value") .put("someKey", new JSONArray() .put(new JSONObject().put("key1", new BrokenToString())) .put(12345) ) .write(writer).toString(); fail("Expected an exception, got a String value"); } catch (JSONException e) { assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage()); } catch(Exception e) { fail("Expected JSONException"); } } /** * Exercise the JSONObject write() method */ /* @Test public void writeAppendable() { String str = "{\"key1\":\"value1\",\"key2\":[1,2,3]}"; String expectedStr = str; JSONObject jsonObject = new JSONObject(str); StringBuilder stringBuilder = new StringBuilder(); Appendable appendable = jsonObject.write(stringBuilder); String actualStr = appendable.toString(); assertTrue("write() expected " +expectedStr+ " but found " +actualStr, expectedStr.equals(actualStr)); } */ /** * Exercise the JSONObject write(Writer, int, int) method */ @Test public void write3Param() throws IOException { String str0 = "{\"key1\":\"value1\",\"key2\":[1,false,3.14]}"; String str2 = "{\n" + " \"key1\": \"value1\",\n" + " \"key2\": [\n" + " 1,\n" + " false,\n" + " 3.14\n" + " ]\n" + " }"; JSONObject jsonObject = new JSONObject(str0); String expectedStr = str0; StringWriter stringWriter = new StringWriter(); try { String actualStr = jsonObject.write(stringWriter,0,0).toString(); assertEquals(expectedStr, actualStr); } finally { stringWriter.close(); } expectedStr = str2; stringWriter = new StringWriter(); try { String actualStr = jsonObject.write(stringWriter,2,1).toString(); assertEquals(expectedStr, actualStr); } finally { stringWriter.close(); } } /** * Exercise the JSONObject write(Appendable, int, int) method */ /* @Test public void write3ParamAppendable() { String str0 = "{\"key1\":\"value1\",\"key2\":[1,false,3.14]}"; String str2 = "{\n" + " \"key1\": \"value1\",\n" + " \"key2\": [\n" + " 1,\n" + " false,\n" + " 3.14\n" + " ]\n" + " }"; JSONObject jsonObject = new JSONObject(str0); String expectedStr = str0; StringBuilder stringBuilder = new StringBuilder(); Appendable appendable = jsonObject.write(stringBuilder,0,0); String actualStr = appendable.toString(); assertEquals(expectedStr, actualStr); expectedStr = str2; stringBuilder = new StringBuilder(); appendable = jsonObject.write(stringBuilder,2,1); actualStr = appendable.toString(); assertEquals(expectedStr, actualStr); } */ /** * Exercise the JSONObject equals() method */ @Test public void equals() { String str = "{\"key\":\"value\"}"; JSONObject aJsonObject = new JSONObject(str); assertTrue("Same JSONObject should be equal to itself", aJsonObject.equals(aJsonObject)); } /** * JSON null is not the same as Java null. This test examines the differences * in how they are handled by JSON-java. */ @Test public void jsonObjectNullOperations() { /** * The Javadoc for JSONObject.NULL states: * "JSONObject.NULL is equivalent to the value that JavaScript calls null, * whilst Java's null is equivalent to the value that JavaScript calls * undefined." * * Standard ECMA-262 6th Edition / June 2015 (included to help explain the javadoc): * undefined value: primitive value used when a variable has not been assigned a value * Undefined type: type whose sole value is the undefined value * null value: primitive value that represents the intentional absence of any object value * Null type: type whose sole value is the null value * Java SE8 language spec (included to help explain the javadoc): * The Kinds of Types and Values ... * There is also a special null type, the type of the expression null, which has no name. * Because the null type has no name, it is impossible to declare a variable of the null * type or to cast to the null type. The null reference is the only possible value of an * expression of null type. The null reference can always be assigned or cast to any reference type. * In practice, the programmer can ignore the null type and just pretend that null is merely * a special literal that can be of any reference type. * Extensible Markup Language (XML) 1.0 Fifth Edition / 26 November 2008 * No mention of null * ECMA-404 1st Edition / October 2013: * JSON Text ... * These are three literal name tokens: ... * null * * There seems to be no best practice to follow, it's all about what we * want the code to do. */ // add JSONObject.NULL then convert to string in the manner of XML.toString() JSONObject jsonObjectJONull = new JSONObject(); Object obj = JSONObject.NULL; jsonObjectJONull.put("key", obj); Object value = jsonObjectJONull.opt("key"); assertTrue("opt() JSONObject.NULL should find JSONObject.NULL", obj.equals(value)); value = jsonObjectJONull.get("key"); assertTrue("get() JSONObject.NULL should find JSONObject.NULL", obj.equals(value)); if (value == null) { value = ""; } String string = value instanceof String ? (String)value : null; assertTrue("XML toString() should convert JSONObject.NULL to null", string == null); // now try it with null JSONObject jsonObjectNull = new JSONObject(); obj = null; jsonObjectNull.put("key", obj); value = jsonObjectNull.opt("key"); assertNull("opt() null should find null", value); // what is this trying to do? It appears to test absolutely nothing... // if (value == null) { // value = ""; // string = value instanceof String ? (String)value : null; // assertTrue("should convert null to empty string", "".equals(string)); try { value = jsonObjectNull.get("key"); fail("get() null should throw exception"); } catch (Exception ignored) {} /** * XML.toString() then goes on to do something with the value * if the key val is "content", then value.toString() will be * called. This will evaluate to "null" for JSONObject.NULL, * and the empty string for null. * But if the key is anything else, then JSONObject.NULL will be emitted * as <key>null</key> and null will be emitted as "" */ String sJONull = XML.toString(jsonObjectJONull); assertTrue("JSONObject.NULL should emit a null value", "<key>null</key>".equals(sJONull)); String sNull = XML.toString(jsonObjectNull); assertTrue("null should emit an empty string", "".equals(sNull)); } @Test(expected = JSONPointerException.class) public void queryWithNoResult() { new JSONObject().query("/a/b"); } @Test public void optQueryWithNoResult() { assertNull(new JSONObject().optQuery("/a/b")); } @Test(expected = IllegalArgumentException.class) public void optQueryWithSyntaxError() { new JSONObject().optQuery("invalid"); } @Test(expected = JSONException.class) public void invalidEscapeSequence() { String json = "{ \"\\url\": \"value\" }"; assertNull("Expected an exception",new JSONObject(json)); } /** * Exercise JSONObject toMap() method. */ @Test public void toMap() { String jsonObjectStr = "{" + "\"key1\":" + "[1,2," + "{\"key3\":true}" + "]," + "\"key2\":" + "{\"key1\":\"val1\",\"key2\":" + "{\"key2\":null}," + "\"key3\":42" + "}," + "\"key3\":" + "[" + "[\"value1\",2.1]" + "," + "[null]" + "]" + "}"; JSONObject jsonObject = new JSONObject(jsonObjectStr); Map<?,?> map = jsonObject.toMap(); assertTrue("Map should not be null", map != null); assertTrue("Map should have 3 elements", map.size() == 3); List<?> key1List = (List<?>)map.get("key1"); assertTrue("key1 should not be null", key1List != null); assertTrue("key1 list should have 3 elements", key1List.size() == 3); assertTrue("key1 value 1 should be 1", key1List.get(0).equals(Integer.valueOf(1))); assertTrue("key1 value 2 should be 2", key1List.get(1).equals(Integer.valueOf(2))); Map<?,?> key1Value3Map = (Map<?,?>)key1List.get(2); assertTrue("Map should not be null", key1Value3Map != null); assertTrue("Map should have 1 element", key1Value3Map.size() == 1); assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE)); Map<?,?> key2Map = (Map<?,?>)map.get("key2"); assertTrue("key2 should not be null", key2Map != null); assertTrue("key2 map should have 3 elements", key2Map.size() == 3); assertTrue("key2 map key 1 should be val1", key2Map.get("key1").equals("val1")); assertTrue("key2 map key 3 should be 42", key2Map.get("key3").equals(Integer.valueOf(42))); Map<?,?> key2Val2Map = (Map<?,?>)key2Map.get("key2"); assertTrue("key2 map key 2 should not be null", key2Val2Map != null); assertTrue("key2 map key 2 should have an entry", key2Val2Map.containsKey("key2")); assertTrue("key2 map key 2 value should be null", key2Val2Map.get("key2") == null); List<?> key3List = (List<?>)map.get("key3"); assertTrue("key3 should not be null", key3List != null); assertTrue("key3 list should have 3 elements", key3List.size() == 2); List<?> key3Val1List = (List<?>)key3List.get(0); assertTrue("key3 list val 1 should not be null", key3Val1List != null); assertTrue("key3 list val 1 should have 2 elements", key3Val1List.size() == 2); assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); assertTrue("key3 list val 1 list element 2 should be 2.1", key3Val1List.get(1).equals(Double.valueOf("2.1"))); List<?> key3Val2List = (List<?>)key3List.get(1); assertTrue("key3 list val 2 should not be null", key3Val2List != null); assertTrue("key3 list val 2 should have 1 element", key3Val2List.size() == 1); assertTrue("key3 list val 2 list element 1 should be null", key3Val2List.get(0) == null); // Assert that toMap() is a deep copy jsonObject.getJSONArray("key3").getJSONArray(0).put(0, "still value 1"); assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); // assert that the new map is mutable assertTrue("Removing a key should succeed", map.remove("key3") != null); assertTrue("Map should have 2 elements", map.size() == 2); } /** * test that validates a singleton can be serialized as a bean. */ @Test public void testSingletonBean() { final JSONObject jo = new JSONObject(Singleton.getInstance()); assertEquals(jo.keySet().toString(), 1, jo.length()); assertEquals(0, jo.get("someInt")); assertEquals(null, jo.opt("someString")); // Update the singleton values Singleton.getInstance().setSomeInt(42); Singleton.getInstance().setSomeString("Something"); final JSONObject jo2 = new JSONObject(Singleton.getInstance()); assertEquals(2, jo2.length()); assertEquals(42, jo2.get("someInt")); assertEquals("Something", jo2.get("someString")); // ensure our original jo hasn't changed. assertEquals(0, jo.get("someInt")); assertEquals(null, jo.opt("someString")); } /** * test that validates a singleton can be serialized as a bean. */ @Test public void testSingletonEnumBean() { final JSONObject jo = new JSONObject(SingletonEnum.getInstance()); assertEquals(jo.keySet().toString(), 1, jo.length()); assertEquals(0, jo.get("someInt")); assertEquals(null, jo.opt("someString")); // Update the singleton values SingletonEnum.getInstance().setSomeInt(42); SingletonEnum.getInstance().setSomeString("Something"); final JSONObject jo2 = new JSONObject(SingletonEnum.getInstance()); assertEquals(2, jo2.length()); assertEquals(42, jo2.get("someInt")); assertEquals("Something", jo2.get("someString")); // ensure our original jo hasn't changed. assertEquals(0, jo.get("someInt")); assertEquals(null, jo.opt("someString")); } /** * Test to validate that a generic class can be serialized as a bean. */ @Test public void testGenericBean() { GenericBean<Integer> bean = new GenericBean<>(42); final JSONObject jo = new JSONObject(bean); assertEquals(jo.keySet().toString(), 8, jo.length()); assertEquals(42, jo.get("genericValue")); assertEquals("Expected the getter to only be called once", 1, bean.genericGetCounter); assertEquals(0, bean.genericSetCounter); } /** * Test to validate that a generic class can be serialized as a bean. */ @Test public void testGenericIntBean() { GenericBeanInt bean = new GenericBeanInt(42); final JSONObject jo = new JSONObject(bean); assertEquals(jo.keySet().toString(), 9, jo.length()); assertEquals(42, jo.get("genericValue")); assertEquals("Expected the getter to only be called once", 1, bean.genericGetCounter); assertEquals(0, bean.genericSetCounter); } /** * Test to verify <code>key</code> limitations in the JSONObject bean serializer. */ @Test public void testWierdListBean() { WeirdList bean = new WeirdList(42, 43, 44); final JSONObject jo = new JSONObject(bean); // get() should have a key of 0 length // get(int) should be ignored base on parameter count // getInt(int) should also be ignored based on parameter count // add(Integer) should be ignore as it doesn't start with get/is and also has a parameter // getALL should be mapped assertEquals("Expected 1 key to be mapped. Instead found: "+jo.keySet().toString(), 1, jo.length()); assertNotNull(jo.get("ALL")); } /** * Tests the exception portions of populateMap. */ @Test public void testExceptionalBean() { ExceptionalBean bean = new ExceptionalBean(); final JSONObject jo = new JSONObject(bean); assertEquals("Expected 1 key to be mapped. Instead found: "+jo.keySet().toString(), 1, jo.length()); assertTrue(jo.get("closeable") instanceof JSONObject); assertTrue(jo.getJSONObject("closeable").has("string")); } }
package picard.sam; import htsjdk.samtools.*; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import picard.cmdline.CommandLineProgramTest; import java.io.File; public class FilterSamReadsTest extends CommandLineProgramTest { @Override public String getCommandLineProgramName() { return FilterSamReads.class.getSimpleName(); } private static final int READ_LENGTH = 151; private final SAMRecordSetBuilder builder = new SAMRecordSetBuilder(); private final static File TEST_DIR = new File("testdata/picard/sam/FilterSamReads/"); @BeforeTest public void setUp() { builder.setReadLength(READ_LENGTH); builder.addPair("mapped_pair_chr1", 0, 1, 151); //should be kept in first test, filtered out in third builder.addPair("mapped_pair_chr2", 1, 1, 151); //should be filtered out for first test, and kept in third builder.addPair("prove_one_of_pair", 0, 1000, 1000); //neither of these will be kept in any test builder.addPair("one_of_pair", 0, 1, 1000); //first read should pass, second should not, but both will be kept in first test } @DataProvider(name = "dataTestJsFilter") public Object[][] dataTestJsFilter() { return new Object[][]{ {"testdata/picard/sam/aligned.sam", "testdata/picard/sam/FilterSamReads/filterOddStarts.js",3}, {"testdata/picard/sam/aligned.sam", "testdata/picard/sam/FilterSamReads/filterReadsWithout5primeSoftClip.js", 0} }; } @DataProvider(name = "dataTestPairedIntervalFilter") public Object[][] dataTestPairedIntervalFilter() { return new Object[][]{ {"testdata/picard/sam/FilterSamReads/filter1.interval_list", 4}, {"testdata/picard/sam/FilterSamReads/filter2.interval_list", 0} }; } /** * filters a SAM using a javascript filter */ @Test(dataProvider = "dataTestJsFilter") public void testJavaScriptFilters(final String samFilename, final String javascriptFilename,final int expectNumber) throws Exception { // input as SAM file final File inputSam = new File(samFilename); final File javascriptFile = new File(javascriptFilename); FilterSamReads filterTest = setupProgram(javascriptFile, inputSam, FilterSamReads.Filter.includeJavascript); Assert.assertEquals(filterTest.doWork(),0); int count = getReadCount(filterTest); Assert.assertEquals(count, expectNumber); } /** * filters a SAM using an interval filter */ @Test(dataProvider = "dataTestPairedIntervalFilter") public void testPairedIntervalFilter(final String intervalFilename, final int expectNumber) throws Exception { // input as SAM file final File inputSam = File.createTempFile("testSam", ".sam", TEST_DIR); inputSam.deleteOnExit(); final SAMFileWriter writer = new SAMFileWriterFactory() .setCreateIndex(true).makeBAMWriter(builder.getHeader(), false, inputSam); for (final SAMRecord record : builder) { writer.addAlignment(record); } writer.close(); final File intervalFile = new File(intervalFilename); FilterSamReads filterTest = setupProgram(intervalFile, inputSam, FilterSamReads.Filter.includePairedIntervals); Assert.assertEquals(filterTest.doWork(),0); int count = getReadCount(filterTest); Assert.assertEquals(count, expectNumber); } private FilterSamReads setupProgram(final File inputFile, final File inputSam, final FilterSamReads.Filter filter) throws Exception { final FilterSamReads program = new FilterSamReads(); program.INPUT = inputSam; program.OUTPUT = File.createTempFile("FilterSamReads.output.", ".sam"); program.OUTPUT.deleteOnExit(); program.FILTER = filter; if(filter == FilterSamReads.Filter.includePairedIntervals) { program.INTERVAL_LIST = inputFile; } else { program.JAVASCRIPT_FILE = inputFile; } return program; } private int getReadCount(FilterSamReads filterTest) throws Exception { final SamReader samReader = SamReaderFactory.makeDefault().open(filterTest.OUTPUT); final SAMRecordIterator iter = samReader.iterator(); int count = 0; while (iter.hasNext()) { iter.next(); ++ count; } iter.close(); samReader.close(); return count; } }
package pig.testing.exec; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.hadoop.hive.cli.CliDriver; import org.apache.hadoop.hive.ql.metadata.HiveException; public class HiveExecutor { public static void execHive(String[] hiveCliArgs) throws HiveException { CliDriver cd = new CliDriver(); try { int retVal = cd.run(hiveCliArgs); if(retVal != 0 ){ throw new HiveException(); } } catch (Exception e) { throw new HiveException(e); } } public static String[] getMetastoreConfig() throws HiveException { String currentPath = Paths.get(".").toAbsolutePath().normalize().toString(); ArrayList<String> hiveCliArgsMetastore = new ArrayList<String>(); hiveCliArgsMetastore.add("--hiveconf"); hiveCliArgsMetastore.add("hive.metastore.warehouse.dir=file:///"+FilenameUtils.separatorsToUnix(currentPath)+"/tmp/warehouse"); hiveCliArgsMetastore.add("--hiveconf"); hiveCliArgsMetastore.add("javax.jdo.option.ConnectionURL=jdbc:derby:;databaseName=tmp/metastore_db;create=true"); hiveCliArgsMetastore.add("--hiveconf"); hiveCliArgsMetastore.add("fs.default.name=file:///"+FilenameUtils.separatorsToUnix(currentPath)+"/tmp"); //file://${user.dir}/ return hiveCliArgsMetastore.toArray(new String[0]); } public static void cleanup() throws HiveException, IOException { String currentPath = Paths.get(".").toAbsolutePath().normalize().toString(); FileUtils.deleteDirectory(new File(currentPath+"/tmp")); } }
package us.bpsm.edn.parser; import static org.junit.Assert.assertEquals; import static us.bpsm.edn.Symbol.newSymbol; import static us.bpsm.edn.Tag.newTag; import static us.bpsm.edn.TaggedValue.newTaggedValue; import static us.bpsm.edn.parser.Parser.Config.BIG_DECIMAL_TAG; import static us.bpsm.edn.parser.Parser.Config.BIG_INTEGER_TAG; import static us.bpsm.edn.parser.Parser.Config.DOUBLE_TAG; import static us.bpsm.edn.parser.Parser.Config.LONG_TAG; import static us.bpsm.edn.parser.Parsers.defaultConfiguration; import static us.bpsm.edn.parser.Parsers.newParserConfigBuilder; import java.io.IOException; import java.io.PushbackReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.junit.Test; import us.bpsm.edn.Tag; import us.bpsm.edn.parser.Parseable; import us.bpsm.edn.parser.Parser; import us.bpsm.edn.parser.Parsers; import us.bpsm.edn.parser.TagHandler; public class ParserTest { @Test public void parseEdnSample() throws IOException { Parseable pbr = Parsers.newParseable(IOUtil.stringFromResource("us/bpsm/edn/edn-sample.txt")); Parser parser = Parsers.newParser(Parsers.defaultConfiguration()); @SuppressWarnings("unchecked") List<Object> expected = Arrays.asList( map(ScannerTest.key("keyword"), ScannerTest.sym("symbol"), 1L, 2.0d, new BigInteger("3"), new BigDecimal("4.0")), Arrays.asList(1L, 1L, 2L, 3L, 5L, 8L), new HashSet<Object>(Arrays.asList('\n', '\t')), Arrays.asList(Arrays.asList(Arrays.asList(true, false, null)))); List<Object> results = new ArrayList<Object>(); for (int i = 0; i < 4; i++) { results.add(parser.nextValue(pbr)); } assertEquals(expected, results); } @Test public void parseTaggedValueWithUnkownTag() { assertEquals(newTaggedValue(newTag(newSymbol("foo", "bar")), 1L), parse("#foo/bar 1")); } @Test public void parseTaggedInstant() { assertEquals(1347235200000L, ((Date)parse("#inst \"2012-09-10\"")).getTime()); } @Test public void parseTaggedUUID() { assertEquals(UUID.fromString("f81d4fae-7dec-11d0-a765-00a0c91e6bf6"), parse("#uuid \"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"")); } private static final String INVALID_UUID = "#uuid \"f81d4fae-XXXX-11d0-a765-00a0c91e6bf6\""; @Test(expected=NumberFormatException.class) public void invalidUUIDCausesException() { parse(INVALID_UUID); } @Test public void discardedTaggedValuesDoNotCallTransformer() { // The given UUID is invalid, as demonstrated in the test above. // were the transformer for #uuid to be called despite the #_, // it would throw an exception and cause this test to fail. assertEquals(123L, parse("#_ " + INVALID_UUID + " 123")); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableListByDefault() { ((List<?>)parse("(1)")).remove(0); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableVectorByDefault() { ((List<?>)parse("[1]")).remove(0); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableSetByDefault() { ((Set<?>)parse("#{1}")).remove(1); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableMapByDefault() { ((Map<?,?>)parse("{1,-1}")).remove(1); } @Test public void integersParseAsLongByDefault() { List<?> expected = Arrays.asList( Long.MIN_VALUE, (long)Integer.MIN_VALUE, -1L, 0L, 1L, (long)Integer.MAX_VALUE, Long.MAX_VALUE); List<?> results = (List<?>)parse("[" + Long.MIN_VALUE + ", " + Integer.MIN_VALUE + ", -1, 0, 1, " + Integer.MAX_VALUE + ", " + Long.MAX_VALUE + "]"); // In Java Integer and Long are never equal(), even if they have // the same value. assertEquals(expected, results); } @Test public void integersAutoPromoteToBigIfTooBig() { BigInteger tooNegative = BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE); BigInteger tooPositive = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE); List<?> expected = Arrays.asList(tooNegative, tooPositive); List<?> results = (List<?>)parse("[" + tooNegative +" " + tooPositive + "]"); assertEquals(expected, results); } @Test public void canCustomizeParsingOfInteger() { Parser.Config cfg = newParserConfigBuilder() .putTagHandler(LONG_TAG, new TagHandler() { public Object transform(Tag tag, Object value) { return Integer.valueOf(((Long)value).intValue()); }}) .putTagHandler(BIG_INTEGER_TAG, new TagHandler() { public Object transform(Tag tag, Object value) { return Integer.valueOf(((BigInteger)value).intValue()); }}) .build(); List<Integer> expected = Arrays.asList(-1, 0, 0, 1); List<?> results = (List<?>) parse(cfg, "[-1N, 0, 0N, 1]"); assertEquals(expected, results); } @Test public void canCustomizeParsingOfFloats() { Parser.Config cfg = newParserConfigBuilder() .putTagHandler(DOUBLE_TAG, new TagHandler() { public Object transform(Tag tag, Object value) { Double d = (Double) value; return d * 2.0; }}) .putTagHandler(BIG_DECIMAL_TAG, new TagHandler() { public Object transform(Tag tag, Object value) { BigDecimal d = (BigDecimal)value; return d.multiply(BigDecimal.TEN); }}) .build(); @SuppressWarnings("unchecked") List<?> expected = Arrays.asList(BigDecimal.TEN.negate(), BigDecimal.ZERO, BigDecimal.TEN, -2.0d, 0.0d, 2.0d); List<?> results = (List<?>) parse(cfg, "[-1M, 0M, 1M, -1.0, 0.0, 1.0]"); assertEquals(expected, results); } //@Test public void performanceOfInstantParsing() { StringBuilder b = new StringBuilder(); for (int h = -12; h <= 12; h++) { b.append("#inst ") .append('"') .append("2012-11-25T10:11:12.343") .append(String.format("%+03d", h)) .append(":00") .append('"') .append(' '); } for (int i = 0; i < 9; i++) { b.append(b.toString()); } String txt = "[" + b.toString() + "]"; long ns = System.nanoTime(); List<?> result = (List<?>) parse(txt); ns = System.nanoTime() - ns; long ms = ns / 1000000; System.out.printf("%d insts took %d ms (%1.2f ms/inst)\n", result.size(), ms, (1.0*ms)/result.size()); } static Object parse(String input) { return parse(defaultConfiguration(), input); } static Object parse(Parser.Config cfg, String input) { return Parsers.newParser(cfg).nextValue(Parsers.newParseable(input)); } private Map<Object, Object> map(Object... kvs) { Map<Object, Object> m = new HashMap<Object, Object>(); for (int i = 0; i < kvs.length; i += 2) { m.put(kvs[i], kvs[i + 1]); } return m; } }
package btl_PI; import java.awt.Point; import java.util.Random; /* * Class Matrix tao 1 matran vs kich thuoc m x n cac phuong thuc tao gia tri cac phan tu cua ma tran * va cac phuong thuc thuat toan an 2 diem */ public class Matrix { /* * ham khoi tao ma tran */ private int[][] matrix; int row, col; public Matrix(int n, int m) { this.row = n; this.col = m; this.matrix = new int[row][col]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) this.matrix[i][j] = -1; } } public int[][] getMatrix() { return this.matrix; } /* * Phuong thuc khoi tao ma tran random */ public void setMatrixmatrix() { Random rand = new Random(); for (int i = 1; i < this.row - 1; i++) for (int j = 1; j < this.col - 1; j++) { this.matrix[i][j] = rand.nextInt(36); } // Tao cac cap giong nhau for (int i = 0; i < 36; i++) { if ((demPT(i) % 2) != 0) change(i); } } // Thay doi phan tu de thanh cac cap private void change(int m) { for (int i = 1; i < this.row - 1; i++) for (int j = 1; j < this.col - 1;) { if (this.matrix[i][j] == m) this.matrix[i][j]++; return; } } /* * Dem so phan tu giong nhau */ private int demPT(int m) { int d = 0; for (int i = 1; i < this.row - 1; i++) for (int j = 1; j < this.col - 1; j++) { if (this.matrix[i][j] == m) d++; } return d; } /* Giai thuat DK thoa man tro choi */ /* TH_1 : Truong hop cung nam tren 1 hang hoac 1 cot */ // Kiem tra voi hang x , cot y1,y2 private boolean checkLineX(int y1, int y2, int x) { // Tim cot max va min int maxColum = Math.max(y1, y2); int minColum = Math.min(y1, y2); if ((minColum + 1) == maxColum) return true; // Run for (int i = minColum + 1; i < maxColum; i++) { if (this.matrix[x][i] != -1) return false; // khong thuc hien duoc } return true; } // Kiem tra voi cot y, hang x1,x2 private boolean checkLineY(int x1, int x2, int y) { // Tim cot max va min int maxRow = Math.max(x1, x2); int minRow = Math.min(x1, x2); if ((minRow + 1) == maxRow) return true; // Run for (int i = minRow + 1; i < maxRow; i++) { if (this.matrix[i][y] != -1) return false; // khong thuc hien duoc } return true; } /* * TH_2 : Xet duyet cac duong di theo chieu ngang, doc trong pham vi chu * nhat */ // Xet duyet duong di theo chieu ngang trong pham vi chu nhat private boolean checkRectX(Point p1, Point p2) { Point pMinY = p1; Point pMaxY = p2; if (p1.y > p2.y) { pMinY = p2; pMaxY = p1; } // Tim cot va x for (int i = pMinY.y; i <= pMaxY.y; i++) { if (i > pMinY.y && this.matrix[pMinY.x][i] != -1) { return false; } if ((this.matrix[pMaxY.x][i] == -1 || i == pMaxY.y) && checkLineY(pMinY.x, pMaxY.x, i) && checkLineX(i, pMaxY.y, pMaxY.x)) { return true; } } return false; } // Xet duyet duonng di theo chieu doc trong pham vi chu nhat private boolean checkRectY(Point p1, Point p2) { Point pMinX = p1; Point pMaxX = p2; if (p1.x > p2.x) { pMinX = p2; pMaxX = p1; } // tim hang va cot y for (int i = pMinX.x; i <= pMaxX.x; i++) { if (i > pMinX.x && this.matrix[i][pMinX.y] != -1) { return false; } if ((this.matrix[i][pMaxX.y] == -1 || i == pMaxX.x) && checkLineX(pMinX.y, pMaxX.y, i) && checkLineY(i, pMaxX.x, pMaxX.y)) { return true; } } return false; } // Xet mo rong theo chieu ngang type = 1 ( di ben phai) type = -1 (di ben // trai) private boolean checkMoreLineX(Point p1, Point p2, int type) { Point pMinY = p1, pMaxY = p2; if (p1.y > p2.y) { pMinY = p2; pMaxY = p1; } // Tim hang va y int y = pMaxY.y + type; int _row = pMinY.x; int colFinish = pMaxY.y; if (type == -1) { colFinish = pMinY.y; y = pMinY.y + type; _row = pMaxY.x; } // Tim cot ket thuc cua hang x // check more if ((this.matrix[_row][colFinish] == -1 || pMinY.y == pMaxY.y) && checkLineX(pMinY.y, pMaxY.y, _row)) { while (this.matrix[pMinY.x][y] == -1 && this.matrix[pMaxY.x][y] == -1) { if (checkLineY(pMinY.x, pMaxY.x, y)) { return true; } y += type; } } return false; } // Xet mo rong theo chieu doc type = 1 ( di len tren) type = -1 (di xuong // duoi) private boolean checkMoreLineY(Point p1, Point p2, int type) { Point pMinX = p1, pMaxX = p2; if (p1.x > p2.x) { pMinX = p2; pMaxX = p1; } int x = pMaxX.x + type; int _col = pMinX.y; int rowFinish = pMaxX.x; if (type == -1) { rowFinish = pMinX.x; x = pMinX.x + type; _col = pMaxX.y; } if ((this.matrix[rowFinish][_col] == -1 || pMinX.x == pMaxX.x) && checkLineY(pMinX.x, pMaxX.x, _col)) { while (this.matrix[x][pMinX.y] == -1 && this.matrix[x][pMaxX.y] == -1) { if (checkLineX(pMinX.y, pMaxX.y, x)) { return true; } x += type; } } return false; } }
package szoftlab4; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; public class Game { private Map map; private Mission mission; private List<Enemy> enemies = new ArrayList<Enemy>(); private List<Projectile> projectiles = new ArrayList<Projectile>(); private List<Obstacle> obstacles = new ArrayList<Obstacle>(); private List<Tower> towers = new ArrayList<Tower>(); private int magic = 1500; public static final int FPS = 30; public Game() { map = new Map(""); mission = new Mission(""); } public static void main(String[] args) { new Game().run(); } public void run() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true) { String line = ""; Scanner ls = null; try { line = br.readLine(); ls = new Scanner(new InputStreamReader(new ByteArrayInputStream(line.getBytes("UTF-8")))); if (!ls.hasNext()) { continue; } String command = ls.next(); if (command.equals("loadMap")) { map = new Map(ls.next()); } else if (command.equals("loadMission")) { mission = new Mission(ls.next()); } else if (command.equals("setFog")) { int opt = ls.nextInt(); if (!((opt == 0) || (opt == 1))) { throw new IllegalArgumentException(); } Fog.setFog(opt == 1); } else if (command.equals("setCritical")) { int opt = ls.nextInt(); if (!((opt == 0) || (opt == 1))) { throw new IllegalArgumentException(); } Tower.critical = (opt == 1); } else if (command.equals("setWaypoint")) { } else if (command.equals("step")) { int num = ls.nextInt(); if (num < 0) { throw new IllegalArgumentException(); } for (int i = 0; i < num; ++i) { step(); } } else if (command.equals("buildTower")) { double x = ls.nextDouble(); double y = ls.nextDouble(); buildTower(new Vector(x, y)); } else if (command.equals("buildObstacle")) { double x = ls.nextDouble(); double y = ls.nextDouble(); buildObstacle(new Vector(x, y)); } else if (command.equals("enchant")) { String type = ls.next(); double x = ls.nextDouble(); double y = ls.nextDouble(); Vector point = new Vector(x, y); if (type.equals("red")) { addGem(point, TowerGem.red); } else if (type.equals("green")) { addGem(point, TowerGem.green); } else if (type.equals("blue")) { addGem(point, TowerGem.blue); } else if (type.equals("yellow")) { addGem(point, ObstacleGem.yellow); } else if (type.equals("orange")) { addGem(point, ObstacleGem.orange); } else { throw new IllegalArgumentException(); } } else if (command.equals("listEnemies")) { listEnemies(); } else if (command.equals("listTowers")) { listTowers(); } else if (command.equals("listObstacles")) { listObstacles(); } else if (command.equals("listProjectiles")) { listProjectiles(); } else { System.out.println("Ismeretlen parancs!"); } } catch (IOException e) { System.out.println("Bemeneti hiba!"); e.printStackTrace(); } catch (NoSuchElementException e) { System.out.println("Hibás parancsformátum!"); } catch (IllegalArgumentException e) { System.out.println("Érvénytelen paraméter!"); } finally { ls.close(); } } } private void step() { slowEnemies(); moveEnemies(); Enemy enemy = mission.getNextEnemy(); if (enemy != null) { addEnemy(enemy); } moveProjectiles(); towersFire(); } private void moveProjectiles(){ for(Projectile p : projectiles){ if(p.step()) projectiles.remove(p); } } private void towersFire(){ for(Tower t : towers){ t.attack(enemies, this); } } private void moveEnemies() { for(Enemy e : enemies) { e.move(); } } private void slowEnemies(){ for(Enemy e : enemies){ for(Obstacle o : obstacles){ if(e.getPosition().equals(o.getPosition(), 5)) e.setSlowingFactor(o.getSlowingFactor(e)); else e.setSlowingFactor(1); } } } public int getMagic(){ return magic; } public void addGem(Vector pos, TowerGem gem) { Tower t = getCollidingTower(pos); if (t != null) { t.setGem(gem); } } public void addGem(Vector pos, ObstacleGem gem) { Obstacle o = getCollidingObstacle(pos); if (o != null) { o.setGem(gem); } } public void addEnemy(Enemy en){ enemies.add(en); } public boolean buildObstacle(Vector pos) { if (map.canBuildObstacle(pos) && !collidesWithObstacle(pos)){ obstacles.add(new Obstacle(pos)); return true; } return false; } public boolean buildTower(Vector pos) { if (map.canBuildTower(pos) && !collidesWithTower(pos)){ towers.add(new Tower(pos)); return true; } return false; } public boolean collidesWithObstacle(Vector pos) { for (Obstacle o : obstacles){ if (o.doesCollide(pos)) return true; } return false; } public boolean collidesWithTower(Vector pos) { for (Tower t : towers){ if (t.doesCollide(pos)) return true; } return false; } public Obstacle getCollidingObstacle(Vector pos) { for (Obstacle o : obstacles){ if (o.doesCollide(pos)) return o; } return null; } public Tower getCollidingTower(Vector pos) { for (Tower t : towers){ if (t.doesCollide(pos)) return t; } return null; } void listEnemies() { for (Enemy e : enemies) { System.out.println(String.format("%d %.1f (%.1f;%.1f)", e.getID(), e.getHealth(), e.getPosition().x, e.getPosition().y)); } } void listTowers() { for (Tower t : towers) { System.out.print(String.format("(%.1f;%.1f) ", t.getPosition().x, t.getPosition().y)); TowerGem tg = t.getGem(); if (tg == TowerGem.red) { System.out.println("red"); } else if (tg == TowerGem.green) { System.out.println("green"); } else if (tg == TowerGem.blue) { System.out.println("blue"); } else { System.out.println("-"); } } } void listObstacles() { for (Obstacle o : obstacles) { System.out.print(String.format("(%.1f;%.1f) ", o.getPosition().x, o.getPosition().y)); ObstacleGem og = o.getGem(); if (og == ObstacleGem.yellow) { System.out.println("yellow"); } else if (og == ObstacleGem.orange) { System.out.println("orange"); } else { System.out.println("-"); } } } void listProjectiles() { for (Projectile p : projectiles) { System.out.println(String.format("(%.1f;%.1f) %d %b", p.getPosition().x, p.getPosition().y, p.target.getID(), p instanceof SplitterProjectile)); } } }
package app.hongs.dh.lucene; import app.hongs.Cnst; import app.hongs.Core; import app.hongs.CoreConfig; import app.hongs.CoreLocale; import app.hongs.CoreLogger; import app.hongs.HongsException; import app.hongs.HongsExpedient; import app.hongs.action.FormSet; import app.hongs.dh.IEntity; import app.hongs.dh.ITrnsct; import app.hongs.dh.ModelForm; import app.hongs.dh.lucene.field.*; import app.hongs.dh.lucene.query.*; import app.hongs.dh.lucene.value.*; import app.hongs.util.Data; import app.hongs.util.Dict; import app.hongs.util.Synt; import app.hongs.util.Tool; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.custom.CustomAnalyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.Query; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.BoostQuery; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; /** * Lucene * * : * lucene-fieldtype Lucene (string,search,stored,int,long,float,double) * lucene-tokenizer * lucene-char-filter * lucene-token-filter * lucene-find-filter * lucene-query-filter * * @author Hongs */ public class LuceneRecord extends ModelForm implements IEntity, ITrnsct, Cloneable, AutoCloseable { protected boolean TRNSCT_MODE = false; protected boolean OBJECT_MODE = false; private IndexSearcher finder = null ; private IndexReader reader = null ; private IndexWriter writer = null ; private String dtpath = null ; private String dtname = null ; /** * * @param path * @param form * @param fmap * @param dmap * @throws HongsException */ public LuceneRecord(String path, Map form, Map fmap, Map dmap) throws HongsException { super(form, fmap, dmap); if (form != null) { String dp = Dict.getValue(form, String.class, "@", "data-path"); String dn = Dict.getValue(form, String.class, "@", "base-name"); if (dp != null && dp.length() != 0) { path = dp; } if (dn != null && dn.length() != 0) { dtname = dn; } } if (path != null) { Map m = new HashMap(); m.put("CORE_PATH", Core.CORE_PATH); m.put("CONF_PATH", Core.CORE_PATH); m.put("DATA_PATH", Core.DATA_PATH); path = Tool.inject(path, m); if (! new File(path).isAbsolute()) { path = Core.DATA_PATH + "/lucene/" + path; } } this.dtpath = path; CoreConfig conf = CoreConfig.getInstance( ); this.TRNSCT_MODE = Synt.declare( Core.getInstance().got(Cnst.TRNSCT_MODE), conf.getProperty("core.in.trnsct.mode", false)); this.OBJECT_MODE = Synt.declare( Core.getInstance().got(Cnst.OBJECT_MODE), conf.getProperty("core.in.object.mode", false)); } public LuceneRecord(String path, Map form) throws HongsException { this(path, form, null, null); } public LuceneRecord(String path) throws HongsException { this(path, null, null, null); } /** * * conf/form conf.form * conf/form.form * Core * @param conf * @param form * @return * @throws HongsException */ public static LuceneRecord getInstance(String conf, String form) throws HongsException { LuceneRecord inst; Core core = Core.getInstance(); String name = LuceneRecord.class.getName( ) + ":" + conf + "." + form; if ( ! core.containsKey( name )) { String path = conf + "/" + form; String canf = FormSet.hasConfFile(path) ? path : conf ; Map farm = FormSet.getInstance(canf).getForm( form); inst = new LuceneRecord(path , farm); core.put( name, inst ); } else { inst = (LuceneRecord) core.got(name); } return inst; } / /** * * * , default.properties : * id ID, id (info) * rn , 0 * gn * pn * wd * ob * rb * or "" * ar * sr "", LuceneRecord * (id,wd) * * @param rd * @return * @throws HongsException */ @Override public Map search(Map rd) throws HongsException { // id getOne Object id = rd.get (Cnst.ID_KEY); if (id != null && !(id instanceof Collection) && !(id instanceof Map)) { if ( "".equals( id ) ) { return new HashMap(); } Map data = new HashMap(); Map info = getOne(rd); data.put("info", info); return data; } int rn; if (rd.containsKey(Cnst.RN_KEY)) { rn = Synt.declare(rd.get(Cnst.RN_KEY), 0); } else { rn = CoreConfig.getInstance().getProperty("fore.rows.per.page", Cnst.RN_DEF); } // 0, getAll if (rn == 0) { Map data = new HashMap(); List list = getAll(rd); data.put("list", list); return data; } int gn; if (rd.containsKey(Cnst.GN_KEY)) { gn = Synt.declare(rd.get(Cnst.GN_KEY), 0); } else { gn = CoreConfig.getInstance().getProperty("fore.pags.for.page", Cnst.GN_DEF); } int pn = Synt.declare(rd.get(Cnst.PN_KEY), 1); if (pn < 1) pn = 1; if (gn < 1) gn = 1; int minPn = pn - (gn / 2 ); if (minPn < 1) minPn = 1; int maxPn = gn + minPn - 1; int limit = rn * maxPn + 1; int minRn = rn * (pn - 1 ); int maxRn = rn + minRn; List list = getAll(rd, limit, minRn, maxRn); int rc = (int) list.remove(0); int pc = (int) Math.ceil( (double) rc / rn); Map resp = new HashMap(); Map page = new HashMap(); resp.put("list", list); resp.put("page", page); page.put("page", pn); page.put("pags", gn); page.put("rows", rn); page.put("pagecount", pc); page.put("rowscount", rc); page.put("uncertain", rc == limit); // true if (rc == 0) { page.put("ern", 1); } else if (list.isEmpty()) { page.put("ern", 2); } return resp; } /** * * @param rd * @return id,name(dispCols) * @throws HongsException */ @Override public Map create(Map rd) throws HongsException { String id = add(rd); Set<String> fs = getListable(); if (fs != null && !fs.isEmpty()) { Map sd = new LinkedHashMap(); for(String fn : getListable()) { if ( ! fn.contains( "." )) { sd.put( fn , rd.get(fn)); } } sd.put(Cnst.ID_KEY, id); return sd; } else { rd.put(Cnst.ID_KEY, id); return rd; } } /** * * @param rd * @return * @throws HongsException */ @Override public int update(Map rd) throws HongsException { Set<String> ids = Synt.declare(rd.get(Cnst.ID_KEY), new HashSet()); Map wh = Synt.declare(rd.get(Cnst.WR_KEY), new HashMap()); for(String id : ids) { if(!permit(wh,id)) { throw new HongsException(0x1096, "Can not update for id '"+id+"'"); } put(id, rd ); } return ids.size(); } /** * * @param rd * @return * @throws HongsException */ @Override public int delete(Map rd) throws HongsException { Set<String> ids = Synt.declare(rd.get(Cnst.ID_KEY), new HashSet()); Map wh = Synt.declare(rd.get(Cnst.WR_KEY), new HashMap()); for(String id : ids) { if(!permit(wh,id)) { throw new HongsException(0x1097, "Can not delete for id '"+id+"'"); } del(id ); } return ids.size(); } /** * * @param wh * @param id * @return * @throws HongsException */ protected boolean permit(Map wh, String id) throws HongsException { if (id == null || "".equals(id)) { throw new NullPointerException("Param id for permit can not be empty"); } if (wh == null) { throw new NullPointerException("Param wh for permit can not be null."); } Set<String> rb ; wh = new HashMap(wh); rb = new HashSet( ); rb.add( "id" ); wh.put(Cnst.ID_KEY, id); wh.put(Cnst.RB_KEY, rb); wh = getOne(wh); return wh != null && !wh.isEmpty(); } / /** * * @param rd * @return ID * @throws HongsException */ public String add(Map rd) throws HongsException { String id = Synt.declare(rd.get(Cnst.ID_KEY), String.class); if (id != null && id.length() != 0) { throw new HongsException.Common("Id can not set in add"); } id = Core.newIdentity(); rd.put(Cnst.ID_KEY, id); addDoc(map2Doc(rd)); return id; } /** * () * @param id * @param rd * @throws HongsException */ public void set(String id, Map rd) throws HongsException { if (id == null || id.length() == 0) { throw new NullPointerException("Id must be set in set"); } Document doc = getDoc(id); if (doc == null) { doc = new Document(); } else { /** * * doc , * map , * Store=NO */ setView(new HashMap()); Map md = doc2Map(doc); md.putAll(rd); rd = md; doc = new Document(); } rd.put(Cnst.ID_KEY, id); docAdd(doc, rd); setDoc(id, doc); } /** * () * @param id * @param rd * @throws HongsException */ public void put(String id, Map rd) throws HongsException { if (id == null || id.length() == 0) { throw new NullPointerException("Id must be set in put"); } Document doc = getDoc(id); if (doc == null) { throw new NullPointerException("Doc#"+id+" not exists"); } else { /** * * doc , * map , * Store=NO */ setView(new HashMap()); Map md = doc2Map(doc); md.putAll(rd); rd = md; } rd.put(Cnst.ID_KEY, id); docAdd(doc, rd); setDoc(id, doc); } /** * (delDoc ) * @param id * @throws HongsException */ public void del(String id) throws HongsException { if (id == null || id.length() == 0) { throw new NullPointerException("Id must be set in del"); } Document doc = getDoc(id); if (doc == null) { throw new NullPointerException("Doc#"+id+" not exists"); } delDoc(id); } /** * * @param id * @return * @throws HongsException */ public Map get(String id) throws HongsException { Document doc = getDoc(id); if (doc != null) { setView(new HashMap()); return doc2Map( doc ); } else { return new HashMap( ); } } /** * * @param rd * @return * @throws HongsException */ public Map getOne(Map rd) throws HongsException { Loop roll = search(rd, 0, 1); if ( roll.hasNext( )) { return roll.next( ); } else { return new HashMap(); } } /** * * @param rd * @return * @throws HongsException */ public List getAll(Map rd) throws HongsException { Loop roll = search(rd, 0, 0); List list = new LinkedList(); while ( roll.hasNext()) { list.add(roll.next()); } return list; } /** * * @param rd * @param total * @param begin * @param end (), 0 * @return , .poll() * @throws HongsException */ public List getAll(Map rd, int total, int begin, int end) throws HongsException { Loop roll = search(rd, begin, total - begin); List list = new LinkedList(); int idx = begin ; if ( end == 0 ) { end = total - begin; } list.add( roll.size( ) ); while ( roll.hasNext()) { list.add(roll.next()); if ( ++idx >= end ) { break ; } } return list; } /** * * @param rd * @param begin * @param limit * @return * @throws HongsException */ public Loop search(Map rd, int begin, int limit) throws HongsException { Query q = getQuery(rd); Sort s = getSort (rd); setView (rd); Loop r = new Loop(this, q, s, begin, limit); if (0 < Core.DEBUG && 8 != (8 & Core.DEBUG)) { CoreLogger.debug("LuceneRecord.search: " + r.toString()); } return r ; } / public void addDoc(Document doc) throws HongsException { IndexWriter iw = getWriter(); try { iw.addDocument (doc); } catch (IOException ex) { throw new HongsException.Common(ex); } if (!TRNSCT_MODE) { commit(); } } public void setDoc(String id, Document doc) throws HongsException { IndexWriter iw = getWriter(); try { iw.updateDocument (new Term(Cnst.ID_KEY, id), doc); } catch (IOException ex) { throw new HongsException.Common(ex); } if (!TRNSCT_MODE) { commit(); } } public void delDoc(String id) throws HongsException { IndexWriter iw = getWriter(); try { iw.deleteDocuments(new Term(Cnst.ID_KEY, id) ); } catch (IOException ex) { throw new HongsException.Common(ex); } if (!TRNSCT_MODE) { commit(); } } public Document getDoc(String id) throws HongsException { IndexSearcher ff = getFinder( ); try { Query qq = new TermQuery(new Term(Cnst.ID_KEY, id)); TopDocs tt = ff.search(qq, 1 ); ScoreDoc[] hh = tt.scoreDocs; if ( 0 != hh.length ) { return ff.doc(hh[0].doc); } else { return null; } } catch ( IOException ex ) { throw new HongsException.Common(ex); } } public Document map2Doc(Map map) throws HongsException { Document doc = new Document(); docAdd(doc, map); return doc; } public Map doc2Map(Document doc) { Map map = new LinkedHashMap(); mapAdd(map, doc); return map; } / /** * * @throws HongsException */ public void init() throws HongsException { if (reader != null) { return; } String dbpath = getDbPath(); try { if (! (new File(dbpath)).exists() ) { String id = Core.newIdentity( ); Map rd = new HashMap( ); rd.put(Cnst.ID_KEY, id); addDoc(map2Doc(rd)); delDoc(id); commit( ); } Path p = Paths.get(dbpath ); Directory dir = FSDirectory.open(p); reader = DirectoryReader.open (dir); finder = new IndexSearcher (reader); } catch (IOException x) { throw new HongsException.Common (x); } if (0 < Core.DEBUG && 4 != (4 & Core.DEBUG)) { CoreLogger.trace("Connect to lucene reader, data path: " + dbpath); } } /** * * @throws HongsException */ public void open() throws HongsException { if (writer != null && writer.isOpen()) { return; } String dbpath = getDbPath(); try { IndexWriterConfig iwc = new IndexWriterConfig(getAnalyzer()); iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); Path d = Paths.get(dbpath ); Directory dir = FSDirectory.open(d); writer = new IndexWriter(dir , iwc); } catch (IOException x) { throw new HongsException.Common (x); } if (0 < Core.DEBUG && 4 != (4 & Core.DEBUG)) { CoreLogger.trace("Connect to lucene writer, data path: " + dbpath); } } @Override public void close() { if (writer != null) { if (TRNSCT_MODE) { try { try { commit(); } catch (Error er) { revert(); throw er; } } catch (Error e) { CoreLogger.error(e); } } try { writer.maybeMerge(); } catch (IOException x) { CoreLogger.error(x); } try { writer.close(); } catch (IOException x) { CoreLogger.error(x); } finally { writer = null; } } if (reader != null) { try { reader.close(); } catch (IOException x) { CoreLogger.error(x); } finally { reader = null; } } if (0 < Core.DEBUG && 4 != (4 & Core.DEBUG)) { CoreLogger.trace("Close lucene connection, data path: " + getDbPath()); } } @Override public LuceneRecord clone() { try { return (LuceneRecord) super.clone(); } catch (CloneNotSupportedException ex) { throw new InternalError(ex.getMessage()); } } @Override protected void finalize() throws Throwable { try { this.close( ); } finally { super.finalize(); } } @Override public void begin() { TRNSCT_MODE = true; } @Override public void commit() { if (writer == null) { return; } TRNSCT_MODE = Synt.declare(Core.getInstance().got(Cnst.TRNSCT_MODE), false); try { writer.commit( ); } catch (IOException ex) { throw new HongsExpedient(0x102c, ex); } } @Override public void revert() { if (writer == null) { return; } TRNSCT_MODE = Synt.declare(Core.getInstance().got(Cnst.TRNSCT_MODE), false); try { writer.rollback(); } catch (IOException ex) { throw new HongsExpedient(0x102d, ex); } } / public String getDbPath() { if (null != dtpath) { return dtpath; } throw new NullPointerException("DBPath can not be null"); } public String getDbName() { if (null != dtname) { return dtname; } String p = Core.DATA_PATH + "/lucene/"; String d = getDbPath(); if (! "/".equals (File.separator) ) { d = d.replace(File.separator, "/"); } if (d.endsWith("/")) { d = d.substring(0,d.length()-1); } if (d.startsWith(p)) { d = d.substring( p.length() ); } dtname= d; return d; } public IndexSearcher getFinder() throws HongsException { init(); return finder; } public IndexReader getReader() throws HongsException { init(); return reader; } public IndexWriter getWriter() throws HongsException { open(); return writer; } /** * * @param rd * @return * @throws HongsException */ public Query getQuery(Map rd) throws HongsException { BooleanQuery.Builder query = new BooleanQuery.Builder(); Map<String, Map> fields = getFields( ); Set<String> filtCols = getFiltable(); Set<String> funcCols = getFuncKeys(); if (filtCols == null || filtCols.isEmpty()) { filtCols = fields.keySet(); } for (Object o : rd.entrySet()) { Map.Entry e = (Map.Entry) o; Object fv = e.getValue( ); String fn = (String) e.getKey(); if (fn == null || fv == null || funcCols.contains( fn ) || !filtCols.contains( fn )) { continue; } Map m = (Map ) fields.get( fn ); if (m == null) { continue; } IQuery aq; String t = getFtype(m); if ( "int".equals(t)) { aq = new IntQuery(); } else if ( "long".equals(t)) { aq = new LongQuery(); } else if ( "float".equals(t)) { aq = new FloatQuery(); } else if ("double".equals(t)) { aq = new DoubleQuery(); } else if ( "date".equals(t)) { aq = new LongQuery(); } else if ("string".equals(t)) { aq = new StringQuery(); } else if ("search".equals(t)) { aq = new SearchQuery(); } else { continue; } qryAdd(query, fn, fv, aq); } if (rd.containsKey(Cnst.WD_KEY)) { Object fv = rd.get (Cnst.WD_KEY); fv = Synt.asserts(fv, ""); Set<String> fs = getFindable( ); if (fv != null && !"".equals(fv)) { if (fs.size() > 1) { // : +(fn1:xxx fn2:xxx) Map fw = new HashMap( ); fw.put(Cnst.OR_REL , fv); BooleanQuery.Builder quary; quary = new BooleanQuery.Builder(); for(String fk: fs) { qryAdd(quary, fk, fw, new SearchQuery()); } query.add(quary.build(), BooleanClause.Occur.MUST); } else { for(String fk: fs) { qryAdd(query, fk, fv, new SearchQuery()); } } } } if (rd.containsKey(Cnst.OR_KEY)) { BooleanQuery.Builder quary = new BooleanQuery.Builder(); Set<Map> set = Synt.declare(rd.get(Cnst.OR_KEY), Set.class); for(Map map : set) { quary.add(getQuery(map), BooleanClause.Occur.SHOULD); } query.add(quary.build(), BooleanClause.Occur.MUST); } if (rd.containsKey(Cnst.SR_KEY)) { Set<Map> set = Synt.declare(rd.get(Cnst.SR_KEY), Set.class); for(Map map : set) { query.add(getQuery(map), BooleanClause.Occur.SHOULD); } } if (rd.containsKey(Cnst.AR_KEY)) { Set<Map> set = Synt.declare(rd.get(Cnst.AR_KEY), Set.class); for(Map map : set) { query.add(getQuery(map), BooleanClause.Occur.MUST); } } BooleanQuery quary = query.build(); if (quary.clauses( ).isEmpty( )) { return new MatchAllDocsQuery(); } return quary; } /** * * @param rd * @return * @throws HongsException */ public Sort getSort(Map rd) throws HongsException { Object xb = rd.get(Cnst.OB_KEY); Set<String> ob = xb != null ? Synt.asTerms ( xb ) : new LinkedHashSet(); Map<String, Map> fields = getFields(); List<SortField> of = new LinkedList(); for (String fn: ob) { if (fn.equals("-")) { of.add(SortField.FIELD_SCORE); continue; } if (fn.equals("_")) { of.add(SortField.FIELD_DOC); continue; } boolean rv = fn.startsWith("-"); if (rv) fn = fn.substring ( 1 ); if (sorted(of, fn, rv)) { continue; } Map m = (Map ) fields.get ( fn); if (m == null) { continue; } if (sortable(m)==false) { continue; } if (repeated(m)== true) { continue; } SortField.Type st; String t = getFtype(m); if ( "int".equals(t)) { st = SortField.Type.INT; } else if ( "long".equals(t)) { st = SortField.Type.LONG; } else if ( "float".equals(t)) { st = SortField.Type.FLOAT; } else if ("double".equals(t)) { st = SortField.Type.DOUBLE; } else if ("string".equals(t)) { st = SortField.Type.STRING; } else if ( "date".equals(t)) { st = SortField.Type.LONG; } else if ("sorted".equals(t)) { st = SortField.Type.LONG; } else { continue; } /** * Lucene 5 DocValues * , '.' */ of.add(new SortField("." + fn , st , rv)); } if (of.isEmpty()) { of.add(SortField.FIELD_DOC); } return new Sort(of.toArray(new SortField[0])); } /** * * @param rd */ public void setView(Map rd) { Object fz = rd.get(Cnst.RB_KEY); Set<String> fs = fz != null ? Synt.asTerms ( fz ) : new LinkedHashSet(); Map<String, Map> fields = getFields(); if (fs != null && !fs.isEmpty()) { Set<String> cf = new HashSet(); Set<String> sf = new HashSet(); for (String fn : fs) { if (fn.startsWith("-")) { fn= fn.substring(1); cf.add(fn); } else { sf.add(fn); } } if (!sf.isEmpty()) { cf.addAll(fields.keySet()); cf.removeAll(sf); } cf.add("@"); // Skip form conf; for(Map.Entry<String, Map> me : fields.entrySet()) { Map fc = me.getValue(); String f = me.getKey(); fc.put ( "--unwanted--" , cf.contains(f) || unstored(fc)); } } else { for(Map.Entry<String, Map> me : fields.entrySet()) { Map fc = me.getValue(); fc.remove( "--unwanted } } } / /** * * @return * @throws HongsException */ protected Analyzer getAnalyzer() throws HongsException { Map<String, Analyzer> az = new HashMap(); Map<String, Map> fields = getFields( ); Analyzer ad = new StandardAnalyzer(); for(Object ot : fields.entrySet( ) ) { Map.Entry et = (Map.Entry) ot; String fn = (String) et.getKey(); Map fc = (Map ) et.getValue(); String t = getFtype(fc); if ("search".equals(t)) { az.put(fn, getAnalyzer(fc, false)); } } return new PerFieldAnalyzerWrapper(ad, az); } /** * * @param fc * @param iq * @return * @throws HongsException */ protected Analyzer getAnalyzer(Map fc, boolean iq) throws HongsException { try { CustomAnalyzer.Builder cb = CustomAnalyzer.builder(); String kn, an, ac; Map oc; an = Synt.declare(fc.get("lucene-tokenizer"), ""); if (!"".equals(an)) { int p = an.indexOf('{'); if (p != -1) { ac = an.substring(p); an = an.substring(0, p - 1).trim( ); oc = Synt.declare(Data.toObject(ac), Map.class); cb.withTokenizer(an, oc); } else { cb.withTokenizer(an); } } else { cb.withTokenizer("Standard"); } for(Object ot2 : fc.entrySet()) { Map.Entry et2 = (Map.Entry) ot2; kn = (String) et2.getKey(); if (iq) { if (kn.startsWith("lucene-find-filter")) { an = (String) et2.getValue(); an = an.trim(); if ("".equals(an)) { continue; } int p = an.indexOf('{'); if (p != -1) { ac = an.substring(p); an = an.substring(0, p - 1).trim( ); oc = Synt.declare(Data.toObject(ac), Map.class); cb.addCharFilter(an, oc); } else { cb.addCharFilter(an); } } else if (kn.startsWith("lucene-query-filter")) { an = (String) et2.getValue(); an = an.trim(); if ("".equals(an)) { continue; } int p = an.indexOf('{'); if (p != -1) { ac = an.substring(p); an = an.substring(0, p - 1).trim( ); oc = Synt.declare(Data.toObject(ac), Map.class); cb.addTokenFilter(an, oc); } else { cb.addTokenFilter(an); } } } else { if (kn.startsWith("lucene-char-filter")) { an = (String) et2.getValue(); an = an.trim(); if ("".equals(an)) { continue; } int p = an.indexOf('{'); if (p != -1) { ac = an.substring(p); an = an.substring(0, p - 1).trim(); oc = Synt.declare(Data.toObject(ac), Map.class); cb.addCharFilter(an, oc); } else { cb.addCharFilter(an); } } else if (kn.startsWith("lucene-token-filter")) { an = (String) et2.getValue(); an = an.trim(); if ("".equals(an)) { continue; } int p = an.indexOf('{'); if (p != -1) { ac = an.substring(p); an = an.substring(0, p - 1).trim(); oc = Synt.declare(Data.toObject(ac), Map.class); cb.addTokenFilter(an, oc); } else { cb.addTokenFilter(an); } } } } return cb.build(); } catch ( IOException ex) { throw new HongsException.Common(ex); } catch ( IllegalArgumentException ex) { throw new HongsException.Common(ex); } } /** * * @param fc * @return */ protected SimpleDateFormat getFormat(Map fc) { String fm = Synt.asserts(fc.get( "format" ), ""); if ( "".equals(fm)) { fm = Synt.declare(fc.get("__type__"), "datetime"); fm = CoreLocale.getInstance() .getProperty("core.default."+ fm +".format"); if (fm == null) { fm = "yyyy/MM/dd HH:mm:ss"; } } SimpleDateFormat fd = new SimpleDateFormat(fm); fd.setTimeZone(Core.getTimezone()); return fd; } /** * * * int * long * float * double * search * string * object * date * @param fc * @return */ protected String getFtype(Map fc) { String t = Synt.declare(fc.get("lucene-fieldtype"), String.class); // lucene-fieldtype __type__ if (t == null) { t = (String) fc.get("__type__"); if ("textarea".equals(t)) { return "stored"; } if ("textcase".equals(t)) { return "search"; } if ("search".equals(t) || "stored".equals(t) || "sorted".equals(t)) { return t; } t = Synt.declare(getFtypes().get(t), t); if ( "enum" .equals(t) || "fork" .equals(t)) { return "string"; } if ( "form" .equals(t) || "json" .equals(t)) { return "object"; } if ("number".equals(t)) { t = Synt.declare(fc.get("type"), "double"); } } else if ("number".equals(t)) { t = "double"; } else if ( "text" .equals(t)) { t = "search"; } return t; } protected boolean sortable(Map fc) { return getSortable().contains(Synt.asserts(fc.get("__name__"), "")); } protected boolean filtable(Map fc) { return getFiltable().contains(Synt.asserts(fc.get("__name__"), "")); } protected boolean repeated(Map fc) { return Synt.asserts(fc.get("__repeated__"), false); } protected boolean unwanted(Map fc) { return Synt.asserts(fc.get("--unwanted--"), false); } protected boolean unstored(Map fc) { return Synt.asserts(fc.get( "unstored" ), false); } protected boolean ignored (Map fc, String k) { return "".equals( k) || "@".equals( k) || "Ignore".equals(fc.get( "rule" )); } protected boolean sorted (List<SortField> sf, String k, boolean r) { return false; } protected void mapAdd(Map map, Document doc) { Map<String, Map> fields = getFields( ); for(Object o : fields.entrySet()) { Map.Entry e = (Map.Entry) o; Map m = (Map) e.getValue(); String k = (String)e.getKey(); if (unwanted(m) || unstored(m) || ignored (m, k)) { continue; } IValue v ; Object u ; String t = getFtype(m); boolean r = repeated(m); IndexableField[] fs = doc.getFields(k); if ("sorted".equals(t)) { continue; } else if ( "date".equals(t)) { // Date 1000 String typ = Synt.asserts(m.get("type"), ""); int mul = "datestamp".equals( typ ) || "timestamp".equals( typ ) ? 1000 : 1; if (OBJECT_MODE) { if ("time".equals(typ) || "timestamp".equals(typ)) { v = new NumberValue(); u = 0 ; } else { v = new DatimeValue(); u = null; ((DatimeValue) v).mul = mul; } } else { if ("time".equals(typ) || "timestamp".equals(typ)) { v = new NumStrValue(); u = "0" ; } else { v = new DatStrValue(); u = "" ; ((DatStrValue) v).mul = mul; ((DatStrValue) v).sdf = getFormat(m); } } } else if ( "int".equals(t) || "long".equals(t) || "float".equals(t) || "double".equals(t) || "number".equals(t)) { if (OBJECT_MODE) { v = new NumberValue(); u = 0 ; } else { v = new NumStrValue(); u = "0"; } } else if ("object".equals(t)) { v = new ObjectValue(); u = new HashMap( ); } else { v = new StringValue(); u = ""; } if (r) { if (fs.length > 0) { for(IndexableField f : fs ) { Dict.put(map , v.get(f), k, null); } } else { map.put(k , new ArrayList()); } } else { if (fs.length > 0) { map.put(k , v.get( fs[0] ) ); } else { map.put(k , u); } } } } protected void docAdd(Document doc, Map map) { Map<String, Map> fields = getFields(); for(Object o : fields.entrySet()) { Map.Entry e = (Map.Entry) o; Map m = (Map) e.getValue(); String k = (String)e.getKey(); Object v = Dict.getParam(map , k); if (null == v || ignored(m , k)) { continue; } IField f ; String t = getFtype(m); boolean s = sortable(m); boolean q = filtable(m); boolean u = unstored(m); boolean r = repeated(m); boolean g = true; // , , !unstored if ( "date".equals (t)) { t = "long"; } if ("sorted".equals (t)) { t = "long"; s = true ; u = true ; } if ( "int".equals (t)) { f = new IntField( ); g = !u; } else if ( "long".equals (t)) { f = new LongField(); g = !u; } else if ( "float".equals (t)) { f = new FloatField(); g = !u; } else if ("double".equals (t)) { f = new DoubleField(); g = !u; } else if ("string".equals (t)) { f = new StringFiald(); q = false; } else if ("search".equals (t)) { f = new SearchFiald(); q = false; s = false; } else if ("object".equals (t)) { f = new ObjectFiald(); q = false; s = false; } else { f = new StoredFiald(); q = false; s = false; } doc.removeFields(k); if (r) { if (g) { if (v instanceof Object[ ] ) { for (Object w: (Object[ ] ) v) { doc.add(f.get(k, w, u)); } } else if (v instanceof Collection) { for (Object w: (Collection) v) { doc.add(f.get(k, w, u)); } } else { Set a = Synt.declare(v, Set.class); for (Object w: a) { doc.add(f.get(k, w, u)); } v = a; } } Set a = Synt.declare(v, Set.class); if (q && a != null && !a.isEmpty()) { for (Object w: a) { doc.add(f.got(k, w)); } } if (s && a != null && !a.isEmpty()) { for (Object w: a) { doc.add(f.srt(k, w)); } } } else { doc.add(f.get( k, v, u)); if (q) { doc.add(f.got(k, v)); } if (s) { doc.add(f.srt(k, v)); } } } } /** * * * : * !eq * !ne * !lt * !le * !gt * !ge * !rg * !in * !ni * Lucene : * !or , * !oi , * !ai , * !wt , * : , * * @param qry * @param k * @param v * @param q * @throws HongsException */ protected void qryAdd(BooleanQuery.Builder qry, String k, Object v, IQuery q) throws HongsException { Map m; if (v instanceof Map) { m = new HashMap(); m.putAll((Map) v); } else { if (null==v || "".equals(v)) { return ; } m = new HashMap(); if (v instanceof Collection) { Collection c = (Collection) v; c.remove(""); if (c.isEmpty()) { return; } m.put(Cnst.IN_REL, c); } else { m.put(Cnst.EQ_REL, v); } } // text if (q instanceof SearchQuery) { Map<String, Map> fields = getFields( ); Map fc = ( Map ) fields.get(k); SearchQuery sq = ( SearchQuery ) q; sq.analyzer(getAnalyzer(fc,true) ); sq.phraseSlop (Synt.declare(fc.get("lucene-parser-phraseSlop" ), Integer.class)); sq.fuzzyPreLen(Synt.declare(fc.get("lucene-parser-fuzzyPreLen"), Integer.class)); sq.fuzzyMinSim(Synt.declare(fc.get("lucene-parser-fuzzyMinSim"), Float.class)); sq.advanceAnalysisInUse(Synt.declare(fc.get("lucene-parser-advanceAnalysisInUse"), Boolean.class)); sq.defaultOperatorIsAnd(Synt.declare(fc.get("lucene-parser-defaultOperatorIsAnd"), Boolean.class)); sq.allowLeadingWildcard(Synt.declare(fc.get("lucene-parser-allowLeadingWildcard"), Boolean.class)); sq.lowercaseExpandedTerms(Synt.declare(fc.get("lucene-parser-lowercaseExpandedTerms"), Boolean.class)); sq.enablePositionIncrements(Synt.declare(fc.get("lucene-parser-enablePositionIncrements"), Boolean.class)); } float bst = 1F; BooleanQuery.Builder src = null; if (m.containsKey(Cnst.WT_REL)) { Object n = m.remove(Cnst.WT_REL); bst = Synt.declare (n , 1F); src = qry; qry = new BooleanQuery.Builder(); } if (m.containsKey(Cnst.EQ_REL)) { Object n = m.remove(Cnst.EQ_REL); qry.add(q.get(k, n), BooleanClause.Occur.MUST); } if (m.containsKey(Cnst.NE_REL)) { Object n = m.remove(Cnst.NE_REL); qry.add(q.get(k, n), BooleanClause.Occur.MUST_NOT); } if (m.containsKey(Cnst.OR_REL)) { Object n = m.remove(Cnst.OR_REL); qry.add(q.get(k, n), BooleanClause.Occur.SHOULD); } if (m.containsKey(Cnst.IN_REL)) { BooleanQuery.Builder qay = new BooleanQuery.Builder(); Set a = Synt.declare(m.remove(Cnst.IN_REL), new HashSet()); for(Object x : a) { qay.add(q.get(k, x), BooleanClause.Occur.SHOULD); } qry.add(qay.build(), BooleanClause.Occur.MUST); } if (m.containsKey(Cnst.AI_REL)) { // All In Set a = Synt.declare(m.remove(Cnst.AI_REL), new HashSet()); for(Object x : a) { qry.add(q.get(k, x), BooleanClause.Occur.MUST); } } if (m.containsKey(Cnst.NI_REL)) { // Not In Set a = Synt.declare(m.remove(Cnst.NI_REL), new HashSet()); for(Object x : a) { qry.add(q.get(k, x), BooleanClause.Occur.MUST_NOT); } } if (m.containsKey(Cnst.OI_REL)) { // Or In Set a = Synt.declare(m.remove(Cnst.OI_REL), new HashSet()); for(Object x : a) { qry.add(q.get(k, x), BooleanClause.Occur.SHOULD); } } / Object n, x; boolean l, g; if (m.containsKey(Cnst.RG_REL)) { Object[] a = Synt.asRange(m.remove(Cnst.RG_REL)); if (null != a) { n = a[0]; l = (boolean) a[2]; x = a[1]; g = (boolean) a[3]; } else { n = null; l = false; x = null; g = false; } } else { if (m.containsKey(Cnst.GE_REL)) { n = m.remove (Cnst.GE_REL); l = true ; } else if (m.containsKey(Cnst.GT_REL)) { n = m.remove (Cnst.GT_REL); l = false; } else { n = null; l = false; } if (m.containsKey(Cnst.LE_REL)) { x = m.remove (Cnst.LE_REL); g = true ; } else if (m.containsKey(Cnst.LT_REL)) { x = m.remove (Cnst.LT_REL); g = false; } else { x = null; g = false; } } if (n != null || x != null) { qry.add(q.get(k, n, x, l, g), BooleanClause.Occur.MUST); } / if (!m.isEmpty()) { Set s = new HashSet(); s.addAll(m.values( )); qryAdd(qry, k, s, q ); } / if (src != null ) { BooleanQuery qay = qry.build(); if (qay.clauses().size() > 0 ) { src.add(new BoostQuery(qay, bst), BooleanClause.Occur.MUST); } } } / public static class Loop implements Iterable<Map>, Iterator<Map> { private final IndexSearcher finder; private final IndexReader reader; private final LuceneRecord that; private ScoreDoc[] docs; private ScoreDoc doc ; private final Query q; private final Sort s; private final int b; private final int l; private int L; private int h; private int H; private int i; private boolean A; /** * * @param that * @param q * @param s * @param b * @param l */ public Loop(LuceneRecord that, Query q, Sort s, int b, int l) { this.that = that; this.docs = null; this.doc = null; this.q = q; this.s = s; this.b = b; if ( l == 0) { l = 1000; A = true; } this.l = l; this.L = l; if ( b != 0) { L += b; } try { finder = that.getFinder(); reader = that.getReader(); } catch ( HongsException ex ) { throw ex.toExpedient( ); } } @Override public Iterator<Map> iterator() { return this; } @Override public boolean hasNext() { try { if ( docs == null) { TopDocs tops; if (s != null) { tops = finder.search(q, L, s); } else { tops = finder.search(q, L); } docs = tops.scoreDocs; h = docs.length; i = b; H = h; L = l; } else if ( A && L <= i ) { TopDocs tops; if (s != null) { tops = finder.searchAfter(doc, q, l, s); } else { tops = finder.searchAfter(doc, q, l); } docs = tops.scoreDocs; h = docs.length; i = 0; H += h; } return i < h; } catch (IOException ex) { throw new HongsExpedient.Common(ex); } } @Override public Map next() { if ( i >= h ) { throw new NullPointerException("hasNext not run?"); } try { /*Read*/ doc = docs[i++]; Document dox = reader.document( doc.doc ); return that.doc2Map(dox); } catch (IOException ex) { throw new HongsExpedient.Common(ex); } } /** * * : * l 0 () * * * * @return */ public int size() { hasNext(); return H ; } /** * @deprecated */ @Override public void remove() { throw new UnsupportedOperationException("Not supported remove in lucene loop."); } @Override public String toString() { hasNext(); StringBuilder sb = new StringBuilder(q.toString()); if ( s != null ) { sb.append( " Sort: "); sb.append( s ); } if ( l != 0 || b != 0 ) { sb.append(" Limit: "); sb.append( b ); sb.append(","); sb.append( l ); } return sb.toString(); } } }
package gr.watchful.permchecker.panels; import gr.watchful.permchecker.datastructures.Mod; import java.awt.Dimension; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.JTextField; @SuppressWarnings("serial") public class ModEditor extends JPanel { private JTextField name; private JTextField author; private JTextField link; private JTextField imageLink; private JTextField permissionLink; public ModEditor(Dimension size) { this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); name = new JTextField("TEST"); this.add(name); author = new JTextField("TEST"); this.add(author); link = new JTextField("TEST"); this.add(link); imageLink = new JTextField("TEST"); this.add(imageLink); permissionLink = new JTextField("TEST"); this.add(permissionLink); } public void setMod(Mod mod) { } }
package functionalTests; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import org.apache.log4j.Logger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.objectweb.proactive.core.config.PAProperties; import org.objectweb.proactive.core.util.OperatingSystem; public class FunctionalTest { static final protected Logger logger = Logger.getLogger("testsuite"); static final public String JVM_PARAMETERS = "-Dproactive.test=true"; /** The amount of time given to a test to success or fail */ static final private long TIMEOUT = 300000; /** A shutdown hook to kill all forked JVMs when exiting the main JVM */ static final private Thread shutdownHook = new Thread() { @Override public void run() { logger.trace("FunctionalTest Shutdown Hook"); killProActive(); } }; @BeforeClass public static void beforeClass() { logger.trace("beforeClass"); logger.trace("Killing remaining ProActive Runtime"); killProActive(); try { Runtime.getRuntime().addShutdownHook(shutdownHook); } catch (IllegalArgumentException e) { logger.trace("shutdownHook already registered"); } long timeout = TIMEOUT; String ptt = System.getProperty("proactive.test.timeout"); if (ptt != null) { timeout = Long.parseLong(ptt); } if (timeout != 0) { logger.trace("Timer will be fired in " + timeout + " ms"); TimerTask timerTask = new TimerTask() { @Override public void run() { // 1- Advertise the failure logger.warn("FunctionalTest timeout reached !"); // 2- Display jstack output // It can be useful to debug (live|dead)lock Map<String, String> pids = getPids(); for (String pid : pids.keySet()) { System.err.println("PID: " + pid + " Command: " + pids.get(pid)); System.err.println(); try { Process p = Runtime.getRuntime() .exec(getJSTACKCommand() + " " + pid); BufferedReader br = new BufferedReader(new InputStreamReader( p.getInputStream())); for (String line = br.readLine(); line != null; line = br.readLine()) { System.err.println("\t" + line); } System.err.println(); System.err.println( " System.err.println(); System.err.println(); System.err.flush(); } catch (IOException e) { // Should not happen e.printStackTrace(); } } // 3- That's all // Shutdown hook will be triggered to kill all remaining ProActive Runtimes System.exit(0); } }; Timer timer = new Timer(true); timer.schedule(timerTask, timeout); } else { logger.trace("Timeout disabled"); } } @AfterClass public static void afterClass() { logger.trace("afterClass"); logger.trace("Removing the shutdownHook"); Runtime.getRuntime().removeShutdownHook(shutdownHook); logger.trace("Killing remaining ProActive Runtime"); killProActive(); } static private void killProActiveWithJPS() throws IOException { String javaHome = System.getProperty("java.home"); File jpsBin = null; switch (OperatingSystem.getOperatingSystem()) { case unix: jpsBin = new File(javaHome + File.separator + ".." + File.separator + "bin" + File.separator + "jps"); break; case windows: jpsBin = new File(javaHome + File.separator + ".." + File.separator + "bin" + File.separator + "jps.exe"); break; } if (!jpsBin.exists()) { throw new FileNotFoundException("JPS not found: " + jpsBin.toString()); } Process jps; jps = Runtime.getRuntime() .exec(new String[] { jpsBin.toString(), "-mlv" }, null, null); Reader reader = new InputStreamReader(jps.getInputStream()); BufferedReader bReader = new BufferedReader(reader); String line = bReader.readLine(); while (line != null) { if (line.matches(".*proactive.test=true.*") || line.matches(".*StartP2PService.*")) { logger.debug("MATCH " + line); String pid = line.substring(0, line.indexOf(" ")); Process kill = null; switch (OperatingSystem.getOperatingSystem()) { case unix: kill = Runtime.getRuntime() .exec(new String[] { "kill", "-9", pid }); break; case windows: kill = Runtime.getRuntime() .exec(new String[] { "taskkill", "/PID", pid }); break; default: logger.info("Unsupported operating system"); break; } try { kill.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } else { logger.debug("NO MATCH " + line); } line = bReader.readLine(); } } static private void killProActiveWithScript() throws Exception { File dir = new File(PAProperties.PA_HOME.getValue()); File command = null; switch (OperatingSystem.getOperatingSystem()) { case unix: command = new File(dir + File.separator + "dev" + File.separator + "scripts" + File.separator + "killTests"); break; default: break; } if (command != null) { if (command.exists()) { try { Runtime.getRuntime() .exec(new String[] { command.getAbsolutePath(), null, dir.toString() }); } catch (Exception e) { logger.warn(e); } } else { throw new IOException(command + " does not exist"); } } else { throw new Exception(command + " not defined for" + OperatingSystem.getOperatingSystem().toString()); } } /** * Kill all ProActive runtimes */ public static void killProActive() { try { killProActiveWithJPS(); } catch (Exception jpsException) { logger.warn("JPS kill failed: " + jpsException.getMessage()); try { killProActiveWithScript(); } catch (Exception scriptException) { logger.warn("Script kill failed: " + scriptException.getMessage()); } } } /** * Returns a map<PID, CommandLine> of ProActive JVMs * @return */ static public Map<String, String> getPids() { HashMap<String, String> pids = new HashMap<String, String>(); try { // Run JPS to list all JVMs on this machine Process p = Runtime.getRuntime().exec(getJPSCommand() + " -ml"); BufferedReader br = new BufferedReader(new InputStreamReader( p.getInputStream())); for (String line = br.readLine(); line != null; line = br.readLine()) { // Discard all non ProActive JVM if (line.contains("org.objectweb.proactive")) { String[] fields = line.split(" ", 2); pids.put(fields[0], fields[1]); } } } catch (IOException e) { // Should not happen e.printStackTrace(); } return pids; } /** * Returns the command to start the jps util * * @return command to start jps */ static public String getJPSCommand() { return getJavaBinDir() + "jps"; } /** * Returns the command to start the jstack util * * @return command to start jstack */ static public String getJSTACKCommand() { return getJavaBinDir() + "jstack"; } /** * Returns the Java bin dir * * @return Java bin/ dir */ static public String getJavaBinDir() { StringBuilder sb = new StringBuilder(); sb.append(System.getProperty("java.home")); sb.append(File.separatorChar); sb.append(".."); sb.append(File.separatorChar); sb.append("bin"); sb.append(File.separatorChar); return sb.toString(); } }
package prodoc; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Vector; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.config.ConnectionConfig; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * This class implements a remote conection to a Prodoc Server * @author jhierrot */ public class DriverRemote extends DriverGeneric { //URL OUrl=null; //URLConnection OUrlc=null; //HttpURLConnection URLCon=null; static private PoolingHttpClientConnectionManager cm=null; private CloseableHttpClient httpclient; private HttpContext context; private HttpPost UrlPost; static final String charset="UTF-8"; OutputStreamWriter output; //private static final String NEWLINE = "\r\n"; public static final String ORDER="Order"; public static final String PARAM="Param"; boolean Conected=false; StringBuilder Answer=new StringBuilder(3000); //private List<String> cookies =null; //private String SessionID =null; final SimpleDateFormat formatterTS = new SimpleDateFormat("yyyyMMddHHmmss"); final SimpleDateFormat formatterDate = new SimpleDateFormat("yyyyMMdd"); DocumentBuilder DB=null; /** * * @param pURL * @param pPARAM * @param pUser * @param pPassword * @throws prodoc.PDException */ public DriverRemote(String pURL, String pPARAM, String pUser, String pPassword) throws PDException { super(pURL, pPARAM, pUser, pPassword); if (PDLog.isDebug()) PDLog.Debug("DriverRemote.DriverRemote>:"+pURL+"/"+pUser+"/"+pPARAM); try { if (pURL==null || pURL.length()<4) PDException.GenPDException("DATA_URL empty or wrong.",pURL); httpclient=GetHttpClient(); UrlPost = new HttpPost(pURL); context = new BasicHttpContext(); DB = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (Exception ex) { PDException.GenPDException("Error_connecting_trough_URL"+pURL,ex.getLocalizedMessage()); } if (PDLog.isDebug()) PDLog.Debug("DriverRemote.DriverRemote<"); } /** * Logged user acording his authenticator * @param userName * @param Password * @throws PDException */ @Override void Assign(String userName, String Password) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.Assign>:"+userName); ReadWrite(S_LOGIN,"<OPD><U>"+userName+"</U><C>"+Password+"</C></OPD>"); Conected=true; getUser().LoadAll(userName); getPDCust().Load(getUser().getCustom()); setAppLang(getPDCust().getLanguage()); if (PDLog.isDebug()) PDLog.Debug("DriverRemote.Assign<:"+userName); } /** * Disconects freeing all resources * @throws PDException */ public void delete() throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.delete>:"+getURL()); try { httpclient.close(); httpclient=null; Conected=false; } catch (Exception ex) { PDException.GenPDException("Error_closing_remote_connection",ex.getLocalizedMessage()); } if (PDLog.isDebug()) PDLog.Debug("DriverRemote.delete<:"+getURL()); } /** * Verify if the conection with the repository is ok * @return true if the connection is valid */ public boolean isConnected() { return (Conected); } /** * Create a table * @param TableName * @param Fields * @throws PDException */ @Override protected void CreateTable(String TableName, Record Fields) throws PDException { if (PDLog.isInfo()) PDLog.Info("DriverRemote.CreateTable>:"+TableName+"/"+Fields); ReadWrite(S_CREATE, "<OPD><Tab>"+TableName+"</Tab>"+Fields.toXMLt()+"</OPD>"); if (PDLog.isDebug()) PDLog.Debug("DriverRemote.CreateTable<:"+TableName); } /** * Drops a table * @param TableName * @throws PDException */ @Override protected void DropTable(String TableName) throws PDException { if (PDLog.isInfo()) PDLog.Info("DriverRemote.DropTable>:"+TableName); ReadWrite(S_DROP, "<OPD><Tab>"+TableName+"</Tab></OPD>"); if (PDLog.isDebug()) PDLog.Debug("DriverRemote.DropTable<:"+TableName); } /** * Modifies a table adding a field * @param TableName * @param NewAttr New field to add * @param IsVer * @throws PDException */ @Override protected void AlterTableAdd(String TableName, Attribute NewAttr, boolean IsVer) throws PDException { if (PDLog.isInfo()) PDLog.Info("DriverRemote.AlterTable>:"+TableName); ReadWrite(S_ALTER, "<OPD><Tab>"+TableName+"</Tab>"+NewAttr.toXMLFull()+"<IsVer>"+(IsVer?"1":"0")+"</IsVer></OPD>"); if (PDLog.isInfo()) PDLog.Info("DriverRemote.AlterTable<:"+TableName); } /** * Modifies a table deleting a field * @param TableName * @param OldAttr old field to delete * @throws PDException */ @Override protected void AlterTableDel(String TableName, String OldAttr) throws PDException { if (PDLog.isInfo()) PDLog.Info("DriverRemote.AlterTable>:"+TableName); ReadWrite(S_ALTERDEL, "<OPD><Tab>"+TableName+"</Tab><OldAttr>"+OldAttr+"</OldAttr></OPD>"); if (PDLog.isInfo()) PDLog.Info("DriverRemote.AlterTable<:"+TableName); } /** * Inserts a record/row * @param TableName * @param Fields * @throws PDException */ @Override protected void InsertRecord(String TableName, Record Fields) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.InsertRecord>:"+TableName+"="+Fields); ReadWrite(S_INSERT, "<OPD><Tab>"+TableName+"</Tab>"+Fields.toXMLtNotNull()+"</OPD>"); if (PDLog.isDebug()) PDLog.Debug("DriverRemote.InsertRecord<"); } /** * Deletes SEVERAL records acording conditions * @param TableName * @param DelConds * @throws PDException */ @Override protected void DeleteRecord(String TableName, Conditions DelConds) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.DeleteRecord>:"+TableName); ReadWrite(S_DELETE, "<OPD><Tab>"+TableName+"</Tab><DelConds>"+DelConds.toXML()+"</DelConds></OPD>"); if (PDLog.isDebug()) PDLog.Debug("DriverRemote.DeleteRecord<"); } /** * Update SEVERAL records acording conditions * @param TableName * @param NewFields * @param UpConds * @throws PDException */ @Override protected void UpdateRecord(String TableName, Record NewFields, Conditions UpConds) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.UpdateRecord>:"+TableName+"="+NewFields); ReadWrite(S_UPDATE, "<OPD><Tab>"+TableName+"</Tab>"+NewFields.toXMLt()+"<UpConds>"+UpConds.toXML()+"</UpConds></OPD>"); // ReadWrite(S_UPDATE, "<OPD><Tab>"+TableName+"</Tab>"+NewFields.toXMLtNotNull()+"<UpConds>"+UpConds.toXML()+"</UpConds></OPD>"); if (PDLog.isDebug()) PDLog.Debug("DriverRemote.UpdateRecord<:"+TableName+"="+NewFields); } /** * Add referential integrity between two tables and one field each * @param TableName1 * @param Field1 * @param TableName2 * @param Field2 * @throws PDException */ @Override protected void AddIntegrity(String TableName1, String Field1, String TableName2, String Field2) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.AddIntegrity>:"+TableName1+","+Field1+"/"+TableName2+","+Field2); ReadWrite(S_INTEGRIT, "<OPD><Tab1>"+TableName1+"</Tab1><Field1>"+Field1+"</Field1><Tab2>"+TableName2+"</Tab2><Field2>"+Field2+"</Field2></OPD>"); if (PDLog.isDebug()) PDLog.Debug("DriverRemote.AddIntegrity<"); } /** * Add referential integrity between two tables and 2 fields each * @param TableName1 * @param Field11 * @param Field12 * @param TableName2 * @param Field21 * @param Field22 * @throws PDException */ @Override protected void AddIntegrity(String TableName1, String Field11, String Field12, String TableName2, String Field21, String Field22) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.AddIntegrity2>:"+TableName1+","+Field11+","+Field12+"/"+TableName2+","+Field12+","+Field22); ReadWrite(S_INTEGRIT2, "<OPD><Tab1>"+TableName1+"</Tab1><Field11>"+Field11+"</Field11><Field12>"+Field12+"</Field12><Tab2>"+TableName2+"</Tab2><Field21>"+Field21+"</Field21><Field22>"+Field22+"</Field22></OPD>"); if (PDLog.isDebug()) PDLog.Debug("DriverRemote.AddIntegrity2<"); } /** * Starts a Transaction * @throws PDException */ @Override public void IniciarTrans() throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.InitTrans"); try { ReadWrite(S_INITTRANS, "<OPD></OPD>"); } catch (Exception ex) { PDException.GenPDException("Error_starting_transaction",ex.getLocalizedMessage()); } setInTransaction(true); } /** * Ends a transaction * @throws PDException */ @Override public void CerrarTrans() throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.CommitTrans"); try { ReadWrite(S_COMMIT, "<OPD></OPD>"); setInTransaction(false); } catch (Exception ex) { PDException.GenPDException("Error_closing_transaction",ex.getLocalizedMessage()); } } /** * Aborts a Transaction * @throws PDException */ @Override public void AnularTrans() throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.CancelTrans"); try { ReadWrite(S_CANCEL, "<OPD></OPD>"); setInTransaction(false); } catch (Exception ex) { PDException.GenPDException("Error_canceling_transaction",ex.getLocalizedMessage()); } } /** * Opens a cursor * @param Search * @return String identifier of the cursor * @throws PDException */ @Override public Cursor OpenCursor(Query Search) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.OpenCursor:"+Search); Cursor C=new Cursor(); Node N=ReadWrite(S_SELECT, "<OPD><Query>"+Search.toXML()+"</Query></OPD>"); Vector Res=new Vector(); NodeList RecLst = N.getChildNodes(); for (int i = 0; i < RecLst.getLength(); i++) { Node Rec = RecLst.item(i); Record R; R=Record.CreateFromXML(Rec); R.initList(); for (int j = 0; j < R.NumAttr(); j++) { Attribute Attr=R.nextAttr(); if (Attr.getName().contains("."+PDDocs.fVERSION)) Attr.setName(PDDocs.fVERSION); else if (Attr.getName().contains("."+PDDocs.fPDID)) Attr.setName(PDDocs.fPDID); } Res.add(R); } Record RF=Search.getRetrieveFields(); RF.initList(); for (int j = 0; j < RF.NumAttr(); j++) { Attribute Attr=RF.nextAttr(); if (Attr.getName().contains("."+PDDocs.fVERSION)) Attr.setName(PDDocs.fVERSION); else if (Attr.getName().contains("."+PDDocs.fPDID)) Attr.setName(PDDocs.fPDID); } return(StoreCursor(Res, RF)); } /** * Close a Cursor * @param CursorIdent * @throws PDException */ @Override public void CloseCursor(Cursor CursorIdent) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.CloseCursor:"+CursorIdent); if (CursorIdent.getResultSet()!=null) ((Vector)CursorIdent.getResultSet()).clear(); CursorIdent.setResultSet(null); delCursor(CursorIdent); } /** * Retrieves next record of cursor * @param CursorIdent * @return OPD next Record * @throws PDException */ @Override public Record NextRec(Cursor CursorIdent) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.NextRec:"+CursorIdent); Vector rs=(Vector)CursorIdent.getResultSet(); if (rs.isEmpty()) return(null); Record Fields=CursorIdent.getFieldsCur(); Fields.assignSimil((Record)rs.get(0)); // description and other elemens from atribute not transmitted by performance rs.remove(0); return(Fields.Copy()); } /** * Communicates to the OpenProdoc Server by http sending instructionss * @param pOrder Order to execute * @param pParam Parameters of the order (can be empty or null depending on order * @return an xml node extracted form XML answer. * @throws PDException in any error */ private Node ReadWrite(String pOrder, String pParam) throws PDException { Node OPDObject=null; CloseableHttpResponse response2 = null; if (PDLog.isDebug()) { PDLog.Debug("DriverRemote. ReadWrite: Order:"+pOrder); if (!pOrder.equals(S_LOGIN)) PDLog.Debug("Param:"+pParam); else PDLog.Debug("Param:"+pParam.substring(0, 18)); } try { List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair(ORDER, pOrder)); nvps.add(new BasicNameValuePair(PARAM, pParam)); UrlPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); response2 = httpclient.execute(UrlPost, context); HttpEntity Resp=response2.getEntity(); Document XMLObjects = DB.parse(Resp.getContent()); NodeList OPDObjectList = XMLObjects.getElementsByTagName("Result"); OPDObject = OPDObjectList.item(0); if (OPDObject.getTextContent().equalsIgnoreCase("KO")) { OPDObjectList = XMLObjects.getElementsByTagName("Msg"); if (OPDObjectList.getLength()>0) { OPDObject = OPDObjectList.item(0); PDException.GenPDException("Server_Error", DriverGeneric.DeCodif(OPDObject.getTextContent())); } else PDException.GenPDException("Server_Error", ""); } OPDObjectList = XMLObjects.getElementsByTagName("Data"); OPDObject = OPDObjectList.item(0); } catch (Exception ex) { PDException.GenPDException(ex.getLocalizedMessage(), ""); } finally { if (response2!=null) try { response2.close(); } catch (IOException ex) { PDException.GenPDException(ex.getLocalizedMessage(), ""); } } DB.reset(); return(OPDObject); } /** * Allows to decide how to download file * @return true ir Driver is remote */ protected boolean IsRemote() { return(true); } /** * * @param RepName * @return * @throws PDException */ protected StoreGeneric getRepository(String RepName) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.getRepository>:"+RepName); PDRepository RepDesc=new PDRepository(this); RepDesc.Load(RepName); StoreGeneric Rep=new StoreRem(RepDesc.getURL(), RepDesc.getUser(), RepDesc.getPassword(), RepDesc.getParam(), RepDesc.isEncrypted(), UrlPost, httpclient, context, DB ); return(Rep); } /** * * @throws PDException */ void Logout() throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.Logout"); try { ReadWrite(S_LOGOUT, "<OPD></OPD>"); } catch (Exception ex) { PDException.GenPDException("Error_in_Logout",ex.getLocalizedMessage()); } } @Override public void UnLock() { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.UnLock"); try { ReadWrite(S_UNLOCK, "<OPD></OPD>"); super.UnLock(); } catch (Exception ex) { PDLog.Error(ex.getLocalizedMessage()); } } private CloseableHttpClient GetHttpClient() { //CloseableHttpClient httpclient = HttpClients.custom() // .setConnectionManager(GenPool()) // .build(); CloseableHttpClient httpclient = HttpClients.createDefault(); return(httpclient); } static synchronized private PoolingHttpClientConnectionManager GenPool() { if (cm==null) { cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(100); ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build(); cm.setDefaultConnectionConfig(connectionConfig); } return(cm); } /** * Returns an object of type Fulltext indexer * if the repository is yet constructed, returns the constructed one * @return object of type repository * @throws PDException in any error */ @Override protected FTConnector getFTRepository(String pDocType) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.getFTRepository>"); if (FTConn!=null) { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.Rep yet Instantiated"); return (FTConn); } if (PDLog.isDebug()) PDLog.Debug("DriverRemote.Rep new Instance"); PDRepository RepDesc=new PDRepository(this); RepDesc.Load("PD_FTRep"); FTConn=new FTRemote(RepDesc.getURL(), RepDesc.getUser(), RepDesc.getPassword(), RepDesc.getParam(), UrlPost, httpclient, context, DB ); if (PDLog.isDebug()) PDLog.Debug("DriverRemote.getFTRepository<"); return(FTConn); } }
package info.ephyra; import info.ephyra.answerselection.AnswerSelection; import info.ephyra.answerselection.filters.AnswerPatternFilter; import info.ephyra.answerselection.filters.AnswerTypeFilter; import info.ephyra.answerselection.filters.DuplicateFilter; import info.ephyra.answerselection.filters.FactoidSubsetFilter; import info.ephyra.answerselection.filters.FactoidsFromPredicatesFilter; import info.ephyra.answerselection.filters.PredicateExtractionFilter; import info.ephyra.answerselection.filters.QuestionKeywordsFilter; import info.ephyra.answerselection.filters.ScoreCombinationFilter; import info.ephyra.answerselection.filters.ScoreNormalizationFilter; import info.ephyra.answerselection.filters.ScoreSorterFilter; import info.ephyra.answerselection.filters.StopwordFilter; import info.ephyra.answerselection.filters.TruncationFilter; import info.ephyra.answerselection.filters.WebDocumentFetcherFilter; import info.ephyra.io.Logger; import info.ephyra.io.MsgPrinter; import info.ephyra.nlp.LingPipe; import info.ephyra.nlp.NETagger; import info.ephyra.nlp.OpenNLP; import info.ephyra.nlp.SnowballStemmer; import info.ephyra.nlp.StanfordNeTagger; import info.ephyra.nlp.StanfordParser; import info.ephyra.nlp.indices.FunctionWords; import info.ephyra.nlp.indices.IrregularVerbs; import info.ephyra.nlp.indices.Prepositions; import info.ephyra.nlp.indices.WordFrequencies; import info.ephyra.nlp.semantics.ontologies.Ontology; import info.ephyra.nlp.semantics.ontologies.WordNet; import info.ephyra.querygeneration.Query; import info.ephyra.querygeneration.QueryGeneration; import info.ephyra.querygeneration.generators.BagOfTermsG; import info.ephyra.querygeneration.generators.BagOfWordsG; import info.ephyra.querygeneration.generators.PredicateG; import info.ephyra.querygeneration.generators.QuestionInterpretationG; import info.ephyra.querygeneration.generators.QuestionReformulationG; import info.ephyra.questionanalysis.AnalyzedQuestion; import info.ephyra.questionanalysis.QuestionAnalysis; import info.ephyra.questionanalysis.QuestionInterpreter; import info.ephyra.questionanalysis.QuestionNormalizer; import info.ephyra.search.Result; import info.ephyra.search.Search; import info.ephyra.search.searchers.IndriKM; import info.ephyra.search.searchers.IndriDocumentKM; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.thread.QueuedThreadPool; import java.net.URLDecoder; import java.io.PrintWriter; import java.io.IOException; import java.util.ArrayList; /** * <code>OpenEphyra</code> is an open framework for question answering (QA). * * @author Nico Schlaefer * @version 2008-03-23 */ public class OpenEphyraServer extends AbstractHandler { /** Factoid question type. */ protected static final String FACTOID = "FACTOID"; /** List question type. */ protected static final String LIST = "LIST"; /** Maximum number of factoid answers. */ protected static final int FACTOID_MAX_ANSWERS = 1; /** Absolute threshold for factoid answer scores. */ protected static final float FACTOID_ABS_THRESH = 0; /** Relative threshold for list answer scores (fraction of top score). */ protected static final float LIST_REL_THRESH = 0.1f; /** Serialized classifier for score normalization. */ public static final String NORMALIZER = "res/scorenormalization/classifiers/" + "AdaBoost70_" + "Score+Extractors_" + "TREC10+TREC11+TREC12+TREC13+TREC14+TREC15+TREC8+TREC9" + ".serialized"; /** The directory of Ephyra, required when Ephyra is used as an API. */ protected String dir; @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String query_str = request.getQueryString(); System.out.println("Query str: " + query_str); if (query_str == null) { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); return; } String[] tokens = query_str.split("="); String question = URLDecoder.decode(tokens[1], "UTF-8"); // response response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); PrintWriter out = response.getWriter(); out.flush(); // determine question type and extract question string String type; if (question.matches("(?i)" + FACTOID + ":.*+")) { // factoid question type = FACTOID; question = question.split(":", 2)[1].trim(); } else if (question.matches("(?i)" + LIST + ":.*+")) { // list question type = LIST; question = question.split(":", 2)[1].trim(); } else { // question type unspecified type = FACTOID; // default type } // ask question Result[] results = new Result[0]; if (type.equals(FACTOID)) { Logger.logFactoidStart(question); results = askFactoid(question, FACTOID_MAX_ANSWERS, FACTOID_ABS_THRESH); Logger.logResults(results); Logger.logFactoidEnd(); } else if (type.equals(LIST)) { Logger.logListStart(question); results = askList(question, LIST_REL_THRESH); Logger.logResults(results); Logger.logListEnd(); } String answer = results[0].getAnswer(); if (answer != null) out.println(answer); else out.println("Sorry, I cannot answer your question."); out.close(); } /** * Entry point of Ephyra. Initializes the engine and starts the web service interface. * * @param args command line arguments are ignored */ public static void main(String[] args) throws Exception { // enable output of status and error messages MsgPrinter.enableStatusMsgs(true); MsgPrinter.enableErrorMsgs(true); // set log file and enable logging Logger.setLogfile("log/OpenEphyra"); Logger.enableLogging(true); String addr = "localhost"; int port = 8080; if (args.length > 1) { addr = args[0]; port = Integer.parseInt(args[1]); } int NTHREADS = Integer.parseInt(System.getenv("THREADS")); Server server = new Server(); SelectChannelConnector con1 = new SelectChannelConnector(); con1.setHost(addr); con1.setPort(port); con1.setThreadPool(new QueuedThreadPool(NTHREADS)); con1.setMaxIdleTime(30000); con1.setRequestHeaderSize(8192); server.setConnectors(new Connector[]{con1}); server.setHandler(new OpenEphyraServer()); server.start(); server.join(); } /** * <p>Creates a new instance of Ephyra and initializes the system.</p> * * <p>For use as a standalone system.</p> */ protected OpenEphyraServer() { this(""); } /** * <p>Creates a new instance of Ephyra and initializes the system.</p> * * <p>For use as an API.</p> * * @param dir directory of Ephyra */ public OpenEphyraServer(String dir) { this.dir = dir; MsgPrinter.printInitializing(); // create tokenizer MsgPrinter.printStatusMsg("Creating tokenizer..."); if (!OpenNLP.createTokenizer(dir + "res/nlp/tokenizer/opennlp/EnglishTok.bin.gz")) MsgPrinter.printErrorMsg("Could not create tokenizer."); // create sentence detector MsgPrinter.printStatusMsg("Creating sentence detector..."); if (!OpenNLP.createSentenceDetector(dir + "res/nlp/sentencedetector/opennlp/EnglishSD.bin.gz")) MsgPrinter.printErrorMsg("Could not create sentence detector."); LingPipe.createSentenceDetector(); // create stemmer MsgPrinter.printStatusMsg("Creating stemmer..."); SnowballStemmer.create(); // create part of speech tagger MsgPrinter.printStatusMsg("Creating POS tagger..."); if (!OpenNLP.createPosTagger( dir + "res/nlp/postagger/opennlp/tag.bin.gz", dir + "res/nlp/postagger/opennlp/tagdict")) MsgPrinter.printErrorMsg("Could not create OpenNLP POS tagger."); // create chunker MsgPrinter.printStatusMsg("Creating chunker..."); if (!OpenNLP.createChunker(dir + "res/nlp/phrasechunker/opennlp/EnglishChunk.bin.gz")) MsgPrinter.printErrorMsg("Could not create chunker."); // create syntactic parser MsgPrinter.printStatusMsg("Creating syntactic parser..."); try { StanfordParser.initialize(); } catch (Exception e) { MsgPrinter.printErrorMsg("Could not create Stanford parser."); } // create named entity taggers MsgPrinter.printStatusMsg("Creating NE taggers..."); NETagger.loadListTaggers(dir + "res/nlp/netagger/lists/"); NETagger.loadRegExTaggers(dir + "res/nlp/netagger/patterns.lst"); MsgPrinter.printStatusMsg(" ...loading models"); if (!StanfordNeTagger.isInitialized() && !StanfordNeTagger.init()) MsgPrinter.printErrorMsg("Could not create Stanford NE tagger."); MsgPrinter.printStatusMsg(" ...done"); // create WordNet dictionary MsgPrinter.printStatusMsg("Creating WordNet dictionary..."); if (!WordNet.initialize(dir + "res/ontologies/wordnet/file_properties.xml")) MsgPrinter.printErrorMsg("Could not create WordNet dictionary."); // load function words (numbers are excluded) MsgPrinter.printStatusMsg("Loading function verbs..."); if (!FunctionWords.loadIndex(dir + "res/indices/functionwords_nonumbers")) MsgPrinter.printErrorMsg("Could not load function words."); // load prepositions MsgPrinter.printStatusMsg("Loading prepositions..."); if (!Prepositions.loadIndex(dir + "res/indices/prepositions")) MsgPrinter.printErrorMsg("Could not load prepositions."); // load irregular verbs MsgPrinter.printStatusMsg("Loading irregular verbs..."); if (!IrregularVerbs.loadVerbs(dir + "res/indices/irregularverbs")) MsgPrinter.printErrorMsg("Could not load irregular verbs."); // load word frequencies MsgPrinter.printStatusMsg("Loading word frequencies..."); if (!WordFrequencies.loadIndex(dir + "res/indices/wordfrequencies")) MsgPrinter.printErrorMsg("Could not load word frequencies."); // load query reformulators MsgPrinter.printStatusMsg("Loading query reformulators..."); if (!QuestionReformulationG.loadReformulators(dir + "res/reformulations/")) MsgPrinter.printErrorMsg("Could not load query reformulators."); // load question patterns MsgPrinter.printStatusMsg("Loading question patterns..."); if (!QuestionInterpreter.loadPatterns(dir + "res/patternlearning/questionpatterns/")) MsgPrinter.printErrorMsg("Could not load question patterns."); // load answer patterns MsgPrinter.printStatusMsg("Loading answer patterns..."); if (!AnswerPatternFilter.loadPatterns(dir + "res/patternlearning/answerpatterns/")) MsgPrinter.printErrorMsg("Could not load answer patterns."); } /** * Initializes the pipeline for factoid questions. */ protected void initFactoid() { // question analysis Ontology wordNet = new WordNet(); // - dictionaries for term extraction QuestionAnalysis.clearDictionaries(); QuestionAnalysis.addDictionary(wordNet); // - ontologies for term expansion QuestionAnalysis.clearOntologies(); QuestionAnalysis.addOntology(wordNet); // query generation QueryGeneration.clearQueryGenerators(); QueryGeneration.addQueryGenerator(new BagOfWordsG()); QueryGeneration.addQueryGenerator(new BagOfTermsG()); QueryGeneration.addQueryGenerator(new PredicateG()); QueryGeneration.addQueryGenerator(new QuestionInterpretationG()); QueryGeneration.addQueryGenerator(new QuestionReformulationG()); // search // - knowledge miners for unstructured knowledge sources Search.clearKnowledgeMiners(); for (String[] indriIndices : IndriKM.getIndriIndices()) Search.addKnowledgeMiner(new IndriKM(indriIndices, false)); // - knowledge annotators for (semi-)structured knowledge sources Search.clearKnowledgeAnnotators(); /* Search.addKnowledgeAnnotator(new WikipediaKA("list.txt")); */ // answer extraction and selection // (the filters are applied in this order) AnswerSelection.clearFilters(); // - answer extraction filters AnswerSelection.addFilter(new AnswerTypeFilter()); AnswerSelection.addFilter(new AnswerPatternFilter()); AnswerSelection.addFilter(new PredicateExtractionFilter()); AnswerSelection.addFilter(new FactoidsFromPredicatesFilter()); AnswerSelection.addFilter(new TruncationFilter()); // - answer selection filters AnswerSelection.addFilter(new StopwordFilter()); AnswerSelection.addFilter(new QuestionKeywordsFilter()); AnswerSelection.addFilter(new ScoreNormalizationFilter(NORMALIZER)); AnswerSelection.addFilter(new ScoreCombinationFilter()); AnswerSelection.addFilter(new FactoidSubsetFilter()); AnswerSelection.addFilter(new DuplicateFilter()); AnswerSelection.addFilter(new ScoreSorterFilter()); } /** * Runs the pipeline and returns an array of up to <code>maxAnswers</code> * results that have a score of at least <code>absThresh</code>. * * @param aq analyzed question * @param maxAnswers maximum number of answers * @param absThresh absolute threshold for scores * @return array of results */ protected Result[] runPipeline(AnalyzedQuestion aq, int maxAnswers, float absThresh) { // query generation MsgPrinter.printGeneratingQueries(); Query[] queries = QueryGeneration.getQueries(aq); // search MsgPrinter.printSearching(); Result[] results = Search.doSearch(queries); // answer selection MsgPrinter.printSelectingAnswers(); results = AnswerSelection.getResults(results, maxAnswers, absThresh); return results; } /** * Returns the directory of Ephyra. * * @return directory */ public String getDir() { return dir; } /** * Asks Ephyra a factoid question and returns up to <code>maxAnswers</code> * results that have a score of at least <code>absThresh</code>. * * @param question factoid question * @param maxAnswers maximum number of answers * @param absThresh absolute threshold for scores * @return array of results */ public Result[] askFactoid(String question, int maxAnswers, float absThresh) { // initialize pipeline initFactoid(); // analyze question MsgPrinter.printAnalyzingQuestion(); AnalyzedQuestion aq = QuestionAnalysis.analyze(question); // get answers Result[] results = runPipeline(aq, maxAnswers, absThresh); return results; } /** * Asks Ephyra a factoid question and returns a single result or * <code>null</code> if no answer could be found. * * @param question factoid question * @return single result or <code>null</code> */ public Result askFactoid(String question) { Result[] results = askFactoid(question, 1, 0); return (results.length > 0) ? results[0] : null; } /** * Asks Ephyra a list question and returns results that have a score of at * least <code>relThresh * top score</code>. * * @param question list question * @param relThresh relative threshold for scores * @return array of results */ public Result[] askList(String question, float relThresh) { question = QuestionNormalizer.transformList(question); Result[] results = askFactoid(question, Integer.MAX_VALUE, 0); // get results with a score of at least relThresh * top score ArrayList<Result> confident = new ArrayList<Result>(); if (results.length > 0) { float topScore = results[0].getScore(); for (Result result : results) if (result.getScore() >= relThresh * topScore) confident.add(result); } return confident.toArray(new Result[confident.size()]); } }
package de.tum.in.cindy3dplugin; import java.awt.Color; import java.util.ArrayList; import java.util.Hashtable; import java.util.Stack; import de.cinderella.api.cs.CindyScript; import de.cinderella.api.cs.CindyScriptPlugin; import de.cinderella.math.Vec; import de.tum.in.cindy3dplugin.Cindy3DViewer.MeshTopology; import de.tum.in.cindy3dplugin.Cindy3DViewer.NormalType; import de.tum.in.cindy3dplugin.LightModificationInfo.LightFrame; import de.tum.in.cindy3dplugin.LightModificationInfo.LightType; import de.tum.in.cindy3dplugin.jogl.JOGLViewer; import de.tum.in.cindy3dplugin.jogl.Util; /** * Implementation of the plugin interface. * * This class is responsible for * <ul> * <li>communicating with Cinderella by providing CindyScript methods and plugin * callbacks, * <li>handling the appearance states and appearance stack, * <li>managing the life cycle of a single {@link Cindy3DViewer} instance, and * <li>forwarding CindyScript calls to the {@link Cindy3DViewer} instance, * translating between the interfaces * </ul> */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class Cindy3DPlugin extends CindyScriptPlugin { private Cindy3DViewer cindy3d = null; /** * Stack of saved point appearances * * @see Cindy3DPlugin#gsave3d() * @see Cindy3DPlugin#grestore3d() */ private Stack<AppearanceState> pointAppearanceStack; /** * The current point appearance */ private AppearanceState pointAppearance; /** * Stack of saved line appearances * * @see Cindy3DPlugin#gsave3d() * @see Cindy3DPlugin#grestore3d() */ private Stack<AppearanceState> lineAppearanceStack; /** * The current line appearance */ private AppearanceState lineAppearance; /** * Stack of saved surface appearances * * @see Cindy3DPlugin#gsave3d() * @see Cindy3DPlugin#grestore3d() */ private Stack<AppearanceState> surfaceAppearanceStack; /** * The current surface appearance */ private AppearanceState surfaceAppearance; /** * Modifiers for the current CindyScript function call */ private Hashtable modifiers; /** * Creates a new plugin instance */ public Cindy3DPlugin() { pointAppearanceStack = new Stack<AppearanceState>(); pointAppearance = new AppearanceState(Color.RED, 60, 1, 1); lineAppearanceStack = new Stack<AppearanceState>(); lineAppearance = new AppearanceState(Color.BLUE, 60, 1, 1); surfaceAppearanceStack = new Stack<AppearanceState>(); surfaceAppearance = new AppearanceState(Color.GREEN, 60, 1, 1); } /* (non-Javadoc) * @see de.cinderella.api.cs.CindyScriptPlugin#register() */ @Override public void register() { if (cindy3d == null) cindy3d = new JOGLViewer(null); } /* (non-Javadoc) * @see de.cinderella.api.cs.CindyScriptPlugin#unregister() */ @Override public void unregister() { if (cindy3d != null) cindy3d.shutdown(); cindy3d = null; } /* (non-Javadoc) * @see de.cinderella.api.cs.CindyScriptPlugin#setModifiers(java.util.Hashtable) */ @Override public void setModifiers(Hashtable m) { modifiers = m; } /* (non-Javadoc) * @see de.cinderella.api.cs.CindyScriptPlugin#getModifiers() */ @Override public Hashtable getModifiers() { return modifiers; } /* (non-Javadoc) * @see de.cinderella.api.cs.CindyScriptPlugin#getAuthor() */ @Override public String getAuthor() { return "Jan Sommer and Matthias Reitinger"; } /* (non-Javadoc) * @see de.cinderella.api.cs.CindyScriptPlugin#getName() */ @Override public String getName() { return "Cindy3D"; } /** * Squares the given number. * * @param x * number to square * @return the square of x */ @CindyScript("square") public double square(double x) { return x * x; } /** * Prepares drawing of 3D objects. * * Must be called before any 3D drawing function. TODO: List these functions */ @CindyScript("begin3d") public void begin3d() { cindy3d.begin(); } /** * Finalizes the drawing of 3D objects. Displays all objects drawn since the * last call to {@link #begin3d}. */ @CindyScript("end3d") public void end3d() { cindy3d.end(); } /** * Draws a point. * * @param vec * coordinates of the point */ @CindyScript("draw3d") public void draw3d(ArrayList<Double> vec) { if (vec.size() != 3) return; cindy3d.addPoint(vec.get(0), vec.get(1), vec.get(2), applyAppearanceModifiers(pointAppearance, getModifiers())); } /** * Draws a line. * * @param vec1 * coordinates of the first end point * @param vec2 * coordinates of the second end point */ @CindyScript("draw3d") public void draw3d(ArrayList<Double> vec1, ArrayList<Double> vec2) { if (vec1.size() != 3 || vec2.size() != 3) return; // Fill in default modifiers Hashtable<String, Object> modifiers = new Hashtable<String, Object>(); modifiers.put("type", "Segment"); // Apply overrides modifiers.putAll(this.modifiers); String type = modifiers.get("type").toString(); AppearanceState appearance = applyAppearanceModifiers(lineAppearance, getModifiers()); if (type.equalsIgnoreCase("segment")) { cindy3d.addSegment(vec1.get(0), vec1.get(1), vec1.get(2), vec2.get(0), vec2.get(1), vec2.get(2), appearance); } else if (type.equalsIgnoreCase("line")) { cindy3d.addLine(vec1.get(0), vec1.get(1), vec1.get(2), vec2.get(0), vec2.get(1), vec2.get(2), appearance); } else if (type.equalsIgnoreCase("ray")) { cindy3d.addRay(vec1.get(0), vec1.get(1), vec1.get(2), vec2.get(0), vec2.get(1), vec2.get(2), appearance); } } /** * Connects a list of points by line segments. * * @param points * list of points to connect */ @CindyScript("connect3d") public void connect3d(ArrayList<Vec> points) { double vertices[][] = new double[points.size()][3]; for (int i = 0; i < points.size(); ++i) { vertices[i][0] = points.get(i).getXR(); vertices[i][1] = points.get(i).getYR(); vertices[i][2] = points.get(i).getZR(); } cindy3d.addLineStrip(vertices, applyAppearanceModifiers(lineAppearance, getModifiers()), false); } /** * Draws the outline of a polygon. * * @param points * vertices of the polygon */ @CindyScript("drawpoly3d") public void drawpoly3d(ArrayList<Vec> points) { double vertices[][] = new double[points.size()][3]; for (int i = 0; i < points.size(); ++i) { vertices[i][0] = points.get(i).getXR(); vertices[i][1] = points.get(i).getYR(); vertices[i][2] = points.get(i).getZR(); } cindy3d.addLineStrip(vertices, applyAppearanceModifiers(lineAppearance, getModifiers()), true); } /** * Draws a polygon. * * @param points * vertices of the polygon */ @CindyScript("fillpoly3d") public void fillpoly3d(ArrayList<Vec> points) { fillpoly3d(points, null); } /** * Draws a polygon with specifying vertex normals. * * @param points * vertices of the polygon * @param normals * normals for each vertex */ @CindyScript("fillpoly3d") public void fillpoly3d(ArrayList<Vec> points, ArrayList<Vec> normals) { if (points.size() == 0 || (normals != null && points.size() != normals.size())) return; double vertices[][] = new double[points.size()][3]; double normal[][] = (normals == null) ? null : new double[normals .size()][3]; for (int i = 0; i < points.size(); ++i) { vertices[i][0] = points.get(i).getXR(); vertices[i][1] = points.get(i).getYR(); vertices[i][2] = points.get(i).getZR(); if (normals != null) { normal[i][0] = normals.get(i).getXR(); normal[i][1] = normals.get(i).getYR(); normal[i][2] = normals.get(i).getZR(); } } cindy3d.addPolygon(vertices, normal, applyAppearanceModifiers(surfaceAppearance, getModifiers())); } /** * Draws a filled circle. * * @param center * center of the circle * @param normal * normal vector (orthogonal to the circle) * @param radius * radius of the circle */ @CindyScript("fillcircle3d") public void fillcircle3d(ArrayList<Double> center, ArrayList<Double> normal, double radius) { if (center.size() != 3 || normal.size() != 3) return; cindy3d.addCircle(center.get(0), center.get(1), center.get(2), normal.get(0), normal.get(1), normal.get(2), radius, applyAppearanceModifiers(surfaceAppearance, getModifiers())); } /** * Draws a grid based mesh. * * Normals are generated automatically according to the modifier * "normaltype". "perFace" is the default and generates one normal per grid * cell. "perVertex" assigns a separate normal to each grid point by * averaging the normals of the incident grid cells. * * @param rows * number of rows of vertices * @param columns * number of columns of vertices * @param points * vertex positions, in row-major order */ @CindyScript("mesh3d") public void mesh3d(int rows, int columns, ArrayList<Vec> points) { if (rows < 0 || columns < 0 || rows * columns != points.size()) return; // Fill in default modifiers Hashtable<String, Object> modifiers = new Hashtable<String, Object>(); modifiers.put("normaltype", "perface"); modifiers.put("topology", "open"); // Apply overrides modifiers.putAll(this.modifiers); String type = modifiers.get("normaltype").toString(); NormalType normalType = NormalType.PER_FACE; if (type.equalsIgnoreCase("pervertex")) { normalType = NormalType.PER_VERTEX; } double[][] vertices = new double[points.size()][3]; for (int i = 0; i < points.size(); ++i) { Vec v = points.get(i); vertices[i][0] = v.getXR(); vertices[i][1] = v.getYR(); vertices[i][2] = v.getZR(); } String topologyStr = modifiers.get("topology").toString(); MeshTopology topology = MeshTopology.OPEN; if (topologyStr.equalsIgnoreCase("open")) { topology = MeshTopology.OPEN; } else if (topologyStr.equalsIgnoreCase("closerows")) { topology = MeshTopology.CLOSE_ROWS; } else if (topologyStr.equalsIgnoreCase("closecolumns")) { topology = MeshTopology.CLOSE_COLUMNS; } else if (topologyStr.equalsIgnoreCase("closeboth")) { topology = MeshTopology.CLOSE_BOTH; } cindy3d.addMesh(rows, columns, vertices, normalType, topology, applyAppearanceModifiers(surfaceAppearance, getModifiers())); } /** * Draws a grid based mesh with user-supplied normals. * * @param rows * number of rows of vertices * @param columns * number of columns of vertices * @param points * vertex positions, in row-major order * @param normals * vertex normals, in row-major order */ @CindyScript("mesh3d") public void mesh3d(int rows, int columns, ArrayList<Vec> points, ArrayList<Vec> normals) { if (rows < 0 || columns < 0 || rows * columns != points.size() || rows * columns != normals.size()) return; double[][] vertices = new double[points.size()][3]; double[][] perVertex = new double[normals.size()][3]; for (int i = 0; i < points.size(); ++i) { Vec v = points.get(i); vertices[i][0] = v.getXR(); vertices[i][1] = v.getYR(); vertices[i][2] = v.getZR(); v = normals.get(i); perVertex[i][0] = v.getXR(); perVertex[i][1] = v.getYR(); perVertex[i][2] = v.getZR(); } // Fill in default modifiers Hashtable<String, Object> modifiers = new Hashtable<String, Object>(); modifiers.put("topology", "open"); // Apply overrides modifiers.putAll(this.modifiers); String topologyStr = modifiers.get("topology").toString(); MeshTopology topology = MeshTopology.OPEN; if (topologyStr.equalsIgnoreCase("open")) { topology = MeshTopology.OPEN; } else if (topologyStr.equalsIgnoreCase("closex")) { topology = MeshTopology.CLOSE_ROWS; } else if (topologyStr.equalsIgnoreCase("closey")) { topology = MeshTopology.CLOSE_COLUMNS; } else if (topologyStr.equalsIgnoreCase("closexy")) { topology = MeshTopology.CLOSE_BOTH; } cindy3d.addMesh(rows, columns, vertices, perVertex, topology, applyAppearanceModifiers(surfaceAppearance, getModifiers())); } /** * Draws a sphere. * * @param center * center of the sphere * @param radius * radius of the sphere */ @CindyScript("drawsphere3d") public void sphere3d(ArrayList<Double> center, double radius) { if (center.size() != 3) return; cindy3d.addSphere(center.get(0), center.get(1), center.get(2), radius, applyAppearanceModifiers(surfaceAppearance, getModifiers())); } /** * Pushes the current appearance on the appearance stack. * * @see Cindy3DPlugin#grestore3d() */ @CindyScript("gsave3d") public void gsave3d() { pointAppearanceStack.push(pointAppearance.clone()); lineAppearanceStack.push(lineAppearance.clone()); surfaceAppearanceStack.push(surfaceAppearance.clone()); } /** * Removes the top element of the appearance stack and replaces the current * appearance with it. * * @see Cindy3DPlugin#gsave3d() */ @CindyScript("grestore3d") public void grestore3d() { if (!pointAppearanceStack.isEmpty()) pointAppearance = pointAppearanceStack.pop(); if (!lineAppearanceStack.isEmpty()) lineAppearance = lineAppearanceStack.pop(); if (!surfaceAppearanceStack.isEmpty()) surfaceAppearance = surfaceAppearanceStack.pop(); } /** * Sets the color of all appearances. * * @param vec * color vector */ @CindyScript("color3d") public void color3d(ArrayList<Double> vec) { setColorState(pointAppearance, vec); setColorState(lineAppearance, vec); setColorState(surfaceAppearance, vec); } /** * Sets the color of the point appearance. * * @param vec * color vector */ @CindyScript("pointcolor3d") public void pointcolor3d(ArrayList<Double> vec) { setColorState(pointAppearance, vec); } /** * Sets the color of the line appearance. * * @param vec * color vector */ @CindyScript("linecolor3d") public void linecolor3d(ArrayList<Double> vec) { setColorState(lineAppearance, vec); } /** * Sets the color of the surface appearance. * * @param vec * color vector */ @CindyScript("surfacecolor3d") public void surfacecolor3d(ArrayList<Double> vec) { setColorState(surfaceAppearance, vec); } /** * Sets the alpha value of all appearances. * * @param alpha * alpha value, between 0 and 1 */ @CindyScript("alpha3d") public void alpha3d(double alpha) { alpha = Math.max(0, Math.min(1, alpha)); surfaceAppearance.setAlpha(alpha); } /** * Sets the alpha value of the surface appearance. * * @param alpha * alpha value, between 0 and 1 */ @CindyScript("surfacealpha3d") public void surfacealpha3d(double alpha) { surfaceAppearance.setAlpha(Math.max(0, Math.min(1, alpha))); } /** * Sets the shininess of all appearances. * * @param shininess * shininess between 0 and 128 */ @CindyScript("shininess3d") public void shininess3d(double shininess) { shininess = Math.max(0, Math.min(128, shininess)); pointAppearance.setShininess(shininess); lineAppearance.setShininess(shininess); surfaceAppearance.setShininess(shininess); } /** * Sets the shininess of the point appearance. * * @param shininess * shininess, between 0 and 128 */ @CindyScript("pointshininess3d") public void pointshininess3d(double shininess) { pointAppearance.setShininess(Math.max(0, Math.min(128, shininess))); } /** * Sets the shininess of the line appearance. * * @param shininess * shininess, between 0 and 128 */ @CindyScript("lineshininess3d") public void lineshininess3d(double shininess) { lineAppearance.setShininess(Math.max(0, Math.min(128, shininess))); } /** * Sets the shininess of the surface appearance. * * @param shininess * shininess, between 0 and 128 */ @CindyScript("surfaceshininess3d") public void surfaceshininess3d(double shininess) { surfaceAppearance.setShininess(Math.max(0, Math.min(128, shininess))); } /** * Sets the size of all appearances. * * @param size * size */ @CindyScript("size3d") public void size3d(double size) { if (size <= 0) return; pointAppearance.setSize(size); lineAppearance.setSize(size); surfaceAppearance.setSize(size); } /** * Sets the size of the point appearance. * * @param size * point size */ @CindyScript("pointsize3d") public void pointsize3d(double size) { pointAppearance.setSize(Math.max(0, size)); } /** * Sets the size of the line appearance. * * @param size * line size */ @CindyScript("linesize3d") public void linesize3d(double size) { lineAppearance.setSize(Math.max(0, size)); } /** * Sets the background color. * * @param vec * background color vector */ @CindyScript("background3d") public void background3d(ArrayList<Double> vec) { if (vec.size() != 3) return; cindy3d.setBackgroundColor(Util.toColor(vec)); } /** * Sets the camera's depth range. * * All objects with distance below <code>near</code> or above * <code>far</code> are not displayed. * * @param near * near distance * @param far * far distance */ @CindyScript("depthrange3d") public void depthrange3d(double near, double far) { cindy3d.setDepthRange(near, far); } /** * Sets render hints. */ @CindyScript("renderhints3d") public void renderhints3d() { cindy3d.setRenderHints(modifiers); } /** * Disables a single light source. * * @param light * light index, between 0 (inclusive) and * {@value de.tum.in.cindy3dplugin.Cindy3DViewer#MAX_LIGHTS} * (exclusive) */ @CindyScript("disablelight3d") public void disablelight3d(int light) { if (light < 0 || light >= Cindy3DViewer.MAX_LIGHTS) { return; } cindy3d.disableLight(light); } /** * Sets parameters for a point light. * * @param light * light index, between 0 (inclusive) and * {@value de.tum.in.cindy3dplugin.Cindy3DViewer#MAX_LIGHTS} * (exclusive) */ @CindyScript("pointlight3d") public void pointlight3d(int light) { if (light < 0 || light >= Cindy3DViewer.MAX_LIGHTS) { return; } cindy3d.setLight( light, getLightModificationInfoFromModifiers(LightType.POINT_LIGHT, modifiers)); } /** * Sets parameters for a directional light. * * @param light * light index, between 0 (inclusive) and * {@value de.tum.in.cindy3dplugin.Cindy3DViewer#MAX_LIGHTS} * (exclusive) */ @CindyScript("directionallight3d") public void directionallight3d(int light) { if (light < 0 || light >= Cindy3DViewer.MAX_LIGHTS) { return; } cindy3d.setLight( light, getLightModificationInfoFromModifiers( LightType.DIRECTIONAL_LIGHT, modifiers)); } /** * Apply modifiers to a appearance state. * * @param initialState * appearance to modify * @param modifiers * modifiers to apply. Recognized modifiers are "color", "size", * "alpha", and "shininess". * @return modified appearance */ private static AppearanceState applyAppearanceModifiers( AppearanceState initialState, Hashtable modifiers) { AppearanceState result = initialState.clone(); Object value = null; value = modifiers.get("color"); if (value instanceof double[]) { setColorState(result, (double[]) value); } value = modifiers.get("size"); if (value instanceof Double) { result.setSize((Double) value); } value = modifiers.get("alpha"); if (value instanceof Double) { double alpha = Math.max(0, Math.min(1, (Double) value)); result.setAlpha(alpha); } value = modifiers.get("shininess"); if (value instanceof Double) { double shininess = Math.max(0, Math.min(128, (Double) value)); result.setShininess((int) shininess); } return result; } /** * Translates modifiers to a <code>LightInfo</code> instance. * * @param type * light type * @param modifiers * modifiers * @return generated instance of <code>LightInfo</code> */ private static LightModificationInfo getLightModificationInfoFromModifiers( LightType type, Hashtable modifiers) { LightModificationInfo info = new LightModificationInfo(type); Object value; value = modifiers.get("ambient"); if (value instanceof double[]) { info.setAmbient(Util.toColor((double[]) value)); } value = modifiers.get("diffuse"); if (value instanceof double[]) { info.setDiffuse(Util.toColor((double[]) value)); } value = modifiers.get("specular"); if (value instanceof double[]) { info.setSpecular(Util.toColor((double[]) value)); } value = modifiers.get("position"); if (value instanceof double[]) { double[] position = (double[]) value; if (position.length == 3) { info.setPosition(position); } } value = modifiers.get("direction"); if (value instanceof double[]) { double[] direction = (double[]) value; if (direction.length == 3) { info.setDirection(direction); } } value = modifiers.get("frame"); if (value instanceof String) { String frame = (String) value; if (frame.equalsIgnoreCase("world")) { info.setFrame(LightFrame.WORLD); } else if (frame.equalsIgnoreCase("camera")) { info.setFrame(LightFrame.CAMERA); } } return info; } /** * Sets the color state of an appearance. * * @param appearance * appearance * @param vec * color vector */ private static void setColorState(AppearanceState appearance, ArrayList<Double> vec) { if (vec.size() != 3) return; appearance.setColor(Util.toColor(vec)); } /** * Sets the color state of an appearance. * * @param appearance * appearance * @param vec * color vector */ private static void setColorState(AppearanceState appearance, double[] vec) { if (vec.length != 3) return; appearance.setColor(Util.toColor(vec)); } }
package org.intermine.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.intermine.web.logic.results.PagedTable; import org.intermine.web.logic.session.SessionMethods; /** * Action that builds a PagedCollection to view a bag. * Redirects to results.do * * @author Kim Rutherford * @author Thomas Riley * */ public class BagDetailsAction extends Action { /** * Set up session attributes for the bag details page. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * * @exception Exception if an error occurs */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); String bagName = request.getParameter("bagName"); if (bagName == null) { bagName = request.getParameter("name"); } String trail = null; if (request.getParameter("trail") != null) { trail = request.getParameter("trail"); } String identifier = "bag." + bagName; PagedTable pt = SessionMethods.getResultsTable(session, identifier); if (pt != null) { if (trail != null) { trail += "|results." + pt.getTableid(); } else { trail = "|results." + pt.getTableid(); } } return new ForwardParameters(mapping.findForward("results")) .addParameter("bagName", bagName) .addParameter("table", identifier) .addParameter("trail", trail).forward(); } }
package org.commcare.android.view; import java.io.IOException; import org.commcare.android.models.Entity; import org.commcare.dalvik.R; import org.commcare.suite.model.Detail; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.odk.collect.android.views.media.AudioButton; import org.odk.collect.android.views.media.AudioController; import org.odk.collect.android.views.media.ViewId; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.speech.tts.TextToSpeech; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.style.BackgroundColorSpan; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; /** * @author ctsims * */ public class EntityView extends LinearLayout { private View[] views; private String[] forms; private TextToSpeech tts; private String[] searchTerms; private Context context; private AudioController controller; private long rowId; private static final String FORM_AUDIO = "audio"; private static final String FORM_IMAGE = "image"; /* * Constructor for row/column contents */ public EntityView(Context context, Detail d, Entity e, TextToSpeech tts, String[] searchTerms, AudioController controller, long rowId) { super(context); this.context = context; this.searchTerms = searchTerms; this.tts = tts; this.setWeightSum(1); this.controller = controller; this.rowId = rowId; views = new View[e.getNumFields()]; forms = d.getTemplateForms(); float[] weights = calculateDetailWeights(d.getTemplateSizeHints()); for (int i = 0; i < views.length; ++i) { if (weights[i] != 0) { Object uniqueId = new ViewId(rowId, i, false); views[i] = initView(e.getField(i), forms[i], uniqueId); views[i].setId(i); } } refreshViewsForNewEntity(e, false, rowId); for (int i = 0; i < views.length; i++) { LayoutParams l = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, weights[i]); if (views[i] != null) { addView(views[i], l); } } } /* * Constructor for row/column headers */ public EntityView(Context context, Detail d, String[] headerText) { super(context); this.context = context; this.setWeightSum(1); views = new View[headerText.length]; float[] lengths = calculateDetailWeights(d.getHeaderSizeHints()); String[] headerForms = d.getHeaderForms(); for (int i = 0 ; i < views.length ; ++i) { if (lengths[i] != 0) { LayoutParams l = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, lengths[i]); ViewId uniqueId = new ViewId(rowId, i, false); views[i] = initView(headerText[i], headerForms[i], uniqueId); views[i].setId(i); addView(views[i], l); } } } /* * Creates up a new view in the view with ID uniqueid, based upon * the entity's text and form */ private View initView(String text, String form, Object uniqueId) { View retVal; if (FORM_IMAGE.equals(form)) { ImageView iv =(ImageView)View.inflate(context, R.layout.entity_item_image, null); retVal = iv; } else if (FORM_AUDIO.equals(form)) { AudioButton b; if (text != null & text.length() > 0) { b = new AudioButton(context, text, uniqueId, controller, true); } else { b = new AudioButton(context, text, uniqueId, controller, false); } retVal = b; } else { View layout = View.inflate(context, R.layout.component_audio_text, null); setupTextAndTTSLayout(layout, text); retVal = layout; } return retVal; } public void setSearchTerms(String[] terms) { this.searchTerms = terms; } public void refreshViewsForNewEntity(Entity e, boolean currentlySelected, long rowId) { for (int i = 0; i < e.getNumFields() ; ++i) { String textField = e.getField(i); View view = views[i]; String form = forms[i]; if (view == null) { continue; } if (FORM_AUDIO.equals(form)) { ViewId uniqueId = new ViewId(rowId, i, false); setupAudioLayout(view, textField, uniqueId); } else if(FORM_IMAGE.equals(form)) { setupImageLayout(view, textField); } else { //text to speech setupTextAndTTSLayout(view, textField); } } if (currentlySelected) { this.setBackgroundResource(R.drawable.grey_bordered_box); } else { this.setBackgroundDrawable(null); } } /* * Updates the AudioButton layout that is passed in, based on the * new id and source */ private void setupAudioLayout(View layout, String source, ViewId uniqueId) { AudioButton b = (AudioButton)layout; if (source != null && source.length() > 0) { b.modifyButtonForNewView(uniqueId, source, true); } else { b.modifyButtonForNewView(uniqueId, source, false); } } /* * Updates the text layout that is passed in, based on the new text */ private void setupTextAndTTSLayout(View layout, final String text) { TextView tv = (TextView)layout.findViewById(R.id.component_audio_text_txt); tv.setVisibility(View.VISIBLE); tv.setText(highlightSearches(text == null ? "" : text)); ImageButton btn = (ImageButton)layout.findViewById(R.id.component_audio_text_btn_audio); btn.setFocusable(false); btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { String textToRead = text; tts.speak(textToRead, TextToSpeech.QUEUE_FLUSH, null); } }); if (tts == null || text == null || text.equals("")) { btn.setVisibility(View.INVISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width = 0; btn.setLayoutParams(params); } else { btn.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width = LayoutParams.WRAP_CONTENT; btn.setLayoutParams(params); } } /* * Updates the ImageView layout that is passed in, based on the * new id and source */ public void setupImageLayout(View layout, final String source) { ImageView iv = (ImageView) layout; Bitmap b; if (!source.equals("")) { try { b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(source).getStream()); if (b == null) { //Input stream could not be used to derive bitmap iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } else { iv.setImageBitmap(b); } } catch (IOException ex) { ex.printStackTrace(); //Error loading image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } catch (InvalidReferenceException ex) { ex.printStackTrace(); //No image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } } else { iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } } private Spannable highlightSearches(String input) { Spannable raw = new SpannableString(input); String normalized = input.toLowerCase(); if (searchTerms == null) { return raw; } //Zero out the existing spans BackgroundColorSpan[] spans=raw.getSpans(0,raw.length(), BackgroundColorSpan.class); for (BackgroundColorSpan span : spans) { raw.removeSpan(span); } for (String searchText : searchTerms) { if (searchText == "") { continue;} int index = TextUtils.indexOf(normalized, searchText); while (index >= 0) { raw.setSpan(new BackgroundColorSpan(this.getContext().getResources().getColor(R.color.search_highlight)), index, index + searchText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); index=TextUtils.indexOf(raw, searchText, index + searchText.length()); } } return raw; } private float[] calculateDetailWeights(int[] hints) { float[] weights = new float[hints.length]; int fullSize = 100; int sharedBetween = 0; for(int hint : hints) { if(hint != -1) { fullSize -= hint; } else { sharedBetween ++; } } double average = ((double)fullSize) / (double)sharedBetween; for(int i = 0; i < hints.length; ++i) { int hint = hints[i]; weights[i] = hint == -1? (float)(average/100.0) : (float)(((double)hint)/100.0); } return weights; } }
package edisyn.gui; import edisyn.*; import java.util.*; import javax.swing.*; import java.awt.event.*; import java.util.prefs.*; public class Favorites { public static final int DEFAULT_MAXIMUM = 10; int maximum; ArrayList<String> top = new ArrayList<>(); public boolean contains(String synthName) { for(int i = 0; i < top.size(); i++) { if (synthName.equals(top.get(i))) return true; } return false; } void buildFromPreferences() { top = new ArrayList<>(); Preferences prefs = Prefs.getGlobalPreferences("Top"); for(int i = maximum - 1; i >= 0; i { String t = prefs.get(("" + i), null); if (t != null) { t = t.trim(); if (t.length() != 0) { _add(t); } } } } void dumpToPreferences() { Preferences global_p = Prefs.getGlobalPreferences("Top"); for(int i = maximum - 1; i >= 0; i { global_p.remove(("" + i)); } for(int i = top.size() - 1; i >= 0; i { global_p.put(("" + i), top.get(i)); } // try { global_p.flush(); global_p.sync(); } catch (Exception ex) { ex.printStackTrace(); } Prefs.save(global_p); } void _add(String synthName) { top.remove(synthName); // if it's already there if (top.size() == maximum) top.remove(top.size() - 1); // remove top element top.add(0, synthName); } public void store(String synthName) { buildFromPreferences(); _add(synthName); dumpToPreferences(); } public void clearAll() { top = new ArrayList<>(); dumpToPreferences(); } public void clear(String synthName) { buildFromPreferences(); top.remove(synthName); dumpToPreferences(); } public ArrayList<String> getAll() { return (ArrayList<String>)(top.clone()); } public static Synth doNewSynthDialog() { Favorites f = new Favorites(); final String[] synthNames = Synth.getSynthNames(); JComboBox combo2 = new JComboBox(new String[0]); combo2.setMaximumRowCount(24); ArrayList<String> sortedTop = (ArrayList<String>)(f.top.clone()); Collections.sort(sortedTop); int[] synthIndices = new int[sortedTop.size()]; String[] synthFavs = new String[sortedTop.size() + 1]; if (sortedTop.size() == 0) synthFavs[sortedTop.size()] = "<html><i>Select a synthesizer below...<i></html>"; else synthFavs[sortedTop.size()] = "<html><i>Select another synthesizer...<i></html>"; for(int j = 0; j < sortedTop.size(); j++) { for(int k = 0; k < synthNames.length; k++) // yeah yeah, O(n^2) { final String fav = sortedTop.get(j); if (synthNames[k].equals(fav)) { synthIndices[j] = k; synthFavs[j] = fav; } } } JComboBox combo1 = new JComboBox(synthFavs); combo1.setMaximumRowCount(synthFavs.length); combo1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent event) { if (event.getStateChange() == ItemEvent.SELECTED) { if (combo1.getSelectedIndex() == sortedTop.size()) { combo2.setModel(new DefaultComboBoxModel(synthNames)); combo2.setEnabled(true); // it's select another synth } else { combo2.setModel(new DefaultComboBoxModel(new String[0])); combo2.setEnabled(false); // it's select another synth } } } }); if (f.top.size() > 0) { // find the last synth for(int i = 0; i < sortedTop.size(); i++) { if (sortedTop.get(i).equals(f.top.get(0))) { combo1.setSelectedIndex(i); break; } } combo2.setModel(new DefaultComboBoxModel(new String[0])); combo2.setEnabled(false); // it's select another synth } else { combo2.setModel(new DefaultComboBoxModel(synthNames)); combo2.setEnabled(true); // it's select another synth } int result = Synth.showMultiOption(null, new String[] { "Recent", "All Synths" }, new JComboBox[] { combo1, combo2 }, new String[] { "Okay", "Quit", "Disconnected" }, 0, "Edisyn", "Select a synthesizer to edit"); if (result == -1 || result == 1) // cancelled return null; int synthnum = combo2.getSelectedIndex(); if (combo1.getSelectedIndex() < sortedTop.size()) { synthnum = synthIndices[combo1.getSelectedIndex()]; } f.store(synthNames[synthnum]); return Synth.instantiate(Synth.getSynths()[synthnum], synthNames[synthnum], false, (result == 0), null); } public JMenu buildNewSynthMenu(final Synth synth) { JMenu newSynth = new JMenu("New Synth"); loadNewSynthMenu(newSynth, synth); return newSynth; } void loadNewSynthMenu(final JMenu newSynth, final Synth synth) { newSynth.removeAll(); ArrayList<String> sortedTop = (ArrayList<String>)(top.clone()); Collections.sort(sortedTop); boolean hasFavorite = false; String[] synthNames = synth.getSynthNames(); for(int j = 0; j < sortedTop.size(); j++) { for(int k = 0; k < synthNames.length; k++) // yeah yeah, O(n^2) { final String fav = sortedTop.get(j); if (synthNames[k].equals(fav)) { hasFavorite = true; final int _k = k; JMenuItem synthMenu = new JMenuItem(synthNames[k]); synthMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { store(fav); synth.doNewSynth(_k); } }); newSynth.add(synthMenu); } } } if (hasFavorite) newSynth.addSeparator(); for(int i = 0; i < synthNames.length; i++) { final int _i = i; JMenuItem synthMenu = new JMenuItem(synthNames[i]); synthMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { store(synthNames[_i]); synth.doNewSynth(_i); } }); newSynth.add(synthMenu); } newSynth.addSeparator(); JMenuItem clearOne = new JMenuItem("Clear " + synth.getSynthNameLocal()); clearOne.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clear(synth.getSynthNameLocal()); loadNewSynthMenu(newSynth, synth); // reload menu } }); newSynth.add(clearOne); JMenuItem clearAll = new JMenuItem("Clear All Recent Synths"); clearAll.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearAll(); loadNewSynthMenu(newSynth, synth); // reload menu } }); newSynth.add(clearAll); } public Favorites() { this(DEFAULT_MAXIMUM); } public Favorites(int maximum) { this.maximum = maximum; buildFromPreferences(); } }
import java.util.*; public class SegmentTree { // Modify the following 6 methods to implement your custom operations on the tree. Pay attention to contracts int queryOperation(int x, int y) { return Math.max(x, y); } int modifyOperation(int x, int y) { return x + y; } int totalDeltaEffect(int delta, int count) { // contract: totalDeltaEffect(delta, count) == queryOperation(delta, queryOperation(delta, ...count times)) return delta; // delta * count (for sum queryOperation) } int getNeutralValue() { // contract: queryOperation(x, getNeutralValue()) == x return Integer.MIN_VALUE; } int getNeutralDelta() { // contract: modifyOperation(x, getNeutralDelta()) == x return 0; } int getInitValue() { return 0; } // generic tree code int n; int[] value; int[] delta; // delta[i] affects value[i], delta[2*i+1] and delta[2*i+2] public SegmentTree(int n) { this.n = n; value = new int[4 * n]; delta = new int[4 * n]; init(0, 0, n - 1); } void init(int root, int left, int right) { if (left == right) { value[root] = getInitValue(); delta[root] = getNeutralDelta(); } else { init(2 * root + 1, left, (left + right) / 2); init(2 * root + 2, (left + right) / 2 + 1, right); value[root] = queryOperation(value[2 * root + 1], value[2 * root + 2]); delta[root] = getNeutralDelta(); } } void pushDelta(int root, int left, int right) { value[root] = modifyOperation(value[root], totalDeltaEffect(delta[root], right - left + 1)); delta[2 * root + 1] = modifyOperation(delta[2 * root + 1], delta[root]); delta[2 * root + 2] = modifyOperation(delta[2 * root + 2], delta[root]); delta[root] = getNeutralDelta(); } public int query(int a, int b) { return query(a, b, 0, 0, n - 1); } int query(int a, int b, int root, int left, int right) { if (a > right || b < left) return getNeutralValue(); if (a <= left && right <= b) return modifyOperation(value[root], totalDeltaEffect(delta[root], right - left + 1)); pushDelta(root, left, right); return queryOperation(query(a, b, root * 2 + 1, left, (left + right) / 2), query(a, b, root * 2 + 2, (left + right) / 2 + 1, right)); } public void modify(int a, int b, int delta) { modify(a, b, delta, 0, 0, n - 1); } void modify(int a, int b, int delta, int root, int left, int right) { if (a > right || b < left) return; if (a <= left && right <= b) { this.delta[root] = modifyOperation(this.delta[root], delta); return; } pushDelta(root, left, right); int middle = (left + right) / 2; modify(a, b, delta, 2 * root + 1, left, middle); modify(a, b, delta, 2 * root + 2, middle + 1, right); value[root] = queryOperation(modifyOperation(value[2 * root + 1], totalDeltaEffect(this.delta[2 * root + 1], middle - left + 1)), modifyOperation(value[2 * root + 2], totalDeltaEffect(this.delta[2 * root + 2], right - middle))); } // Random test public static void main(String[] args) { Random rnd = new Random(); for (int step = 0; step < 1000; step++) { int n = rnd.nextInt(50) + 1; int[] x = new int[n]; SegmentTree t = new SegmentTree(n); Arrays.fill(x, t.getInitValue()); for (int i = 0; i < 1000; i++) { int b = rnd.nextInt(n); int a = rnd.nextInt(b + 1); int cmd = rnd.nextInt(3); if (cmd == 0) { int delta = rnd.nextInt(100) - 50; t.modify(a, b, delta); for (int j = a; j <= b; j++) x[j] = t.modifyOperation(x[j], t.totalDeltaEffect(delta, 1)); } else if (cmd == 1) { int res1 = t.query(a, b); int res2 = x[a]; for (int j = a + 1; j <= b; j++) res2 = t.queryOperation(res2, x[j]); if (res1 != res2) throw new RuntimeException("error"); } else { for (int j = 0; j < n; j++) { if (t.query(j, j) != x[j]) throw new RuntimeException("error"); } } } } System.out.println("Test passed"); } }
package water; import org.junit.*; public class KVSpeedTest extends TestUtil { @Ignore @Test public void testDoesNothing() { } /* static final int NCLOUD=10; static final int NKEYS=1000000; @BeforeClass static public void setup() { stall_till_cloudsize(NCLOUD); } // Make a million keys-per-node. Make sure they are all cached/shared on at // least one other node. Time removing them all. Can be network bound as // the million read/write/put/invalidates hit the wires. @Test @Ignore public void testMillionRemoveKeys() { long start = System.currentTimeMillis(); // Compute home keys byte[] homes = new byte[NKEYS*NCLOUD]; for( int i=0; i<homes.length; i++ ) homes[i] = (byte)Key.make("Q"+i).home(H2O.CLOUD); final Key k = Key.make("homes"); DKV.put(k,new Value(k,homes)); start = logTime(start,"HOMEALL",NCLOUD); // Populate NKEYS locally new MRTask() { @Override protected void setupLocal() { byte[] homes = DKV.get(k).rawMem(); final int sidx = H2O.SELF.index(); long start = System.currentTimeMillis(); for( int i=0; i<homes.length; i++ ) { if( homes[i]==sidx ) { String s = "Q"+i; Key k = Key.make(s); DKV.put(k,new Value(k,s),_fs); } } logTime(start, "PUT1 "+H2O.SELF, 1); } }.doAllNodes(); start = logTime(start,"PUTALL",NCLOUD); // Force sharing at least once new MRTask() { @Override protected void setupLocal() { byte[] homes = DKV.get(k).rawMem(); final int sidx = H2O.SELF.index(); long start = System.currentTimeMillis(); for( int i=0; i<homes.length; i++ ) if( homes[i]==sidx ) DKV.prefetch(Key.make("Q"+i+1)); start = logTime(start, "PREFETCH1 "+H2O.SELF, 1); for( int i=0; i<homes.length; i++ ) if( homes[i]==sidx ) DKV.get(Key.make("Q"+i+1)); logTime(start, "GET1 "+H2O.SELF, 1); } }.doAllNodes(); start = logTime(start,"GETALL",NCLOUD); Futures fs = new Futures(); for( int i=0; i<homes.length; i++ ) DKV.remove(Key.make("Q"+i), fs); start = logTime(start,"REMALL_START",NCLOUD); fs.blockForPending(); logTime(start,"REMALL_DONE",NCLOUD); DKV.remove(k); } private long logTime( long start, String msg, int ncloud ) { long now = System.currentTimeMillis(); double d = (double)(now-start)/NKEYS/ncloud; System.out.println(msg+" "+d+" msec/op"); return now; } */ }
package webserver; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.commons.lang3.StringUtils; import org.eclipse.jetty.util.StringUtil; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import qora.account.Account; import qora.block.Block; import qora.blockexplorer.BlockExplorer; import qora.crypto.Crypto; import qora.naming.Name; import qora.transaction.Transaction; import qora.web.BlogBlackWhiteList; import qora.web.HTMLSearchResult; import qora.web.Profile; import qora.web.ProfileHelper; import qora.web.blog.BlogEntry; import settings.Settings; import utils.AccountBalanceComparator; import utils.BlogUtils; import utils.GZIP; import utils.JSonWriter; import utils.NameUtils; import utils.NameUtils.NameResult; import utils.Pair; import utils.PebbleHelper; import utils.Qorakeys; import utils.StrJSonFine; import utils.Triplet; import api.ATResource; import api.AddressesResource; import api.ApiErrorFactory; import api.BlocksResource; import api.BlogPostResource; import api.CalcFeeResource; import api.NameSalesResource; import api.NamesResource; import api.TransactionsResource; import com.mitchellbosecke.pebble.error.PebbleException; import controller.Controller; import database.DBSet; import database.NameMap; @Path("/") public class WebResource { @Context HttpServletRequest request; @GET public Response Default() { // REDIRECT return Response.status(302).header("Location", "index/main.html") .build(); } public Response handleDefault() { try { String searchValue = request.getParameter("search"); PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/main.mini.html"); if (searchValue == null) { return Response.ok( PebbleHelper.getPebbleHelper("web/main.html") .evaluate(), "text/html; charset=utf-8") .build(); } if(StringUtils.isBlank(searchValue)) { return Response.ok( pebbleHelper.evaluate(), "text/html; charset=utf-8") .build(); } List<Pair<String, String>> searchResults; searchResults = NameUtils.getWebsitesByValue(searchValue); List<HTMLSearchResult> results = generateHTMLSearchresults(searchResults); pebbleHelper.getContextMap().put("searchresults", results); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } public List<HTMLSearchResult> generateHTMLSearchresults( List<Pair<String, String>> searchResults) throws IOException, PebbleException { List<HTMLSearchResult> results = new ArrayList<>(); for (Pair<String, String> result : searchResults) { String name = result.getA(); String websitecontent = result.getB(); Document htmlDoc = Jsoup.parse(websitecontent); String title = selectTitleOpt(htmlDoc); title = title == null ? "" : title; String description = selectDescriptionOpt(htmlDoc); description = description == null ? "" : description; description = StringUtils.abbreviate(description, 150); results.add(new HTMLSearchResult(title, description, name, "/" + name, "/" + name, "/namepairs:" + name)); } return results; } @SuppressWarnings("rawtypes") @Path("index/blockexplorer.json") @GET public Response jsonQueryMain(@Context UriInfo info) { Map output = BlockExplorer.getInstance().jsonQueryMain(info); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(StrJSonFine.StrJSonFine(JSONValue.toJSONString(output))) .build(); } @Path("index/blockexplorer") @GET public Response blockexplorer() { return blockexplorerhtml(); } @Path("index/blockexplorer.html") @GET public Response blockexplorerhtml() { try { String content = readFile("web/blockexplorer.html", StandardCharsets.UTF_8); return Response.ok(content, "text/html; charset=utf-8").build(); } catch (IOException e) { e.printStackTrace(); return error404(request); } } @Path("index/blogsearch.html") @GET public Response doBlogSearch() { String searchValue = request.getParameter("search"); try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/main.mini.html"); if (StringUtil.isBlank(searchValue)) { return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } List<HTMLSearchResult> results = handleBlogSearch(searchValue); pebbleHelper.getContextMap().put("searchresults", results); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } @Path("index/blogdirectory.html") @GET public Response doBlogdirectory() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/main.mini.html"); List<HTMLSearchResult> results = handleBlogSearch(null); pebbleHelper.getContextMap().put("searchresults", results); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } @SuppressWarnings("unchecked") @POST @Path("index/settingssave.html") @Consumes("application/x-www-form-urlencoded") public Response saveProfileSettings(@Context HttpServletRequest request, MultivaluedMap<String, String> form) { JSONObject json = new JSONObject(); try { String profileName = form.getFirst("profilename"); if (StringUtils.isBlank(profileName)) { json.put("type", "parametersMissing"); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } Name name = null; name = Controller.getInstance().getName(profileName); if (name == null || !Profile.isAllowedProfileName(profileName)) { json.put("type", "profileNameisnotAllowed"); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } boolean blogenable = Boolean.valueOf(form .getFirst(Qorakeys.BLOGENABLE.toString())); boolean profileenable = Boolean.valueOf(form .getFirst(Qorakeys.PROFILEENABLE.toString())); String titleOpt = form.getFirst(Qorakeys.BLOGTITLE.toString()); titleOpt = decodeIfNotNull(titleOpt); String blogDescrOpt = form.getFirst(Qorakeys.BLOGDESCRIPTION .toString()); blogDescrOpt = decodeIfNotNull(blogDescrOpt); String profileAvatarOpt = form.getFirst(Qorakeys.PROFILEAVATAR .toString()); String profileBannerOpt = form.getFirst(Qorakeys.PROFILEMAINGRAPHIC .toString()); String bwlistkind = form.getFirst("bwlistkind"); String blackwhitelist = form.getFirst("blackwhitelist"); blackwhitelist = URLDecoder.decode(blackwhitelist, "UTF-8"); profileAvatarOpt = decodeIfNotNull(profileAvatarOpt); profileBannerOpt = decodeIfNotNull(profileBannerOpt); Profile profile = Profile.getProfileOpt(name); profile.saveAvatarTitle(profileAvatarOpt); profile.saveProfileMainGraphicOpt(profileBannerOpt); profile.saveBlogDescription(blogDescrOpt); profile.saveBlogTitle(titleOpt); profile.setBlogEnabled(blogenable); profile.setProfileEnabled(profileenable); profile.getBlogBlackWhiteList().clearList(); profile.getBlogBlackWhiteList().setWhitelist( !bwlistkind.equals("black")); String[] bwList = StringUtils.split(blackwhitelist, ";"); for (String listentry : bwList) { profile.getBlogBlackWhiteList().addAddressOrName(listentry); } try { profile.saveProfile(); json.put("type", "settingsSuccessfullySaved"); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } catch (WebApplicationException e) { json = new JSONObject(); json.put("type", "error"); json.put("error", e.getResponse().getEntity()); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } } catch (Throwable e) { e.printStackTrace(); json.put("type", "error"); json.put("error", e.getMessage()); return Response.status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } } @Path("index/settings.html") @GET public Response doProfileSettings() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/settings.html"); String profileName = request.getParameter("profilename"); List<Name> namesAsList = new CopyOnWriteArrayList<Name>(Controller .getInstance().getNamesAsList()); for (Name name : namesAsList) { if (!Profile.isAllowedProfileName(name.getName())) { namesAsList.remove(name); } } pebbleHelper.getContextMap().put("names", namesAsList); Name name = null; if (profileName != null) { name = Controller.getInstance().getName(profileName); } if (namesAsList.size() > 0) { if (name == null) { Profile activeProfileOpt = ProfileHelper.getInstance() .getActiveProfileOpt(); if (activeProfileOpt != null) { name = activeProfileOpt.getName(); } else { name = namesAsList.get(0); } } // WE HAVE HERE ONLY ALLOWED NAMES SO PROFILE CAN'T BE NULL HERE Profile profile = Profile.getProfileOpt(name); pebbleHelper.getContextMap().put("profile", profile); pebbleHelper.getContextMap().put("name", name); } else { pebbleHelper .getContextMap() .put("result", "<div class=\"alert alert-danger\" role=\"alert\">You need to register a name to create a profile.<br></div>"); } return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } public String decodeIfNotNull(String parameter) throws UnsupportedEncodingException { return parameter != null ? URLDecoder.decode(parameter, "UTF-8") : null; } @Path("index/webdirectory.html") @GET public Response doWebdirectory() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/main.mini.html"); List<Pair<String, String>> websitesByValue = NameUtils .getWebsitesByValue(null); List<HTMLSearchResult> results = generateHTMLSearchresults(websitesByValue); pebbleHelper.getContextMap().put("searchresults", results); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } private List<HTMLSearchResult> handleBlogSearch(String blogSearchOpt) { List<HTMLSearchResult> results = new ArrayList<>(); List<Triplet<String, String, String>> allEnabledBlogs = BlogUtils .getEnabledBlogs(blogSearchOpt); for (Triplet<String, String, String> triplet : allEnabledBlogs) { String name = triplet.getA(); String title = triplet.getB(); String description = triplet.getC(); description = StringUtils.abbreviate(description, 150); results.add(new HTMLSearchResult(title, description, name, "/index/blog.html?blogname=" + name, "/index/blog.html?blogname=" + name, "/namepairs:" + name)); } return results; } public static String selectTitleOpt(Document htmlDoc) { String title = selectFirstElementOpt(htmlDoc, "title"); return title; } public static String selectFirstElementOpt(Document htmlDoc, String tag) { Elements titleElements = htmlDoc.select(tag); String title = null; if (titleElements.size() > 0) { title = titleElements.get(0).text(); } return title; } public static String selectDescriptionOpt(Document htmlDoc) { String result = ""; Elements descriptions = htmlDoc.select("meta[name=\"description\"]"); if (descriptions.size() > 0) { Element descr = descriptions.get(0); if (descr.hasAttr("content")) { result = descr.attr("content"); } } return result; } @Path("index/main.html") @GET public Response handleIndex() { return handleDefault(); } @Path("favicon.ico") @GET public Response favicon() { File file = new File("web/favicon.ico"); if (file.exists()) { return Response.ok(file, "image/vnd.microsoft.icon").build(); } else { return error404(request); } } @Path("index/favicon.ico") @GET public Response indexfavicon() { File file = new File("web/favicon.ico"); if (file.exists()) { return Response.ok(file, "image/vnd.microsoft.icon").build(); } else { return error404(request); } } String[] imgsArray = { "qora.png", "logo_header.png", "qora-user.png", "logo_bottom.png", "banner_01.png", "loading.gif", "00_generating.png", "01_genesis.jpg", "02_payment_in.png", "02_payment_out.png", "03_name_registration.png", "04_name_update.png", "05_name_sale.png", "06_cancel_name_sale.png", "07_name_purchase_in.png", "07_name_purchase_out.png", "08_poll_creation.jpg", "09_poll_vote.jpg", "10_arbitrary_transaction.png", "11_asset_issue.png", "12_asset_transfer_in.png", "12_asset_transfer_out.png", "13_order_creation.png", "14_cancel_order.png", "15_multi_payment_in.png", "15_multi_payment_out.png", "16_deploy_at.png", "17_message_in.png", "17_message_out.png", "asset_trade.png", "at_tx_in.png", "at_tx_out.png", "grleft.png", "grright.png", "redleft.png", "redright.png", "bar.gif", "bar_left.gif", "bar_right.gif" }; @Path("index/img/{filename}") @GET public Response image(@PathParam("filename") String filename) { ArrayList<String> imgs = new ArrayList<String>(); imgs.addAll(Arrays.asList(imgsArray)); int imgnum = imgs.indexOf(filename); if (imgnum == -1) { return error404(request); } File file = new File("web/img/" + imgs.get(imgnum)); String type = ""; switch (getFileExtention(imgs.get(imgnum))) { case "png": type = "image/png"; break; case "gif": type = "image/gif"; break; case "jpg": type = "image/jpeg"; break; } if (file.exists()) { return Response.ok(file, type).build(); } else { return error404(request); } } public static String getFileExtention(String filename) { int dotPos = filename.lastIndexOf(".") + 1; return filename.substring(dotPos); } @SuppressWarnings("unchecked") @Path("index/API.html") @GET public Response handleAPICall() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/apianswer.html"); // EXAMPLE POST/GET/DELETE String type = request.getParameter("type"); // EXAMPLE /names/key/MyName String url = request.getParameter("apiurl"); String okmsg = request.getParameter("okmsg"); String errormsg = request.getParameter("errormsg"); if (StringUtils.isBlank(type) || (!type.equalsIgnoreCase("get") && !type.equalsIgnoreCase("post") && !type .equalsIgnoreCase("delete"))) { pebbleHelper.getContextMap().put("title", "An Api error occured"); pebbleHelper .getContextMap() .put("apicall", "You need a type parameter with value GET/POST or DELETE "); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } if (StringUtils.isBlank(url)) { pebbleHelper.getContextMap().put("title", "An Api error occured"); pebbleHelper.getContextMap().put("apicall", "You need to provide an apiurl parameter"); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } url = url.startsWith("/") ? url.substring(1) : url; Map<String, String[]> parameterMap = new HashMap<String, String[]>( request.getParameterMap()); parameterMap.remove("type"); parameterMap.remove("apiurl"); parameterMap.remove("okmsg"); parameterMap.remove("errormsg"); Set<String> keySet = parameterMap.keySet(); JSONObject json = new JSONObject(); for (String key : keySet) { String[] value = parameterMap.get(key); json.put(key, value[0]); } try { // CREATE CONNECTION URL urlToCall = new URL("http://127.0.0.1:" + Settings.getInstance().getRpcPort() + "/" + url); HttpURLConnection connection = (HttpURLConnection) urlToCall .openConnection(); // EXECUTE connection.setRequestMethod(type.toUpperCase()); if (type.equalsIgnoreCase("POST")) { connection.setDoOutput(true); connection.getOutputStream().write( json.toJSONString().getBytes("UTF-8")); connection.getOutputStream().flush(); connection.getOutputStream().close(); } // READ RESULT InputStream stream; if (connection.getResponseCode() == 400) { stream = connection.getErrorStream(); } else { stream = connection.getInputStream(); } InputStreamReader isReader = new InputStreamReader(stream, "UTF-8"); BufferedReader br = new BufferedReader(isReader); String result = br.readLine(); if (result.contains("message") && result.contains("error")) { if (StringUtils.isNotBlank(errormsg)) { pebbleHelper.getContextMap().put("customtext", "<font color=red>" + errormsg + "</font>"); } pebbleHelper.getContextMap().put("title", "An Api error occured"); pebbleHelper.getContextMap().put( "apicall", "apicall: " + type.toUpperCase() + " " + url + (json.size() > 0 ? json.toJSONString() : "")); pebbleHelper.getContextMap().put("errormessage", "Result:" + result); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } else { if (StringUtils.isNotBlank(okmsg)) { pebbleHelper.getContextMap().put("customtext", "<font color=green>" + okmsg + "</font>"); } pebbleHelper.getContextMap().put("title", "The API Call was successful"); pebbleHelper.getContextMap().put( "apicall", "Submitted Api call: " + type.toUpperCase() + " " + url + (json.size() > 0 ? json.toJSONString() : "")); pebbleHelper.getContextMap().put("errormessage", "Result:" + result); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } } catch (IOException e) { e.printStackTrace(); String additionalHelp = ""; if (e instanceof FileNotFoundException) { additionalHelp = "The apicall with the following apiurl is not existing: "; } pebbleHelper.getContextMap().put("title", "An Api error occured"); pebbleHelper.getContextMap().put( "apicall", "You tried to submit the following apicall: " + type.toUpperCase() + " " + url + (json.size() > 0 ? json.toJSONString() : "")); pebbleHelper.getContextMap().put("errormessage", additionalHelp + e.getMessage()); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } } catch (Throwable e) { e.printStackTrace(); } return error404(request); } @Path("index/libs/css/style.css") @GET public Response style() { File file = new File("web/libs/css/style.css"); if (file.exists()) { return Response.ok(file, "text/css").build(); } else { return error404(request); } } @Path("index/libs/css/sidebar.css") @GET public Response sidebarcss() { File file = new File("web/libs/css/sidebar.css"); if (file.exists()) { return Response.ok(file, "text/css").build(); } else { return error404(request); } } @Path("index/libs/css/timeline.css") @GET public Response timelinecss() { File file = new File("web/libs/css/timeline.css"); if (file.exists()) { return Response.ok(file, "text/css").build(); } else { return error404(request); } } @Path("index/libs/js/sidebar.js") @GET public Response sidebarjs() { File file = new File("web/libs/js/sidebar.js"); if (file.exists()) { return Response.ok(file, "text/javascript").build(); } else { return error404(request); } } @SuppressWarnings("unchecked") @POST @Path("index/postblogprocessing.html") @Consumes("application/x-www-form-urlencoded") public Response postBlogProcessing(@Context HttpServletRequest request, MultivaluedMap<String, String> form) { JSONObject json = new JSONObject(); String title = form.getFirst(BlogPostResource.TITLE_KEY); String creator = form.getFirst("creator"); String contentparam = form.getFirst("content"); String fee = form.getFirst("fee"); String preview = form.getFirst("preview"); String calcfee = form.getFirst("calcfee"); String blogname = form.getFirst(BlogPostResource.BLOGNAME_KEY); if (StringUtil.isNotBlank(creator) && StringUtil.isNotBlank(contentparam) && StringUtil.isNotBlank(fee)) { JSONObject jsonBlogPost = new JSONObject(); Pair<Account, NameResult> nameToAdress = NameUtils .nameToAdress(creator); String authorOpt = null; if (nameToAdress.getB() == NameResult.OK) { authorOpt = creator; jsonBlogPost.put(BlogPostResource.AUTHOR, authorOpt); jsonBlogPost.put("creator", nameToAdress.getA().getAddress()); } else { jsonBlogPost.put("creator", creator); } jsonBlogPost.put("fee", fee); jsonBlogPost.put("title", title); jsonBlogPost.put("body", contentparam); if (StringUtils.isNotBlank(preview) && preview.equals("true")) { json.put("type", "preview"); BlogEntry entry = new BlogEntry(title, contentparam, authorOpt, new Date().getTime(), creator); json.put("previewBlogpost", entry.toJson()); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } try { if (StringUtils.isNotBlank(calcfee) && calcfee.equals("true")) { jsonBlogPost.put("blogname", blogname); String result = new CalcFeeResource() .calcFeeForBlogPost(jsonBlogPost.toJSONString()); json.put("type", "fee"); json.put("result", result); } else { String result = new BlogPostResource().addBlogEntry( jsonBlogPost.toJSONString(), blogname); json.put("type", "postSuccessful"); json.put("result", result); } return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } catch (WebApplicationException e) { json = new JSONObject(); json.put("type", "error"); json.put("error", e.getResponse().getEntity()); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } } return Response.status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } @Path("index/postblog.html") @GET public Response postBlog() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/postblog.html"); pebbleHelper.getContextMap().put("errormessage", ""); pebbleHelper.getContextMap().put("font", ""); pebbleHelper.getContextMap().put("content", ""); pebbleHelper.getContextMap().put("option", ""); pebbleHelper.getContextMap().put("oldtitle", ""); pebbleHelper.getContextMap().put("oldcreator", ""); pebbleHelper.getContextMap().put("oldcontent", ""); pebbleHelper.getContextMap().put("oldfee", ""); pebbleHelper.getContextMap().put("preview", ""); String blogname = request .getParameter(BlogPostResource.BLOGNAME_KEY); BlogBlackWhiteList blogBlackWhiteList = BlogBlackWhiteList .getBlogBlackWhiteList(blogname); Pair<List<Account>, List<Name>> ownAllowedElements = blogBlackWhiteList .getOwnAllowedElements(true); List<Account> resultingAccounts = new ArrayList<Account>( ownAllowedElements.getA()); List<Name> resultingNames = ownAllowedElements.getB(); Collections.sort(resultingAccounts, new AccountBalanceComparator()); Collections.reverse(resultingAccounts); String accountStrings = ""; for (Name name : resultingNames) { accountStrings += "<option value=" + name.getName() + ">" + name.getNameBalanceString() + "</option>"; } for (Account account : resultingAccounts) { accountStrings += "<option value=" + account.getAddress() + ">" + account + "</option>"; } // are we allowed to post if (resultingNames.size() == 0 && resultingAccounts.size() == 0) { pebbleHelper .getContextMap() .put("errormessage", "<div class=\"alert alert-danger\" role=\"alert\">You can't post to this blog! None of your accounts has balance or the blogowner did not allow your accounts to post!<br></div>"); } Profile activeProfileOpt = ProfileHelper.getInstance() .getActiveProfileOpt(); if (activeProfileOpt != null && resultingNames.contains(activeProfileOpt.getName())) { pebbleHelper.getContextMap().put("primaryname", activeProfileOpt.getName().getName()); } pebbleHelper.getContextMap().put("option", accountStrings); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } @SuppressWarnings("unchecked") @POST @Path("index/followblog.html") @Consumes("application/x-www-form-urlencoded") public Response followBlog(@Context HttpServletRequest request, MultivaluedMap<String, String> form) { try { JSONObject json = new JSONObject(); String blogname = form.getFirst(BlogPostResource.BLOGNAME_KEY); String followString = form.getFirst("follow"); NameMap nameMap = DBSet.getInstance().getNameMap(); Profile activeProfileOpt = ProfileHelper.getInstance() .getActiveProfileOpt(); if (followString != null && activeProfileOpt != null && blogname != null && nameMap.contains(blogname)) { boolean follow = Boolean.valueOf(followString); Name name = nameMap.get(blogname); Profile profile = Profile.getProfileOpt(name); if (activeProfileOpt.isProfileEnabled()) { if (follow) { if (profile != null && profile.isProfileEnabled() && profile.isBlogEnabled()) { String result; if (activeProfileOpt.getFollowedBlogs().contains( blogname)) { result = "<center><div class=\"alert alert-danger\" role=\"alert\">Blog follow not successful<br>" + "You already follow this blog" + "</div></center>"; json.put("type", "youAlreadyFollowThisBlog"); json.put("follower", profile.getFollower() .size()); json.put("isFollowing", activeProfileOpt .getFollowedBlogs().contains(blogname)); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } // Prevent following of own profiles if (Controller.getInstance() .getNamesAsListAsString() .contains(blogname)) { result = "<center><div class=\"alert alert-danger\" role=\"alert\">Blog follow not successful<br>" + "You can't follow your own profiles" + "</div></center>"; json.put("type", "youCantFollowYourOwnProfiles"); json.put("follower", profile.getFollower() .size()); json.put("isFollowing", activeProfileOpt .getFollowedBlogs().contains(blogname)); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } boolean isFollowing = activeProfileOpt .getFollowedBlogs().contains(blogname); try { activeProfileOpt.addFollowedBlog(blogname); result = activeProfileOpt.saveProfile(); result = "<div class=\"alert alert-success\" role=\"alert\">You follow this blog now<br>" + result + "</div>"; json.put("type", "YouFollowThisBlogNow"); json.put("result", result); json.put("follower", profile.getFollower() .size()); json.put("isFollowing", activeProfileOpt .getFollowedBlogs().contains(blogname)); } catch (WebApplicationException e) { result = "<center><div class=\"alert alert-danger\" role=\"alert\">Blog follow not successful<br>" + e.getResponse().getEntity() + "</div></center>"; json.put("type", "BlogFollowNotSuccessful"); json.put("result", e.getResponse().getEntity()); json.put("follower", profile.getFollower() .size()); json.put("isFollowing", isFollowing); } return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } } else { boolean isFollowing = activeProfileOpt .getFollowedBlogs().contains(blogname); if (activeProfileOpt.getFollowedBlogs().contains( blogname)) { activeProfileOpt.removeFollowedBlog(blogname); String result; try { result = activeProfileOpt.saveProfile(); result = "<div class=\"alert alert-success\" role=\"alert\">Unfollow successful<br>" + result + "</div>"; json.put("type", "unfollowSuccessful"); json.put("result", result); json.put("follower", profile.getFollower() .size()); json.put("isFollowing", activeProfileOpt .getFollowedBlogs().contains(blogname)); } catch (WebApplicationException e) { result = "<center><div class=\"alert alert-danger\" role=\"alert\">Blog unfollow not successful<br>" + e.getResponse().getEntity() + "</div></center>"; json.put("type", "blogUnfollowNotSuccessful"); json.put("result", e.getResponse().getEntity()); json.put("follower", profile.getFollower() .size()); json.put("isFollowing", isFollowing); } return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } } } } return getBlog(null); } catch (Throwable e) { e.printStackTrace(); return Response.status(200) .header("Content-Type", "application/json; charset=utf-8") .entity("{}").build(); } } @SuppressWarnings("unchecked") @POST @Path("index/likeprofile.html") @Consumes("application/x-www-form-urlencoded") public Response likeProfile(@Context HttpServletRequest request, MultivaluedMap<String, String> form) { JSONObject json = new JSONObject(); try { String profilename = form.getFirst(BlogPostResource.BLOGNAME_KEY); String likeString = form.getFirst("like"); NameMap nameMap = DBSet.getInstance().getNameMap(); Profile activeProfileOpt = ProfileHelper.getInstance() .getActiveProfileOpt(); if (likeString != null && activeProfileOpt != null && profilename != null && nameMap.contains(profilename)) { boolean like = Boolean.valueOf(likeString); Profile profile = Profile.getProfileOpt(profilename); if (activeProfileOpt.isProfileEnabled()) { if (like) { if (profile != null && profile.isProfileEnabled() && profile.isBlogEnabled()) { String result; if (activeProfileOpt.getLikedProfiles().contains( profilename)) { json.put("type", "YouAlreadyLikeThisProfile"); json.put("likes", profile.getLikes().size()); json.put("isLikeing", activeProfileOpt.getLikedProfiles() .contains(profilename)); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } // Prevent liking of own profiles if (Controller.getInstance() .getNamesAsListAsString() .contains(profilename)) { json.put("type", "YouCantLikeYourOwnProfiles"); json.put("likes", profile.getLikes().size()); json.put("isLikeing", activeProfileOpt.getLikedProfiles() .contains(profilename)); return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } boolean isLikeing = activeProfileOpt .getLikedProfiles().contains(profilename); activeProfileOpt.addLikeProfile(profilename); try { result = activeProfileOpt.saveProfile(); json.put("type", "LikeSuccessful"); json.put("result", result); json.put("likes", profile.getLikes().size()); json.put("isLikeing", activeProfileOpt.getLikedProfiles() .contains(profilename)); } catch (WebApplicationException e) { json.put("type", "LikeNotSuccessful"); json.put("result", e.getResponse().getEntity()); json.put("likes", profile.getLikes().size()); json.put("isLikeing", isLikeing); } return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } } else { if (activeProfileOpt.getLikedProfiles().contains( profilename)) { boolean isLikeing = activeProfileOpt .getLikedProfiles().contains(profilename); activeProfileOpt.removeLikeProfile(profilename); String result; try { result = activeProfileOpt.saveProfile(); json.put("type", "LikeRemovedSuccessful"); json.put("result", result); json.put("likes", profile.getLikes().size()); json.put("isLikeing", activeProfileOpt.getLikedProfiles() .contains(profilename)); } catch (WebApplicationException e) { json.put("type", "LikeRemovedNotSuccessful"); json.put("result", e.getResponse().getEntity()); json.put("likes", profile.getLikes().size()); json.put("isLikeing", isLikeing); } return Response .status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } } } } } catch (Throwable e) { e.printStackTrace(); json.put("type", "error"); json.put("error", e.getMessage()); return Response.status(200) .header("Content-Type", "application/json; charset=utf-8") .entity(json.toJSONString()).build(); } return Response.status(200) .header("Content-Type", "application/json; charset=utf-8") .entity("{}").build(); } @Path("index/blog.html") @GET public Response getBlog(String messageOpt) { try { String blogname = request .getParameter(BlogPostResource.BLOGNAME_KEY); String switchprofile = request.getParameter("switchprofile"); ProfileHelper.getInstance().switchProfileOpt(switchprofile); PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/blog.html"); pebbleHelper.getContextMap().put("postblogurl", "postblog.html"); pebbleHelper.getContextMap().put("apimessage", messageOpt); NameMap nameMap = DBSet.getInstance().getNameMap(); if (blogname != null) { if (!nameMap.contains(blogname)) { return Response.ok( PebbleHelper.getPebbleHelper( "web/profiledisabled.html").evaluate(), "text/html; charset=utf-8").build(); } Name name = nameMap.get(blogname); Profile profile = Profile.getProfileOpt(name); if (profile == null || !profile.isProfileEnabled()) { pebbleHelper = PebbleHelper .getPebbleHelper("web/profiledisabled.html"); if (Controller.getInstance().getAccountByAddress( name.getOwner().getAddress()) != null) { pebbleHelper.getContextMap().put("ownProfileName", blogname); } return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } pebbleHelper.getContextMap().put("postblogurl", "postblog.html?blogname=" + blogname); pebbleHelper.getContextMap().put("blogprofile", profile); pebbleHelper.getContextMap().put("blogenabled", profile.isBlogEnabled()); if (Controller.getInstance().getAccountByAddress( name.getOwner().getAddress()) != null) { pebbleHelper.getContextMap() .put("ownProfileName", blogname); } pebbleHelper.getContextMap().put("follower", profile.getFollower()); pebbleHelper.getContextMap().put("likes", profile.getLikes()); } else { pebbleHelper.getContextMap().put("blogenabled", true); } Profile activeProfileOpt = ProfileHelper.getInstance() .getActiveProfileOpt(); pebbleHelper.getContextMap().put( "isFollowing", activeProfileOpt != null && activeProfileOpt.getFollowedBlogs().contains( blogname)); pebbleHelper.getContextMap().put( "isLikeing", activeProfileOpt != null && activeProfileOpt.getLikedProfiles().contains( blogname)); List<BlogEntry> blogPosts = BlogUtils.getBlogPosts(blogname); pebbleHelper.getContextMap().put("blogposts", blogPosts); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } @Path("index/libs/js/Base58.js") @GET public Response Base58js() { File file = new File("web/libs/js/Base58.js"); if (file.exists()) { return Response.ok(file, "text/javascript").build(); } else { return error404(request); } } @Path("index/libs/js/common.js") @GET public Response commonjs() { File file = new File("web/libs/js/common.js"); if (file.exists()) { return Response.ok(file, "text/javascript").build(); } else { return error404(request); } } @Path("index/libs/jquery/jquery.{version}.js") @GET public Response jquery(@PathParam("version") String version) { File file; if (version.equals("1")) { file = new File("web/libs/jquery/jquery-1.11.3.min.js"); } else if (version.equals("2")) { file = new File("web/libs/jquery/jquery-2.1.4.min.js"); } else { file = new File("web/libs/jquery/jquery-2.1.4.min.js"); } if (file.exists()) { return Response.ok(file, "text/javascript; charset=utf-8").build(); } else { return error404(request); } } @Path("index/libs/angular/angular.{version}.js") @GET public Response angular(@PathParam("version") String version) { File file; if (version.equals("1.3")) { file = new File("web/libs/angular/angular.min.1.3.15.js"); } else if (version.equals("1.4")) { file = new File("web/libs/angular/angular.min.1.4.0.js"); } else { file = new File("web/libs/angular/angular.min.1.3.15.js"); } if (file.exists()) { return Response.ok(file, "text/javascript; charset=utf-8").build(); } else { return error404(request); } } @Path("index/libs/bootstrap/{version}/{folder}/{filename}") @GET public Response bootstrap(@PathParam("version") String version, @PathParam("folder") String folder, @PathParam("filename") String filename) { String fullname = "web/libs/bootstrap-3.3.4-dist/"; String type = "text/html; charset=utf-8"; switch (folder) { case "css": { fullname += "css/"; type = "text/css"; switch (filename) { case "bootstrap.css": fullname += "bootstrap.css"; break; case "theme.css": fullname += "theme.css"; break; case "bootstrap.css.map": fullname += "bootstrap.css.map"; break; case "bootstrap.min.css": fullname += "bootstrap.min.css"; break; case "bootstrap-theme.css": fullname += "bootstrap-theme.css"; break; case "bootstrap-theme.css.map": fullname += "bootstrap-theme.css.mapp"; break; case "bootstrap-theme.min.css": fullname += "bootstrap-theme.min.css"; break; } break; } case "fonts": { fullname += "fonts/"; switch (filename) { case "glyphicons-halflings-regular.eot": fullname += "glyphicons-halflings-regular.eot"; type = "application/vnd.ms-fontobject"; break; case "glyphicons-halflings-regular.svg": fullname += "glyphicons-halflings-regular.svg"; type = "image/svg+xml"; break; case "glyphicons-halflings-regular.ttf": fullname += "glyphicons-halflings-regular.ttf"; type = "application/x-font-ttf"; break; case "glyphicons-halflings-regular.woff": fullname += "glyphicons-halflings-regular.woff"; type = "application/font-woff"; break; case "glyphicons-halflings-regular.woff2": fullname += "glyphicons-halflings-regular.woff2"; type = "application/font-woff"; break; } break; } case "js": { fullname += "js/"; type = "text/javascript"; switch (filename) { case "bootstrap.js": fullname += "bootstrap.js"; break; case "bootstrap.min.js": fullname += "bootstrap.js"; break; case "npm.js": fullname += "npm.js"; break; } break; } } File file = new File(fullname); if (file.exists()) { return Response.ok(file, type).build(); } else { return error404(request); } } public Response error404(HttpServletRequest request) { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/404.html"); return Response.status(404) .header("Content-Type", "text/html; charset=utf-8") .entity(pebbleHelper.evaluate()).build(); } catch (PebbleException e) { e.printStackTrace(); return Response.status(404).build(); } } public static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); } @SuppressWarnings("unchecked") @Path("namepairs:{name}") @GET public Response showNamepairs(@PathParam("name") String name) { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/main.mini.html"); NameMap nameMap = DBSet.getInstance().getNameMap(); if (nameMap.contains(name)) { Name nameObj = nameMap.get(name); String value = nameObj.getValue(); JSONObject resultJson = NameUtils.getJsonForNameOpt(nameObj); // BAD FORMAT --> NO KEYVALUE if (resultJson == null) { resultJson = new JSONObject(); resultJson.put(Qorakeys.DEFAULT.toString(), value); value = jsonToFineSting(resultJson.toJSONString()); } pebbleHelper.getContextMap().put("keyvaluepairs", resultJson); pebbleHelper.getContextMap().put("dataname", name); return Response.status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(pebbleHelper.evaluate()).build(); } else { return error404(request); } } catch (Throwable e) { e.printStackTrace(); return error404(request); } } @Path("block:{block}") @GET public Response getBlock(@PathParam("block") String strBlock) { String str; try { if (strBlock.matches("\\d+")) { str = BlocksResource.getbyHeight(Integer.valueOf(strBlock)); } else if (strBlock.equals("last")) { str = BlocksResource.getLastBlock(); } else { str = BlocksResource.getBlock(strBlock); } str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>Block does not exist!</h2"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Block : " + strBlock + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @SuppressWarnings("unchecked") @Path("tx:{tx}") @GET public Response getTx(@PathParam("tx") String strTx) { String str = null; try { if (Crypto.getInstance().isValidAddress(strTx)) { Account account = new Account(strTx); Pair<Block, List<Transaction>> result = Controller .getInstance().scanTransactions(null, -1, -1, -1, -1, account); JSONObject json = new JSONObject(); JSONArray transactions = new JSONArray(); for (Transaction transaction : result.getB()) { transactions.add(transaction.toJson()); } json.put(strTx, transactions); str = json.toJSONString(); } else { str = TransactionsResource.getTransactionsBySignature(strTx); } str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>Transaction does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Transaction : " + strTx + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("balance:{address}") @GET public Response getBalance(@PathParam("address") String address) { String str = null; try { String addressreal = ""; if (!Crypto.getInstance().isValidAddress(address)) { Pair<Account, NameResult> nameToAdress = NameUtils .nameToAdress(address); if (nameToAdress.getB() == NameResult.OK) { addressreal = nameToAdress.getA().getAddress(); } else { throw ApiErrorFactory.getInstance().createError( nameToAdress.getB().getErrorCode()); } } else { addressreal = address; } str = AddressesResource.getGeneratingBalance(addressreal); } catch (Exception e1) { str = "<h2>Address does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Balance of " + address + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = {\"amount\":" + str + "}")) .build(); } @Path("balance:{address}:{confirmations}") @GET public Response getBalance(@PathParam("address") String address, @PathParam("confirmations") int confirmations) { String str = null; try { str = AddressesResource .getGeneratingBalance(address, confirmations); } catch (Exception e1) { str = "<h2>Address does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Balance of " + address + ":" + confirmations + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = {\"amount\":" + str + "}")) .build(); } @Path("name:{name}") @GET public Response getName(@PathParam("name") String strName) { String str = null; String strNameSale = null; try { str = NamesResource.getName(strName); if (DBSet.getInstance().getNameExchangeMap().contains(strName)) { strNameSale = NameSalesResource.getNameSale(strName); } str = jsonToFineSting(str); if (strNameSale != null) { str += "\n\n" + jsonToFineSting(strNameSale); } } catch (Exception e1) { str = "<h2>Name does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Name : " + strName + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("at:{at}") @GET public Response getAt(@PathParam("at") String strAt) { String str = null; try { str = ATResource.getAT(strAt); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT : " + strAt + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("atbysender:{atbysender}") @GET public Response getAtTx(@PathParam("atbysender") String strAtbySender) { String str = null; try { str = ATResource.getATTransactionsBySender(strAtbySender); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT Sender : " + strAtbySender + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("atbycreator:{atbycreator}") @GET public Response getAtbyCreator( @PathParam("atbycreator") String strAtbyCreator) { String str = null; try { str = ATResource.getATsByCreator(strAtbyCreator); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT Creator : " + strAtbyCreator + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("attxbyrecipient:{attxbyrecipient}") @GET public Response getATTransactionsByRecipient( @PathParam("attxbyrecipient") String StrAtTxbyRecipient) { String str = null; try { str = ATResource.getATTransactionsByRecipient(StrAtTxbyRecipient); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT TX by Recipient : " + StrAtTxbyRecipient + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } public String miniIndex() { try { return readFile("web/main.mini.html", StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); return "ERROR"; } } public String jsonToFineSting(String str) { Writer writer = new JSonWriter(); Object jsonResult = JSONValue.parse(str); try { if (jsonResult instanceof JSONArray) { ((JSONArray) jsonResult).writeJSONString(writer); return writer.toString(); } if (jsonResult instanceof JSONObject) { ((JSONObject) jsonResult).writeJSONString(writer); return writer.toString(); } writer.close(); return ""; } catch (IOException e) { e.printStackTrace(); return ""; } } @Path("{name}") @GET public Response getNames(@PathParam("name") String nameName) { Name name = Controller.getInstance().getName(nameName); // CHECK IF NAME EXISTS if (name == null) { return error404(request); } String value = name.getValue(); // REDIRECT if (value.toLowerCase().startsWith("http: || value.toLowerCase().startsWith("https: return Response.status(302).header("Location", value).build(); } JSONObject jsonObject = NameUtils.getJsonForNameOpt(name); String website = null; if (jsonObject != null && jsonObject.containsKey(Qorakeys.WEBSITE.getKeyname())) { website = (String) jsonObject.get(Qorakeys.WEBSITE.getKeyname()); } if (website == null) { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/websitenotfound.html"); pebbleHelper.getContextMap().put("name", nameName.replaceAll(" ", "%20")); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } website = injectValues(website); // SHOW WEB-PAGE return Response.status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(website).build(); } public static String injectValues(String value) { // PROCESSING TAG INJ Pattern pattern = Pattern.compile("(?i)(<inj.*>(.*?)</inj>)"); Matcher matcher = pattern.matcher(value); while (matcher.find()) { Document doc = Jsoup.parse(matcher.group(1)); Elements inj = doc.select("inj"); Element element = inj.get(0); NameMap nameMap = DBSet.getInstance().getNameMap(); String name = matcher.group(2); if (nameMap.contains(name)) { Name nameinj = nameMap.get(name); String result = GZIP.webDecompress(nameinj.getValue() .toString()); if (element.hasAttr("key")) { String key = element.attr("key"); try { JSONObject jsonObject = (JSONObject) JSONValue .parse(result); if (jsonObject != null) { // Looks like valid jSon if (jsonObject.containsKey(key)) { result = (String) jsonObject.get(key); } } } catch (Exception e) { // no json probably } } value = value.replace(matcher.group(), result); } } return value; } }
package com.demonwav.mcdev.platform.mcp.inspections; import com.demonwav.mcdev.platform.MinecraftModule; import com.demonwav.mcdev.platform.mcp.McpModuleType; import com.demonwav.mcdev.platform.mcp.util.McpConstants; import com.demonwav.mcdev.util.McPsiUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiClassType; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiParameter; import com.intellij.psi.PsiType; import com.intellij.psi.PsiTypeElement; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; public class EntityConstructorInspection extends BaseInspection { @Nls @NotNull @Override public String getDisplayName() { return "MCP Entity class missing World constructor"; } @NotNull @Override protected String buildErrorString(Object... infos) { return "All entities must have a constructor that takes one " + McpConstants.WORLD + " parameter."; } @Override public BaseInspectionVisitor buildVisitor() { return new BaseInspectionVisitor() { @Override public void visitClass(PsiClass aClass) { if (!McPsiUtil.extendsOrImplementsClass(aClass, McpConstants.ENTITY)) { return; } final Module module = ModuleUtilCore.findModuleForPsiElement(aClass); if (module == null) { return; } final MinecraftModule instance = MinecraftModule.getInstance(module); if (instance == null) { return; } if (!instance.isOfType(McpModuleType.getInstance())) { return; } final PsiMethod[] constructors = aClass.getConstructors(); for (PsiMethod constructor : constructors) { if (constructor.getParameterList().getParameters().length != 1) { continue; } final PsiParameter parameter = constructor.getParameterList().getParameters()[0]; final PsiTypeElement typeElement = parameter.getTypeElement(); if (typeElement == null) { continue; } final PsiType type = typeElement.getType(); if (!(type instanceof PsiClassType)) { continue; } final PsiClass resolve = ((PsiClassType) type).resolve(); if (resolve == null) { continue; } if (resolve.getQualifiedName() == null) { continue; } if (resolve.getQualifiedName().equals(McpConstants.WORLD)) { return; } } registerClassError(aClass); } }; } }
package org.commcare.android.view; import java.io.File; import java.io.IOException; import org.commcare.android.models.Entity; import org.commcare.dalvik.R; import org.commcare.suite.model.Detail; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.speech.tts.TextToSpeech; import android.text.Html; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.style.BackgroundColorSpan; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.media.MediaPlayer; /** * @author ctsims * */ public class EntityView extends LinearLayout { private View[] views; private String[] forms; private TextToSpeech tts; private MediaPlayer mp; private String[] searchTerms; public EntityView(Context context, Detail d, Entity e, TextToSpeech tts, String[] searchTerms) { super(context); this.searchTerms = searchTerms; this.tts = tts; mp = new MediaPlayer(); this.setWeightSum(1); views = new View[e.getNumFields()]; forms = d.getTemplateForms(); float[] weights = calculateDetailWeights(d.getTemplateSizeHints()); for(int i = 0 ; i < views.length ; ++i) { if(weights[i] != 0) { LayoutParams l = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, weights[i]); views[i] = getView(context, null, forms[i]); views[i].setId(i); addView(views[i], l); } } setParams(e, false); } public EntityView(Context context, Detail d, String[] headerText) { super(context); this.setWeightSum(1); mp = new MediaPlayer(); views = new View[headerText.length]; float[] lengths = calculateDetailWeights(d.getHeaderSizeHints()); String[] headerForms = d.getHeaderForms(); for(int i = 0 ; i < views.length ; ++i) { if(lengths[i] != 0) { LayoutParams l = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, lengths[i]); /*this first call is just demarcating the space for each view in a row, and then * setParams will fill in those existing views with the appropriate content, depending * on the form type */ views[i] = getView(context, headerText[i], headerForms[i]); views[i].setId(i); addView(views[i], l); } } } /* * if form = "text", then 'text' field is just normal text * if form = "audio" or "image", then text is the path to the audio/image */ private View getView(Context context, String text, String form) { View retVal; if ("image".equals(form)) { ImageView iv =(ImageView)View.inflate(context, R.layout.entity_item_image, null); retVal = iv; if (text != null) { try { Bitmap b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(text).getStream()); iv.setImageBitmap(b); } catch (IOException e) { e.printStackTrace(); //Error loading image } catch (InvalidReferenceException e) { e.printStackTrace(); //No image } } } else if ("audio".equals(form)) { View layout = View.inflate(context, R.layout.component_audio_text, null); setupAudioLayout(layout,text); retVal = layout; } else { View layout = View.inflate(context, R.layout.component_audio_text, null); setupTTSLayout(layout, text); retVal = layout; } return retVal; } public void setSearchTerms(String[] terms) { this.searchTerms = terms; } public void setParams(Entity e, boolean currentlySelected) { for (int i = 0; i < e.getNumFields() ; ++i) { String textField = e.getField(i); View view = views[i]; String form = forms[i]; if (view == null || textField == null) { continue; } if ("audio".equals(form)) { setupAudioLayout(view, textField); } else if("image".equals(form)) { setupImageLayout(view, textField); } else { //text to speech setupTTSLayout(view, textField); } } if (currentlySelected) { this.setBackgroundResource(R.drawable.grey_bordered_box); } else { this.setBackgroundDrawable(null); } } private void setupAudioLayout(View layout, final String text) { ImageButton btn = (ImageButton)layout.findViewById(R.id.component_audio_text_btn_audio); btn.setFocusable(false); btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { if (mp.isPlaying()) { mp.pause(); } else { try { mp.setDataSource(text); mp.prepare(); mp.start(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); if (text == null || text.equals("") || !new File(text).exists()) { btn.setVisibility(View.INVISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width= 0; btn.setLayoutParams(params); } else { btn.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width=LayoutParams.WRAP_CONTENT; btn.setLayoutParams(params); } } private void setupTTSLayout(View layout, final String text) { TextView tv = (TextView)layout.findViewById(R.id.component_audio_text_txt); ImageButton btn = (ImageButton)layout.findViewById(R.id.component_audio_text_btn_audio); btn.setFocusable(false); btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { String textToRead = text; tts.speak(textToRead, TextToSpeech.QUEUE_FLUSH, null); } }); if (tts == null || text == null || text.equals("")) { btn.setVisibility(View.INVISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width= 0; btn.setLayoutParams(params); } else { btn.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width=LayoutParams.WRAP_CONTENT; btn.setLayoutParams(params); } tv.setText(highlightSearches(text == null ? "" : text)); } public void setupImageLayout(View layout, final String text) { ImageView iv = (ImageView) layout; Bitmap b; try { if(!text.equals("")) { b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(text).getStream()); //TODO: shouldn't this check if b is null? iv.setImageBitmap(b); } else{ iv.setImageBitmap(null); } } catch (IOException ex) { ex.printStackTrace(); //Error loading image iv.setImageBitmap(null); } catch (InvalidReferenceException ex) { ex.printStackTrace(); //No image iv.setImageBitmap(null); } } private Spannable highlightSearches(String input) { Spannable raw=new SpannableString(input); String normalized = input.toLowerCase(); if(searchTerms == null) { return raw; } //Zero out the existing spans BackgroundColorSpan[] spans=raw.getSpans(0,raw.length(), BackgroundColorSpan.class); for (BackgroundColorSpan span : spans) { raw.removeSpan(span); } for(String searchText : searchTerms) { if(searchText == "") { continue;} int index=TextUtils.indexOf(normalized, searchText); while (index >= 0) { raw.setSpan(new BackgroundColorSpan(this.getContext().getResources().getColor(R.color.search_highlight)), index, index + searchText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); index=TextUtils.indexOf(raw, searchText, index + searchText.length()); } } return raw; } private float[] calculateDetailWeights(int[] hints) { float[] weights = new float[hints.length]; int fullSize = 100; int sharedBetween = 0; for(int hint : hints) { if(hint != -1) { fullSize -= hint; } else { sharedBetween ++; } } double average = ((double)fullSize) / (double)sharedBetween; for(int i = 0; i < hints.length; ++i) { int hint = hints[i]; weights[i] = hint == -1? (float)(average/100.0) : (float)(((double)hint)/100.0); } return weights; } }
package processing.app.syntax; import org.fife.ui.rsyntaxtextarea.*; import org.fife.ui.rsyntaxtextarea.Theme; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.focusabletip.FocusableTip; import org.fife.ui.rtextarea.RTextArea; import org.fife.ui.rtextarea.RUndoManager; import processing.app.*; import javax.swing.*; import javax.swing.event.EventListenerList; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Segment; import javax.swing.undo.UndoManager; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Logger; public class SketchTextArea extends RSyntaxTextArea { private final static Logger LOG = Logger.getLogger(SketchTextArea.class.getName()); /** * The last docTooltip displayed. */ private FocusableTip docTooltip; /** * The component that tracks the current line number. */ protected EditorLineStatus editorLineStatus; private EditorListener editorListener; private final PdeKeywords pdeKeywords; public SketchTextArea(PdeKeywords pdeKeywords) throws IOException { this.pdeKeywords = pdeKeywords; installFeatures(); } protected void installFeatures() throws IOException { setTheme(PreferencesData.get("editor.syntax_theme", "default")); setLinkGenerator(new DocLinkGenerator(pdeKeywords)); fixControlTab(); setSyntaxEditingStyle(SYNTAX_STYLE_CPLUSPLUS); } public void setTheme(String name) throws IOException { FileInputStream defaultXmlInputStream = null; try { defaultXmlInputStream = new FileInputStream(new File(BaseNoGui.getContentFile("lib"), "theme/syntax/" + name + ".xml")); Theme theme = Theme.load(defaultXmlInputStream); theme.apply(this); } finally { if (defaultXmlInputStream != null) { defaultXmlInputStream.close(); } } setForeground(processing.app.Theme.getColor("editor.fgcolor")); setBackground(processing.app.Theme.getColor("editor.bgcolor")); setCurrentLineHighlightColor(processing.app.Theme.getColor("editor.linehighlight.color")); setCaretColor(processing.app.Theme.getColor("editor.caret.color")); setSelectedTextColor(null); setUseSelectedTextColor(false); setSelectionColor(processing.app.Theme.getColor("editor.selection.color")); setMatchedBracketBorderColor(processing.app.Theme.getColor("editor.brackethighlight.color")); setHyperlinkForeground((Color) processing.app.Theme.getStyledFont("url", getFont()).get("color")); setSyntaxTheme(TokenTypes.DATA_TYPE, "data_type"); setSyntaxTheme(TokenTypes.FUNCTION, "function"); setSyntaxTheme(TokenTypes.RESERVED_WORD, "reserved_word"); setSyntaxTheme(TokenTypes.RESERVED_WORD_2, "reserved_word_2"); setSyntaxTheme(TokenTypes.VARIABLE, "variable"); setSyntaxTheme(TokenTypes.OPERATOR, "operator"); setSyntaxTheme(TokenTypes.COMMENT_DOCUMENTATION, "comment1"); setSyntaxTheme(TokenTypes.COMMENT_EOL, "comment1"); setSyntaxTheme(TokenTypes.COMMENT_KEYWORD, "comment1"); setSyntaxTheme(TokenTypes.COMMENT_MARKUP, "comment1"); setSyntaxTheme(TokenTypes.LITERAL_CHAR, "literal_char"); setSyntaxTheme(TokenTypes.LITERAL_STRING_DOUBLE_QUOTE, "literal_string_double_quote"); } private void setSyntaxTheme(int tokenType, String id) { Style style = getSyntaxScheme().getStyle(tokenType); Map<String, Object> styledFont = processing.app.Theme.getStyledFont(id, style.font); style.foreground = (Color) styledFont.get("color"); style.font = (Font) styledFont.get("font"); getSyntaxScheme().setStyle(tokenType, style); } // Removing the default focus traversal keys // This is because the DefaultKeyboardFocusManager handles the keypress and consumes the event protected void fixControlTab() { KeyStroke ctrlTab = KeyStroke.getKeyStroke("ctrl TAB"); KeyStroke ctrlShiftTab = KeyStroke.getKeyStroke("ctrl shift TAB"); // Remove ctrl-tab from normal focus traversal Set<AWTKeyStroke> forwardKeys = new HashSet<AWTKeyStroke>(this.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)); forwardKeys.remove(ctrlTab); this.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forwardKeys); // Remove ctrl-shift-tab from normal focus traversal Set<AWTKeyStroke> backwardKeys = new HashSet<AWTKeyStroke>(this.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)); backwardKeys.remove(ctrlShiftTab); } public void setEditorLineStatus(EditorLineStatus editorLineStatus) { this.editorLineStatus = editorLineStatus; } @Override public void select(int selectionStart, int selectionEnd) { super.select(selectionStart, selectionEnd); if (editorLineStatus != null) editorLineStatus.set(selectionStart, selectionEnd); } public boolean isSelectionActive() { return this.getSelectedText() != null; } public void setSelectedText(String text) { int old = getTextMode(); setTextMode(OVERWRITE_MODE); replaceSelection(text); setTextMode(old); } public void processKeyEvent(KeyEvent evt) { // this had to be added because the menu key events weren't making it up to the frame. switch (evt.getID()) { case KeyEvent.KEY_TYPED: if (editorListener != null) editorListener.keyTyped(evt); break; case KeyEvent.KEY_PRESSED: if (editorListener != null) editorListener.keyPressed(evt); break; case KeyEvent.KEY_RELEASED: // inputHandler.keyReleased(evt); break; } if (!evt.isConsumed()) { super.processKeyEvent(evt); } } public void switchDocument(Document document, UndoManager newUndo) { // HACK: Dont discard changes on curret UndoManager. setUndoManager(null); // bypass reset current undo manager... super.setDocument(document); setUndoManager((RUndoManager) newUndo); // HACK: Complement previous hack (hide code folding on switch) | Drawback: Lose folding state // if(sketch.getCodeCount() > 1 && textarea.isCodeFoldingEnabled()){ // textarea.setCodeFoldingEnabled(false); // textarea.setCodeFoldingEnabled(true); } @Override protected JPopupMenu createPopupMenu() { JPopupMenu menu = super.createPopupMenu(); return menu; } @Override protected void configurePopupMenu(JPopupMenu popupMenu) { super.configurePopupMenu(popupMenu); } @Override protected RTAMouseListener createMouseListener() { return new SketchTextAreaMouseListener(this); } public void getTextLine(int line, Segment segment) { try { int offset = getLineStartOffset(line); int end = getLineEndOffset(line); getDocument().getText(offset, end - offset, segment); } catch (BadLocationException e) { } } public String getTextLine(int line) { try { int offset = getLineStartOffset(line); int end = getLineEndOffset(line); return getDocument().getText(offset, end - offset); } catch (BadLocationException e) { return null; } } public void setEditorListener(EditorListener editorListener) { this.editorListener = editorListener; } private static class DocLinkGenerator implements LinkGenerator { private final PdeKeywords pdeKeywords; public DocLinkGenerator(PdeKeywords pdeKeywords) { this.pdeKeywords = pdeKeywords; } @Override public LinkGeneratorResult isLinkAtOffset(RSyntaxTextArea textArea, final int offs) { final Token token = textArea.modelToToken(offs); final String reference = pdeKeywords.getReference(token.getLexeme()); // LOG.fine("reference: " + reference + ", match: " + (token.getType() == TokenTypes.DATA_TYPE || token.getType() == TokenTypes.VARIABLE || token.getType() == TokenTypes.FUNCTION)); if (token != null && (reference != null || (token.getType() == TokenTypes.DATA_TYPE || token.getType() == TokenTypes.VARIABLE || token.getType() == TokenTypes.FUNCTION))) { LinkGeneratorResult generatorResult = new LinkGeneratorResult() { @Override public int getSourceOffset() { return offs; } @Override public HyperlinkEvent execute() { LOG.fine("Open Reference: " + reference); Base.showReference("Reference/" + reference); return null; } }; return generatorResult; } return null; } } private class SketchTextAreaMouseListener extends RTextAreaMutableCaretEvent { private Insets insets; private boolean isScanningForLinks; private int hoveredOverLinkOffset = -1; protected SketchTextAreaMouseListener(RTextArea textArea) { super(textArea); insets = new Insets(0, 0, 0, 0); } /** * Notifies all listeners that have registered interest for notification * on this event type. The listener list is processed last to first. * * @param e The event to fire. * @see EventListenerList */ private void fireHyperlinkUpdate(HyperlinkEvent e) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==HyperlinkListener.class) { ((HyperlinkListener)listeners[i+1]).hyperlinkUpdate(e); } } } private HyperlinkEvent createHyperlinkEvent(MouseEvent e) { HyperlinkEvent he = null; Token t = viewToToken(e.getPoint()); if (t!=null) { // Copy token, viewToModel() unfortunately modifies Token t = new TokenImpl(t); } if (t != null && t.isHyperlink()) { URL url = null; String desc = null; try { String temp = t.getLexeme(); if (temp.startsWith("www.")) { temp = "http://" + temp; } url = new URL(temp); } catch (MalformedURLException mue) { desc = mue.getMessage(); } he = new HyperlinkEvent(SketchTextArea.this, HyperlinkEvent.EventType.ACTIVATED, url, desc); } return he; } @Override public void mouseClicked(MouseEvent e) { if (getHyperlinksEnabled()) { HyperlinkEvent he = createHyperlinkEvent(e); if (he!=null) { fireHyperlinkUpdate(he); } } } @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); if (!getHyperlinksEnabled()) { return; } // LinkGenerator linkGenerator = getLinkGenerator(); // GitHub issue RSyntaxTextArea/#25 - links identified at "edges" of editor // should not be activated if mouse is in margin insets. insets = getInsets(insets); if (insets!=null) { int x = e.getX(); int y = e.getY(); if (x<=insets.left || y<insets.top) { if (isScanningForLinks) { stopScanningForLinks(); } return; } } isScanningForLinks = true; Token t = viewToToken(e.getPoint()); if (t!=null) { // Copy token, viewToModel() unfortunately modifies Token t = new TokenImpl(t); } Cursor c2 = null; if (t!=null && t.isHyperlink()) { if (hoveredOverLinkOffset==-1 || hoveredOverLinkOffset!=t.getOffset()) { hoveredOverLinkOffset = t.getOffset(); repaint(); } c2 = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); } // else if (t!=null && linkGenerator!=null) { // int offs = viewToModel(e.getPoint()); // LinkGeneratorResult newResult = linkGenerator. // isLinkAtOffset(SketchTextArea.this, offs); // if (newResult!=null) { // // Repaint if we're at a new link now. // if (linkGeneratorResult==null || // !equal(newResult, linkGeneratorResult)) { // repaint(); // linkGeneratorResult = newResult; // hoveredOverLinkOffset = t.getOffset(); // c2 = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); // else { // // Repaint if we've moved off of a link. // if (linkGeneratorResult!=null) { // repaint(); // c2 = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); // hoveredOverLinkOffset = -1; // linkGeneratorResult = null; else { c2 = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); hoveredOverLinkOffset = -1; // linkGeneratorResult = null; } if (getCursor()!=c2) { setCursor(c2); // TODO: Repaint just the affected line(s). repaint(); // Link either left or went into. } } private void stopScanningForLinks() { if (isScanningForLinks) { Cursor c = getCursor(); isScanningForLinks = false; if (c != null && c.getType() == Cursor.HAND_CURSOR) { setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); repaint(); // TODO: Repaint just the affected line. } } } } }
package com.sometrik.framework; import java.util.ArrayList; import java.util.Iterator; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.GradientDrawable; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.LinearLayout.LayoutParams; public class FWLayout extends LinearLayout implements NativeCommandHandler { private FrameWork frame; private boolean childListeners = false; private ChildClickListener hostListener; public FWLayout(FrameWork frameWork) { super(frameWork); this.frame = frameWork; setDividerDrawable(frame.getResources().getDrawable(android.R.drawable.divider_horizontal_bright)); // setDividerDrawable(frame.getResources().getDrawable(android.R.drawable.divider_horizontal_textfield)); this.setBackgroundColor(Color.rgb(255, 255, 255)); } @Override public int getElementId() { return getId(); } @Override public void addChild(final View view) { addView(view); if (childListeners) { if (view instanceof AdapterView) { return; } else { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("child click " + v.getId()); int index = getChildIndex(v.getId()); hostListener.onClick(index, v.getId()); } }); } } else if (view instanceof FWLayout){ view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getElementId(), 0, 1); } }); } } public interface ChildClickListener { public void onClick(int childIndex, int childId); } private int getChildIndex(int id) { for (int i = 0; i < getChildCount(); i++) { if (id == getChildAt(i).getId()) { return i; } } return 0; } @Override public void addOption(int optionId, String text) { System.out.println("FWLayout couldn't handle command"); } @Override public void setValue(String v) { System.out.println("FWLayout couldn't handle command"); } @Override public void setValue(int v) { if (v == 1){ frame.setCurrentView(this, true); } else if (v == 2){ frame.setCurrentView(this, false); } } public void setChildListeners(final ChildClickListener listener) { this.hostListener = listener; childListeners = true; for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); if (view instanceof AdapterView) { return; } else { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("child click " + v.getId()); int index = getChildIndex(v.getId()); hostListener.onClick(index, v.getId()); } }); } } } @Override public void setViewEnabled(Boolean enabled) { System.out.println("FWLayout couldn't handle command"); } @Override public void setStyle(String key, String value) { if (key.equals("gravity")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); if (value.equals("bottom")) { params.gravity = Gravity.BOTTOM; } else if (value.equals("top")) { params.gravity = Gravity.TOP; } else if (value.equals("left")) { params.gravity = Gravity.LEFT; } else if (value.equals("right")) { params.gravity = Gravity.RIGHT; } setLayoutParams(params); } else if (key.equals("width")) { if (getParent() instanceof ScrollView) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); this.setLayoutParams(params); } else { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); if (value.equals("wrap-content")) { params.width = LinearLayout.LayoutParams.WRAP_CONTENT; } else if (value.equals("match-parent")) { params.width = LinearLayout.LayoutParams.MATCH_PARENT; } else { final float scale = getContext().getResources().getDisplayMetrics().density; int pixels = (int) (Integer.parseInt(value) * scale + 0.5f); params.width = pixels; } setLayoutParams(params); } } else if (key.equals("height")) { if (getParent() instanceof ScrollView) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); this.setLayoutParams(params); } else { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); if (value.equals("wrap-content")) { params.height = LinearLayout.LayoutParams.WRAP_CONTENT; } else if (value.equals("match-parent")) { params.height = LinearLayout.LayoutParams.MATCH_PARENT; } else { final float scale = getContext().getResources().getDisplayMetrics().density; int pixels = (int) (Integer.parseInt(value) * scale + 0.5f); params.height = pixels; } setLayoutParams(params); } } else if (key.equals("weight")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); params.weight = Integer.parseInt(value); setLayoutParams(params); } else if (key.equals("padding-top")) { setPadding(getPaddingLeft(), Integer.parseInt(value), getPaddingRight(), getPaddingBottom()); } else if (key.equals("padding-bottom")) { setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), Integer.parseInt(value)); } else if (key.equals("padding-left")) { setPadding(Integer.parseInt(value), getPaddingTop(), getPaddingRight(), getPaddingBottom()); } else if (key.equals("padding-right")) { setPadding(getPaddingLeft(), getPaddingTop(), Integer.parseInt(value), getPaddingBottom()); } else if (key.equals("frame")) { if (value.equals("light")) { this.setBackgroundDrawable(frame.getResources().getDrawable(android.R.drawable.dialog_holo_light_frame)); // this.setDividerDrawable(frame.getResources().getDrawable(android.R.drawable.divider_horizontal_bright)); } else if (value.equals("dark")) { this.setBackgroundDrawable(frame.getResources().getDrawable(android.R.drawable.alert_light_frame)); } } else if (key.equals("divider")) { if (value.equals("middle")) { this.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE); } else if (value.equals("end")) { this.setShowDividers(LinearLayout.SHOW_DIVIDER_END); } else if (value.equals("beginning")) { this.setShowDividers(LinearLayout.SHOW_DIVIDER_BEGINNING); } } else if (key.equals("background-color")) { this.setBackgroundColor(Color.parseColor(value)); } else if (key.equals("margin-right")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); params.rightMargin = Integer.parseInt(value); setLayoutParams(params); } else if (key.equals("margin-left")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); params.leftMargin = Integer.parseInt(value); setLayoutParams(params); } else if (key.equals("margin-top")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); params.topMargin = Integer.parseInt(value); setLayoutParams(params); } else if (key.equals("margin-bottom")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); params.bottomMargin = Integer.parseInt(value); setLayoutParams(params); } else if (key.equals("shadow")) { setElevation(Integer.parseInt(value)); } else if (key.equals("border")) { if (value.equals("none")) { setBackgroundResource(0); } else { GradientDrawable gd = new GradientDrawable(); gd.setColor(Color.parseColor("#ffffff")); // Changes this drawbale to use a single color instead of a gradient gd.setCornerRadius(5); gd.setStroke(1, Color.parseColor(value)); setBackgroundDrawable(gd); } } } @Override public void setError(boolean hasError, String errorText) { } @Override public void onScreenOrientationChange(boolean isLandscape) { invalidate(); } @Override public void addData(String text, int row, int column, int sheet) { System.out.println("FWLayout couldn't handle command"); } @Override public void setViewVisibility(boolean visibility) { if (visibility){ this.setVisibility(VISIBLE); } else { this.setVisibility(GONE); } } @Override public void clear() { System.out.println("couldn't handle command"); } @Override public void flush() { // TODO Auto-generated method stub } @Override public void addColumn(String text, int columnType) { // TODO Auto-generated method stub } @Override public void reshape(int value, int size) { if (size > getChildCount()) { System.out.println("FWLayout did nothing"); } ArrayList<View> viewsToBeRemoved = new ArrayList<View>(); for (int i = size; i < getChildCount(); i++) { View view = getChildAt(i); viewsToBeRemoved.add(view); } Iterator<View> i = viewsToBeRemoved.iterator(); while (i.hasNext()) { View v = i.next(); if (v instanceof FWImageView) { Bitmap drawable = ((BitmapDrawable) v.getBackground()).getBitmap(); if (drawable != null) { drawable.recycle(); } } frame.removeViewFromList(v.getId()); removeView(v); } } @Override public void setImage(byte[] bytes, int width, int height, Config config) { // TODO Auto-generated method stub } @Override public void reshape(int size) { ArrayList<View> viewsToBeRemoved = new ArrayList<View>(); for (int i = size; i < getChildCount(); i++) { View view = getChildAt(i); viewsToBeRemoved.add(view); } Iterator<View> i = viewsToBeRemoved.iterator(); while (i.hasNext()) { View v = i.next(); removeView(v); } } }
package com.intellij.compiler.server; import com.intellij.ProjectTopics; import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.CompilerConfigurationImpl; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.compiler.impl.CompilerUtil; import com.intellij.compiler.impl.javaCompiler.BackendCompiler; import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseCompilerConfiguration; import com.intellij.compiler.impl.javaCompiler.javac.JavacConfiguration; import com.intellij.compiler.server.impl.BuildProcessClasspathManager; import com.intellij.concurrency.JobScheduler; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionListener; import com.intellij.execution.ExecutionManager; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.ide.DataManager; import com.intellij.ide.PowerSaveMode; import com.intellij.ide.file.BatchFileChangeListener; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.application.*; import com.intellij.openapi.compiler.CompilationStatusListener; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompilerPaths; import com.intellij.openapi.compiler.CompilerTopics; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.*; import com.intellij.openapi.projectRoots.*; import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.openapi.roots.*; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.openapi.vfs.newvfs.impl.FileNameCache; import com.intellij.openapi.wm.IdeFrame; import com.intellij.util.*; import com.intellij.util.concurrency.SequentialTaskExecutor; import com.intellij.util.containers.IntArrayList; import com.intellij.util.io.BaseOutputReader; import com.intellij.util.io.PathKt; import com.intellij.util.io.storage.HeavyProcessLatch; import com.intellij.util.lang.JavaVersion; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.net.NetUtils; import com.intellij.util.text.DateFormatUtil; import gnu.trove.THashSet; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.handler.codec.protobuf.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder; import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import io.netty.util.internal.ThreadLocalRandom; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.ide.BuiltInServerManager; import org.jetbrains.ide.BuiltInServerManagerImpl; import org.jetbrains.io.ChannelRegistrar; import org.jetbrains.jps.api.*; import org.jetbrains.jps.cmdline.BuildMain; import org.jetbrains.jps.cmdline.ClasspathBootstrap; import org.jetbrains.jps.incremental.Utils; import org.jetbrains.jps.model.java.compiler.JavaCompilers; import javax.tools.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.text.SimpleDateFormat; import java.util.List; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.intellij.openapi.util.Pair.pair; import static org.jetbrains.jps.api.CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope; /** * @author Eugene Zhuravlev */ public final class BuildManager implements Disposable { public static final Key<Boolean> ALLOW_AUTOMAKE = Key.create("_allow_automake_when_process_is_active_"); private static final Key<Integer> COMPILER_PROCESS_DEBUG_PORT = Key.create("_compiler_process_debug_port_"); private static final Key<String> FORCE_MODEL_LOADING_PARAMETER = Key.create(BuildParametersKeys.FORCE_MODEL_LOADING); private static final Key<CharSequence> STDERR_OUTPUT = Key.create("_process_launch_errors_"); private static final SimpleDateFormat USAGE_STAMP_DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy"); private static final Logger LOG = Logger.getInstance(BuildManager.class); private static final String COMPILER_PROCESS_JDK_PROPERTY = "compiler.process.jdk"; public static final String SYSTEM_ROOT = "compile-server"; public static final String TEMP_DIR_NAME = "_temp_"; // do not make static in order not to access application on class load private final boolean IS_UNIT_TEST_MODE; private static final String IWS_EXTENSION = ".iws"; private static final String IPR_EXTENSION = ".ipr"; private static final String IDEA_PROJECT_DIR_PATTERN = "/.idea/"; private static final Function<String, Boolean> PATH_FILTER = SystemInfo.isFileSystemCaseSensitive ? s -> !(s.contains(IDEA_PROJECT_DIR_PATTERN) || s.endsWith(IWS_EXTENSION) || s.endsWith(IPR_EXTENSION)) : s -> !(StringUtil.endsWithIgnoreCase(s, IWS_EXTENSION) || StringUtil.endsWithIgnoreCase(s, IPR_EXTENSION) || StringUtil.containsIgnoreCase(s, IDEA_PROJECT_DIR_PATTERN)); private final List<String> myFallbackJdkParams = new SmartList<>(); private final Map<TaskFuture<?>, Project> myAutomakeFutures = Collections.synchronizedMap(new HashMap<>()); private final Map<String, RequestFuture<?>> myBuildsInProgress = Collections.synchronizedMap(new HashMap<>()); private final Map<String, Future<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>>> myPreloadedBuilds = Collections.synchronizedMap(new HashMap<>()); private final BuildProcessClasspathManager myClasspathManager = new BuildProcessClasspathManager(this); private final Executor myRequestsProcessor = SequentialTaskExecutor.createSequentialApplicationPoolExecutor( "BuildManager RequestProcessor Pool"); private final List<VFileEvent> myUnprocessedEvents = new ArrayList<>(); private final Executor myAutomakeTrigger = SequentialTaskExecutor.createSequentialApplicationPoolExecutor( "BuildManager Auto-Make Trigger"); private final Map<String, ProjectData> myProjectDataMap = Collections.synchronizedMap(new HashMap<>()); private volatile int myFileChangeCounter; private final BuildManagerPeriodicTask myAutoMakeTask = new BuildManagerPeriodicTask() { @Override protected int getDelay() { return Registry.intValue("compiler.automake.trigger.delay"); } @Override protected void runTask() { runAutoMake(); } @Override protected boolean shouldPostpone() { return shouldPostponeAutomake(); } }; private final BuildManagerPeriodicTask myDocumentSaveTask = new BuildManagerPeriodicTask() { @Override protected int getDelay() { return Registry.intValue("compiler.document.save.trigger.delay"); } @Override public void runTask() { if (shouldSaveDocuments()) { ApplicationManager.getApplication().invokeAndWait(() -> ((FileDocumentManagerImpl)FileDocumentManager.getInstance()).saveAllDocuments(false)); } } private boolean shouldSaveDocuments() { final Project contextProject = getCurrentContextProject(); return contextProject != null && canStartAutoMake(contextProject); } }; private final Runnable myGCTask = () -> { // todo: make customizable in UI? final int unusedThresholdDays = Registry.intValue("compiler.build.data.unused.threshold", -1); if (unusedThresholdDays <= 0) { return; } File buildSystemDir = getBuildSystemDirectory().toFile(); File[] dirs = buildSystemDir.listFiles(pathname -> pathname.isDirectory() && !TEMP_DIR_NAME.equals(pathname.getName())); if (dirs != null) { final Date now = new Date(); for (File buildDataProjectDir : dirs) { File usageFile = getUsageFile(buildDataProjectDir); if (usageFile.exists()) { final Pair<Date, File> usageData = readUsageFile(usageFile); if (usageData != null) { final File projectFile = usageData.second; if (projectFile != null && !projectFile.exists() || DateFormatUtil.getDifferenceInDays(usageData.first, now) > unusedThresholdDays) { LOG.info("Clearing project build data because the project does not exist or was not opened for more than " + unusedThresholdDays + " days: " + buildDataProjectDir); FileUtil.delete(buildDataProjectDir); } } } else { updateUsageFile(null, buildDataProjectDir); // set usage stamp to start countdown } } } }; private final ChannelRegistrar myChannelRegistrar = new ChannelRegistrar(); private final BuildMessageDispatcher myMessageDispatcher = new BuildMessageDispatcher(); private volatile int myListenPort = -1; @NotNull private final Charset mySystemCharset = CharsetToolkit.getDefaultSystemCharset(); private volatile boolean myBuildProcessDebuggingEnabled; public BuildManager() { final Application application = ApplicationManager.getApplication(); IS_UNIT_TEST_MODE = application.isUnitTestMode(); final String fallbackSdkHome = getFallbackSdkHome(); if (fallbackSdkHome != null) { myFallbackJdkParams.add("-D" + GlobalOptions.FALLBACK_JDK_HOME + "=" + fallbackSdkHome); myFallbackJdkParams.add("-D" + GlobalOptions.FALLBACK_JDK_VERSION + "=" + SystemInfo.JAVA_VERSION); } MessageBusConnection connection = application.getMessageBus().connect(this); connection.subscribe(ProjectManager.TOPIC, new ProjectWatcher()); connection.subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() { @Override public void after(@NotNull List<? extends VFileEvent> events) { if (!IS_UNIT_TEST_MODE) { synchronized (myUnprocessedEvents) { myUnprocessedEvents.addAll(events); } myAutomakeTrigger.execute(() -> { if (!application.isDisposed()) { ReadAction.run(()-> { if (application.isDisposed()) return; final List<VFileEvent> snapshot; synchronized (myUnprocessedEvents) { if (myUnprocessedEvents.isEmpty()) { return; } snapshot = new ArrayList<>(myUnprocessedEvents); myUnprocessedEvents.clear(); } if (shouldTriggerMake(snapshot)) { scheduleAutoMake(); } }); } else { synchronized (myUnprocessedEvents) { myUnprocessedEvents.clear(); } } }); } } private boolean shouldTriggerMake(List<? extends VFileEvent> events) { if (PowerSaveMode.isEnabled()) { return false; } Project project = null; ProjectFileIndex fileIndex = null; for (VFileEvent event : events) { final VirtualFile eventFile = event.getFile(); if (eventFile == null) { continue; } if (!eventFile.isValid()) { return true; // should be deleted } if (project == null) { // lazy init project = getCurrentContextProject(); if (project == null) { return false; } fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); } if (fileIndex.isInContent(eventFile)) { if (ProjectUtil.isProjectOrWorkspaceFile(eventFile) || GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(eventFile, project)) { // changes in project files or generated stuff should not trigger auto-make continue; } return true; } } return false; } }); connection.subscribe(BatchFileChangeListener.TOPIC, new BatchFileChangeListener() { @Override public void batchChangeStarted(@NotNull Project project, @Nullable String activityName) { myFileChangeCounter++; cancelAutoMakeTasks(project); } @Override public void batchChangeCompleted(@NotNull Project project) { myFileChangeCounter } }); ShutDownTracker.getInstance().registerShutdownTask(this::stopListening); if (!IS_UNIT_TEST_MODE) { ScheduledFuture<?> future = JobScheduler.getScheduler().scheduleWithFixedDelay(() -> runCommand(myGCTask), 3, 180, TimeUnit.MINUTES); Disposer.register(this, () -> future.cancel(false)); } } @Nullable private static String getFallbackSdkHome() { String home = SystemProperties.getJavaHome(); // should point either to jre or jdk if (home == null) return null; if (!JdkUtil.checkForJdk(home)) { String parent = new File(home).getParent(); if (parent != null && JdkUtil.checkForJdk(parent)) { home = parent; } } return FileUtil.toSystemIndependentName(home); } @NotNull private static List<Project> getOpenProjects() { final Project[] projects = ProjectManager.getInstance().getOpenProjects(); if (projects.length == 0) { return Collections.emptyList(); } final List<Project> projectList = new SmartList<>(); for (Project project : projects) { if (isValidProject(project)) { projectList.add(project); } } return projectList; } private static boolean isValidProject(@Nullable Project project) { return project != null && !project.isDisposed() && !project.isDefault() && project.isInitialized(); } public static BuildManager getInstance() { return ServiceManager.getService(BuildManager.class); } public void notifyFilesChanged(final Collection<? extends File> paths) { doNotify(paths, false); } public void notifyFilesDeleted(Collection<? extends File> paths) { doNotify(paths, true); } public void runCommand(@NotNull Runnable command) { myRequestsProcessor.execute(command); } private void doNotify(final Collection<? extends File> paths, final boolean notifyDeletion) { // ensure events processed in the order they arrived runCommand(() -> { final List<String> filtered = new ArrayList<>(paths.size()); for (File file : paths) { final String path = FileUtil.toSystemIndependentName(file.getPath()); if (PATH_FILTER.fun(path)) { filtered.add(path); } } if (filtered.isEmpty()) { return; } synchronized (myProjectDataMap) { //if (IS_UNIT_TEST_MODE) { // if (notifyDeletion) { // LOG.info("Registering deleted paths: " + filtered); // else { // LOG.info("Registering changed paths: " + filtered); for (Map.Entry<String, ProjectData> entry : myProjectDataMap.entrySet()) { final ProjectData data = entry.getValue(); if (notifyDeletion) { data.addDeleted(filtered); } else { data.addChanged(filtered); } RequestFuture<?> future = myBuildsInProgress.get(entry.getKey()); if (future != null && !future.isCancelled() && !future.isDone()) { final UUID sessionId = future.getRequestID(); final Channel channel = myMessageDispatcher.getConnectedChannel(sessionId); if (channel != null) { final CmdlineRemoteProto.Message.ControllerMessage message = CmdlineRemoteProto.Message.ControllerMessage.newBuilder().setType( CmdlineRemoteProto.Message.ControllerMessage.Type.FS_EVENT).setFsEvent(data.createNextEvent()).build(); channel.writeAndFlush(CmdlineProtoUtil.toMessage(sessionId, message)); } } } } }); } public static void forceModelLoading(CompileContext context) { context.getCompileScope().putUserData(FORCE_MODEL_LOADING_PARAMETER, Boolean.TRUE.toString()); } public void clearState(Project project) { final String projectPath = getProjectPath(project); cancelPreloadedBuilds(projectPath); synchronized (myProjectDataMap) { final ProjectData data = myProjectDataMap.get(projectPath); if (data != null) { data.dropChanges(); } } scheduleAutoMake(); } public void clearState() { final boolean cleared; synchronized (myProjectDataMap) { cleared = !myProjectDataMap.isEmpty(); for (Map.Entry<String, ProjectData> entry : myProjectDataMap.entrySet()) { cancelPreloadedBuilds(entry.getKey()); entry.getValue().dropChanges(); } } if (cleared) { scheduleAutoMake(); } } public boolean isProjectWatched(Project project) { return myProjectDataMap.containsKey(getProjectPath(project)); } @Nullable public List<String> getFilesChangedSinceLastCompilation(Project project) { String projectPath = getProjectPath(project); synchronized (myProjectDataMap) { ProjectData data = myProjectDataMap.get(projectPath); if (data != null && !data.myNeedRescan) { return convertToStringPaths(data.myChanged); } return null; } } private static List<String> convertToStringPaths(final Collection<? extends InternedPath> interned) { final ArrayList<String> list = new ArrayList<>(interned.size()); for (InternedPath path : interned) { list.add(path.getValue()); } return list; } @Nullable private static String getProjectPath(final Project project) { final String url = project.getPresentableUrl(); if (url == null) { return null; } return VirtualFileManager.extractPath(url); } public void scheduleAutoMake() { if (!IS_UNIT_TEST_MODE && !PowerSaveMode.isEnabled()) { if (LOG.isDebugEnabled()) { LOG.debug("Automake scheduled:\n" + getThreadTrace(Thread.currentThread(), 10)); } myAutoMakeTask.schedule(); } } @NotNull private static String getThreadTrace(Thread thread, final int depth) { // debugging final StringBuilder buf = new StringBuilder(); final StackTraceElement[] trace = thread.getStackTrace(); for (int i = 0; i < depth && i < trace.length; i++) { final StackTraceElement element = trace[i]; buf.append("\tat ").append(element).append("\n"); } return buf.toString(); } private void scheduleProjectSave() { if (!IS_UNIT_TEST_MODE && !PowerSaveMode.isEnabled()) { if (LOG.isDebugEnabled()) { LOG.debug("Automake canceled; reason: project save scheduled"); } myAutoMakeTask.cancelPendingExecution(); myDocumentSaveTask.schedule(); } } private void runAutoMake() { final Project project = getCurrentContextProject(); if (project == null || !canStartAutoMake(project)) { return; } final List<TargetTypeBuildScope> scopes = CmdlineProtoUtil.createAllModulesScopes(false); final AutoMakeMessageHandler handler = new AutoMakeMessageHandler(project); final TaskFuture<?> future = scheduleBuild( project, false, true, false, scopes, Collections.emptyList(), Collections.singletonMap(BuildParametersKeys.IS_AUTOMAKE, "true"), handler ); if (future != null) { myAutomakeFutures.put(future, project); try { future.waitFor(); } finally { myAutomakeFutures.remove(future); if (handler.unprocessedFSChangesDetected()) { scheduleAutoMake(); } } } } private static boolean canStartAutoMake(@NotNull Project project) { if (project.isDisposed()) { return false; } final CompilerWorkspaceConfiguration config = CompilerWorkspaceConfiguration.getInstance(project); if (!config.MAKE_PROJECT_ON_SAVE) { return false; } return config.allowAutoMakeWhileRunningApplication() || !hasRunningProcess(project); } private static boolean shouldPostponeAutomake() { // Heuristics for postpone-decision: // 1. There are unsaved documents OR // 2. The IDE is not idle: the last activity happened less than 3 seconds ago (registry-configurable) if (FileDocumentManager.getInstance().getUnsavedDocuments().length > 0) { return true; } final long threshold = Registry.intValue("compiler.automake.postpone.when.idle.less.than", 3000); // todo: UI option instead of registry? final long idleSinceLastActivity = ApplicationManager.getApplication().getIdleTime(); return idleSinceLastActivity < threshold; } @Nullable private static Project getCurrentContextProject() { final List<Project> openProjects = getOpenProjects(); if (openProjects.isEmpty()) { return null; } if (openProjects.size() == 1) { return openProjects.get(0); } Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); if (window == null) { return null; } Component comp = window; while (true) { final Container _parent = comp.getParent(); if (_parent == null) { break; } comp = _parent; } Project project = null; if (comp instanceof IdeFrame) { project = ((IdeFrame)comp).getProject(); } if (project == null) { project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(comp)); } return isValidProject(project)? project : null; } private static boolean hasRunningProcess(@NotNull Project project) { for (ProcessHandler handler : ExecutionManager.getInstance(project).getRunningProcesses()) { if (!handler.isProcessTerminated() && !ALLOW_AUTOMAKE.get(handler, Boolean.FALSE)) { // active process return true; } } return false; } @NotNull public Collection<TaskFuture<?>> cancelAutoMakeTasks(@NotNull Project project) { final Collection<TaskFuture<?>> futures = new SmartList<>(); synchronized (myAutomakeFutures) { for (Map.Entry<TaskFuture<?>, Project> entry : myAutomakeFutures.entrySet()) { if (entry.getValue().equals(project)) { TaskFuture<?> future = entry.getKey(); future.cancel(false); futures.add(future); } } } if (LOG.isDebugEnabled() && !futures.isEmpty()) { LOG.debug("Automake cancel (all tasks):\n" + getThreadTrace(Thread.currentThread(), 10)); } return futures; } private void cancelAllPreloadedBuilds() { String[] paths = ArrayUtilRt.toStringArray(myPreloadedBuilds.keySet()); for (String path : paths) { cancelPreloadedBuilds(path); } } private void cancelPreloadedBuilds(final String projectPath) { if (LOG.isDebugEnabled()) { LOG.debug("Cancel preloaded build for " + projectPath + "\n" + getThreadTrace(Thread.currentThread(), 50)); } runCommand(() -> { Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> pair = takePreloadedProcess(projectPath); if (pair != null) { final RequestFuture<PreloadedProcessMessageHandler> future = pair.first; final OSProcessHandler processHandler = pair.second; myMessageDispatcher.cancelSession(future.getRequestID()); // waiting for preloaded process from project's task queue guarantees no build is started for this project // until this one gracefully exits and closes all its storages getProjectData(projectPath).taskQueue.execute(() -> { Throwable error = null; try { while (!processHandler.waitFor()) { LOG.info("processHandler.waitFor() returned false for session " + future.getRequestID() + ", continue waiting"); } } catch (Throwable e) { error = e; } finally { notifySessionTerminationIfNeeded(future.getRequestID(), error); } }); } }); } @Nullable private Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> takePreloadedProcess(String projectPath) { Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> result; final Future<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>> preloadProgress = myPreloadedBuilds.remove(projectPath); try { result = preloadProgress != null ? preloadProgress.get() : null; } catch (Throwable e) { LOG.info(e); result = null; } return result != null && !result.first.isDone()? result : null; } @Nullable public TaskFuture<?> scheduleBuild( final Project project, final boolean isRebuild, final boolean isMake, final boolean onlyCheckUpToDate, final List<TargetTypeBuildScope> scopes, final Collection<String> paths, final Map<String, String> userData, final DefaultMessageHandler messageHandler) { final String projectPath = getProjectPath(project); final boolean isAutomake = messageHandler instanceof AutoMakeMessageHandler; final BuilderMessageHandler handler = new NotifyingMessageHandler(project, messageHandler, isAutomake); try { ensureListening(); } catch (Exception e) { final UUID sessionId = UUID.randomUUID(); // the actual session did not start, use random UUID handler.handleFailure(sessionId, CmdlineProtoUtil.createFailure(e.getMessage(), null)); handler.sessionTerminated(sessionId); return null; } final DelegateFuture _future = new DelegateFuture(); // by using the same queue that processes events we ensure that // the build will be aware of all events that have happened before this request runCommand(() -> { final Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> preloaded = takePreloadedProcess(projectPath); final RequestFuture<PreloadedProcessMessageHandler> preloadedFuture = Pair.getFirst(preloaded); final boolean usingPreloadedProcess = preloadedFuture != null; final UUID sessionId; if (usingPreloadedProcess) { LOG.info("Using preloaded build process to compile " + projectPath); sessionId = preloadedFuture.getRequestID(); preloadedFuture.getMessageHandler().setDelegateHandler(handler); } else { sessionId = UUID.randomUUID(); } final RequestFuture<? extends BuilderMessageHandler> future = usingPreloadedProcess? preloadedFuture : new RequestFuture<>(handler, sessionId, new CancelBuildSessionAction<>()); // futures we need to wait for: either just "future" or both "future" and "buildFuture" below TaskFuture<?>[] delegatesToWait = {future}; if (!usingPreloadedProcess && (future.isCancelled() || project.isDisposed())) { // in case of preloaded process the process was already running, so the handler will be notified upon process termination handler.sessionTerminated(sessionId); future.setDone(); } else { final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals = CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings.newBuilder().setGlobalOptionsPath(PathManager.getOptionsPath()) .build(); CmdlineRemoteProto.Message.ControllerMessage.FSEvent currentFSChanges; final ExecutorService projectTaskQueue; final boolean needRescan; synchronized (myProjectDataMap) { final ProjectData data = getProjectData(projectPath); if (isRebuild) { data.dropChanges(); } if (IS_UNIT_TEST_MODE) { LOG.info("Scheduling build for " + projectPath + "; CHANGED: " + new HashSet<>(convertToStringPaths(data.myChanged)) + "; DELETED: " + new HashSet<>(convertToStringPaths(data.myDeleted))); } needRescan = data.getAndResetRescanFlag(); currentFSChanges = needRescan ? null : data.createNextEvent(); projectTaskQueue = data.taskQueue; } final CmdlineRemoteProto.Message.ControllerMessage params; if (isRebuild) { params = CmdlineProtoUtil.createBuildRequest(projectPath, scopes, Collections.emptyList(), userData, globals, null); } else if (onlyCheckUpToDate) { params = CmdlineProtoUtil.createUpToDateCheckRequest(projectPath, scopes, paths, userData, globals, currentFSChanges); } else { params = CmdlineProtoUtil.createBuildRequest(projectPath, scopes, isMake ? Collections.emptyList() : paths, userData, globals, currentFSChanges); } if (!usingPreloadedProcess) { myMessageDispatcher.registerBuildMessageHandler(future, params); } try { Future<?> buildFuture = projectTaskQueue.submit(() -> { Throwable execFailure = null; try { if (project.isDisposed()) { if (usingPreloadedProcess) { future.cancel(false); } else { return; } } myBuildsInProgress.put(projectPath, future); final OSProcessHandler processHandler; CharSequence errorsOnLaunch; if (usingPreloadedProcess) { final boolean paramsSent = myMessageDispatcher.sendBuildParameters(future.getRequestID(), params); if (!paramsSent) { myMessageDispatcher.cancelSession(future.getRequestID()); } processHandler = preloaded.second; errorsOnLaunch = STDERR_OUTPUT.get(processHandler); } else { if (isAutomake && needRescan) { // if project state was cleared because of roots changed or this is the first compilation after project opening, // ensure project model is saved on disk, so that automake sees the latest model state. // For ordinary make all project, app settings and unsaved docs are always saved before build starts. try { ApplicationManager.getApplication().invokeAndWait(project::save); } catch (Throwable e) { LOG.info(e); } } processHandler = launchBuildProcess(project, myListenPort, sessionId, false); errorsOnLaunch = new StringBuffer(); processHandler.addProcessListener(new StdOutputCollector((StringBuffer)errorsOnLaunch)); processHandler.startNotify(); } Integer debugPort = processHandler.getUserData(COMPILER_PROCESS_DEBUG_PORT); if (debugPort != null) { String message = "Build: waiting for debugger connection on port " + debugPort; messageHandler .handleCompileMessage(sessionId, CmdlineProtoUtil.createCompileProgressMessageResponse(message).getCompileMessage()); } while (!processHandler.waitFor()) { LOG.info("processHandler.waitFor() returned false for session " + sessionId + ", continue waiting"); } final int exitValue = processHandler.getProcess().exitValue(); if (exitValue != 0) { final StringBuilder msg = new StringBuilder(); msg.append("Abnormal build process termination: "); if (errorsOnLaunch != null && errorsOnLaunch.length() > 0) { msg.append("\n").append(errorsOnLaunch); if (StringUtil.contains(errorsOnLaunch, "java.lang.NoSuchMethodError")) { msg.append( "\nThe error may be caused by JARs in Java Extensions directory which conflicts with libraries used by the external build process.") .append( "\nTry adding -Djava.ext.dirs=\"\" argument to 'Build process VM options' in File | Settings | Build, Execution, Deployment | Compiler to fix the problem."); } } else { msg.append("unknown error"); } handler.handleFailure(sessionId, CmdlineProtoUtil.createFailure(msg.toString(), null)); } } catch (Throwable e) { execFailure = e; } finally { myBuildsInProgress.remove(projectPath); notifySessionTerminationIfNeeded(sessionId, execFailure); if (isProcessPreloadingEnabled(project)) { runCommand(() -> { if (!myPreloadedBuilds.containsKey(projectPath)) { try { final Future<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>> preloadResult = launchPreloadedBuildProcess(project, projectTaskQueue); myPreloadedBuilds.put(projectPath, preloadResult); } catch (Throwable e) { LOG.info("Error pre-loading build process for project " + projectPath, e); } } }); } } }); delegatesToWait = new TaskFuture[]{future, new TaskFutureAdapter<>(buildFuture)}; } catch (Throwable e) { handleProcessExecutionFailure(sessionId, e); } } boolean set = _future.setDelegates(delegatesToWait); assert set; }); return _future; } private boolean isProcessPreloadingEnabled(Project project) { // automatically disable process preloading when debugging or testing if (IS_UNIT_TEST_MODE || !Registry.is("compiler.process.preload") || myBuildProcessDebuggingEnabled) { return false; } if (project.isDisposed()) { return true; } for (BuildProcessParametersProvider provider : BuildProcessParametersProvider.EP_NAME.getExtensionList(project)) { if (!provider.isProcessPreloadingEnabled()) { return false; } } return true; } private void notifySessionTerminationIfNeeded(@NotNull UUID sessionId, @Nullable Throwable execFailure) { if (myMessageDispatcher.getAssociatedChannel(sessionId) == null) { // either the connection has never been established (process not started or execution failed), or no messages were sent from the launched process. // in this case the session cannot be unregistered by the message dispatcher final BuilderMessageHandler unregistered = myMessageDispatcher.unregisterBuildMessageHandler(sessionId); if (unregistered != null) { if (execFailure != null) { unregistered.handleFailure(sessionId, CmdlineProtoUtil.createFailure(execFailure.getMessage(), execFailure)); } unregistered.sessionTerminated(sessionId); } } } private void handleProcessExecutionFailure(@NotNull UUID sessionId, Throwable e) { final BuilderMessageHandler unregistered = myMessageDispatcher.unregisterBuildMessageHandler(sessionId); if (unregistered != null) { unregistered.handleFailure(sessionId, CmdlineProtoUtil.createFailure(e.getMessage(), e)); unregistered.sessionTerminated(sessionId); } } @NotNull private ProjectData getProjectData(String projectPath) { synchronized (myProjectDataMap) { return myProjectDataMap.computeIfAbsent(projectPath, k -> new ProjectData( SequentialTaskExecutor.createSequentialApplicationPoolExecutor("BuildManager Pool"))); } } private void ensureListening() { if (myListenPort < 0) { synchronized (this) { if (myListenPort < 0) { myListenPort = startListening(); } } } } @Override public void dispose() { stopListening(); } @NotNull public static Pair<Sdk, JavaSdkVersion> getBuildProcessRuntimeSdk(@NotNull Project project) { return getRuntimeSdk(project, 8); } @NotNull public static Pair<Sdk, JavaSdkVersion> getJavacRuntimeSdk(@NotNull Project project) { return getRuntimeSdk(project, 6); } private static Pair<Sdk, JavaSdkVersion> getRuntimeSdk(Project project, int oldestPossibleVersion) { final Set<Sdk> candidates = new LinkedHashSet<>(); final Sdk defaultSdk = ProjectRootManager.getInstance(project).getProjectSdk(); if (defaultSdk != null && defaultSdk.getSdkType() instanceof JavaSdkType) { candidates.add(defaultSdk); } for (Module module : ModuleManager.getInstance(project).getModules()) { final Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) { candidates.add(sdk); } } // now select the latest version from the sdks that are used in the project, but not older than the internal sdk version final JavaSdk javaSdkType = JavaSdk.getInstance(); return candidates.stream() .map(sdk -> pair(sdk, JavaVersion.tryParse(sdk.getVersionString()))) .filter(p -> p.second != null && p.second.isAtLeast(oldestPossibleVersion)) .max(Comparator.comparing(p -> p.second)) .map(p -> pair(p.first, JavaSdkVersion.fromJavaVersion(p.second))) .orElseGet(() -> { Sdk internalJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); return pair(internalJdk, javaSdkType.getVersion(internalJdk)); }); } private Future<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>> launchPreloadedBuildProcess(final Project project, ExecutorService projectTaskQueue) { ensureListening(); // launching build process from projectTaskQueue ensures that no other build process for this project is currently running return projectTaskQueue.submit(() -> { if (project.isDisposed()) { return null; } final RequestFuture<PreloadedProcessMessageHandler> future = new RequestFuture<>(new PreloadedProcessMessageHandler(), UUID.randomUUID(), new CancelBuildSessionAction<>()); try { myMessageDispatcher.registerBuildMessageHandler(future, null); final OSProcessHandler processHandler = launchBuildProcess(project, myListenPort, future.getRequestID(), true); final StringBuffer errors = new StringBuffer(); processHandler.addProcessListener(new StdOutputCollector(errors)); STDERR_OUTPUT.set(processHandler, errors); processHandler.startNotify(); return Pair.create(future, processHandler); } catch (Throwable e) { handleProcessExecutionFailure(future.getRequestID(), e); throw e instanceof Exception? (Exception)e : new RuntimeException(e); } }); } private OSProcessHandler launchBuildProcess(@NotNull Project project, final int port, @NotNull UUID sessionId, boolean requestProjectPreload) throws ExecutionException { String compilerPath; final String vmExecutablePath; JavaSdkVersion sdkVersion = null; final String forcedCompiledJdkHome = Registry.stringValue(COMPILER_PROCESS_JDK_PROPERTY); if (StringUtil.isEmptyOrSpaces(forcedCompiledJdkHome)) { // choosing sdk with which the build process should be run final Pair<Sdk, JavaSdkVersion> pair = getBuildProcessRuntimeSdk(project); final Sdk projectJdk = pair.first; sdkVersion = pair.second; final Sdk internalJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); // validate tools.jar presence final JavaSdkType projectJdkType = (JavaSdkType)projectJdk.getSdkType(); if (FileUtil.pathsEqual(projectJdk.getHomePath(), internalJdk.getHomePath())) { // important: because internal JDK can be either JDK or JRE, // this is the most universal way to obtain tools.jar path in this particular case final JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler(); if (systemCompiler == null) { //temporary workaround for IDEA-169747 try { compilerPath = ClasspathBootstrap.getResourcePath(Class.forName("com.sun.tools.javac.api.JavacTool", false, BuildManager.class.getClassLoader())); } catch (Throwable t) { LOG.info(t); compilerPath = null; } if (compilerPath == null) { throw new ExecutionException("No system java compiler is provided by the JRE. Make sure tools.jar is present in IntelliJ IDEA classpath."); } } else { compilerPath = ClasspathBootstrap.getResourcePath(systemCompiler.getClass()); } } else { compilerPath = projectJdkType.getToolsPath(projectJdk); if (compilerPath == null && !JavaSdkUtil.isJdkAtLeast(projectJdk, JavaSdkVersion.JDK_1_9)) { throw new ExecutionException("Cannot determine path to 'tools.jar' library for " + projectJdk.getName() + " (" + projectJdk.getHomePath() + ")"); } } vmExecutablePath = projectJdkType.getVMExecutablePath(projectJdk); } else { compilerPath = new File(forcedCompiledJdkHome, "lib/tools.jar").getAbsolutePath(); vmExecutablePath = new File(forcedCompiledJdkHome, "bin/java").getAbsolutePath(); } final CompilerConfiguration projectConfig = CompilerConfiguration.getInstance(project); final CompilerWorkspaceConfiguration config = CompilerWorkspaceConfiguration.getInstance(project); final GeneralCommandLine cmdLine = new GeneralCommandLine(); cmdLine.setExePath(vmExecutablePath); boolean isProfilingMode = false; String userDefinedHeapSize = null; final List<String> userAdditionalOptionsList = new SmartList<>(); final String userAdditionalVMOptions = config.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS; final boolean userLocalOptionsActive = !StringUtil.isEmptyOrSpaces(userAdditionalVMOptions); final String additionalOptions = userLocalOptionsActive ? userAdditionalVMOptions : projectConfig.getBuildProcessVMOptions(); if (!StringUtil.isEmptyOrSpaces(additionalOptions)) { final StringTokenizer tokenizer = new StringTokenizer(additionalOptions, " ", false); while (tokenizer.hasMoreTokens()) { final String option = tokenizer.nextToken(); if (StringUtil.startsWithIgnoreCase(option, "-Xmx")) { if (userLocalOptionsActive) { userDefinedHeapSize = option; } } else { if ("-Dprofiling.mode=true".equals(option)) { isProfilingMode = true; } userAdditionalOptionsList.add(option); } } } if (userDefinedHeapSize != null) { cmdLine.addParameter(userDefinedHeapSize); } else { final int heapSize = projectConfig.getBuildProcessHeapSize(JavacConfiguration.getOptions(project, JavacConfiguration.class).MAXIMUM_HEAP_SIZE); cmdLine.addParameter("-Xmx" + heapSize + "m"); } if (SystemInfo.isMac && sdkVersion != null && JavaSdkVersion.JDK_1_6.equals(sdkVersion) && Registry.is("compiler.process.32bit.vm.on.mac")) { // unfortunately -d32 is supported on jdk 1.6 only cmdLine.addParameter("-d32"); } cmdLine.addParameter("-Djava.awt.headless=true"); if (sdkVersion != null && sdkVersion.ordinal() < JavaSdkVersion.JDK_1_9.ordinal()) { //-Djava.endorsed.dirs is not supported in JDK 9+, may result in abnormal process termination cmdLine.addParameter("-Djava.endorsed.dirs=\"\""); // turn off all jre customizations for predictable behaviour } if (IS_UNIT_TEST_MODE) { cmdLine.addParameter("-Dtest.mode=true"); } cmdLine.addParameter("-Djdt.compiler.useSingleThread=true"); // always run eclipse compiler in single-threaded mode if (requestProjectPreload) { cmdLine.addParameter("-Dpreload.project.path=" + FileUtil.toCanonicalPath(getProjectPath(project))); cmdLine.addParameter("-Dpreload.config.path=" + FileUtil.toCanonicalPath(PathManager.getOptionsPath())); } if (ProjectUtilCore.isExternalStorageEnabled(project)) { cmdLine.addParameter("-D" + GlobalOptions.EXTERNAL_PROJECT_CONFIG + "=" + ProjectUtil.getExternalConfigurationDir(project)); } final String shouldGenerateIndex = System.getProperty(GlobalOptions.GENERATE_CLASSPATH_INDEX_OPTION); if (shouldGenerateIndex != null) { cmdLine.addParameter("-D"+ GlobalOptions.GENERATE_CLASSPATH_INDEX_OPTION +"=" + shouldGenerateIndex); } cmdLine.addParameter("-D" + GlobalOptions.COMPILE_PARALLEL_OPTION + "=" + config.PARALLEL_COMPILATION); if (config.PARALLEL_COMPILATION) { final boolean allowParallelAutomake = Registry.is("compiler.automake.allow.parallel", true); if (!allowParallelAutomake) { cmdLine.addParameter("-D" + GlobalOptions.ALLOW_PARALLEL_AUTOMAKE_OPTION + "=false"); } } cmdLine.addParameter("-D" + GlobalOptions.REBUILD_ON_DEPENDENCY_CHANGE_OPTION + "=" + config.REBUILD_ON_DEPENDENCY_CHANGE); if (Registry.is("compiler.build.report.statistics")) { cmdLine.addParameter("-D" + GlobalOptions.REPORT_BUILD_STATISTICS + "=true"); } if (Boolean.TRUE.equals(Boolean.valueOf(System.getProperty("java.net.preferIPv4Stack", "false")))) { cmdLine.addParameter("-Djava.net.preferIPv4Stack=true"); } // this will make netty initialization faster on some systems cmdLine.addParameter("-Dio.netty.initialSeedUniquifier=" + ThreadLocalRandom.getInitialSeedUniquifier()); for (String option : userAdditionalOptionsList) { cmdLine.addParameter(option); } if (isProfilingMode) { cmdLine.addParameter("-agentlib:yjpagent=disablealloc,delay=10000,sessionname=ExternalBuild"); } // debugging int debugPort = -1; if (myBuildProcessDebuggingEnabled) { debugPort = Registry.intValue("compiler.process.debug.port"); if (debugPort <= 0) { try { debugPort = NetUtils.findAvailableSocketPort(); } catch (IOException e) { throw new ExecutionException("Cannot find free port to debug build process", e); } } if (debugPort > 0) { cmdLine.addParameter("-XX:+HeapDumpOnOutOfMemoryError"); cmdLine.addParameter("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + debugPort); } } if (Registry.is("compiler.build.portable.caches")) { cmdLine.addParameter("-Didea.resizeable.file.truncate.on.close=true"); cmdLine.addParameter("-Dkotlin.jps.non.caching.storage=true"); cmdLine.addParameter("-Dorg.jetbrains.jps.portable.caches=true"); } // javac's VM should use the same default locale that IDEA uses in order for javac to print messages in 'correct' language cmdLine.setCharset(mySystemCharset); cmdLine.addParameter("-D" + CharsetToolkit.FILE_ENCODING_PROPERTY + "=" + mySystemCharset.name()); String[] propertiesToPass = {"user.language", "user.country", "user.region", PathManager.PROPERTY_PATHS_SELECTOR, "idea.case.sensitive.fs"}; for (String name : propertiesToPass) { final String value = System.getProperty(name); if (value != null) { cmdLine.addParameter("-D" + name + "=" + value); } } cmdLine.addParameter("-D" + PathManager.PROPERTY_HOME_PATH + "=" + PathManager.getHomePath()); cmdLine.addParameter("-D" + PathManager.PROPERTY_CONFIG_PATH + "=" + PathManager.getConfigPath()); cmdLine.addParameter("-D" + PathManager.PROPERTY_PLUGINS_PATH + "=" + PathManager.getPluginsPath()); cmdLine.addParameter("-D" + GlobalOptions.LOG_DIR_OPTION + "=" + FileUtil.toSystemIndependentName(getBuildLogDirectory().getAbsolutePath())); cmdLine.addParameters(myFallbackJdkParams); cmdLine.addParameter("-Dio.netty.noUnsafe=true"); final Path workDirectory = getBuildSystemDirectory(); try { Files.createDirectories(workDirectory); } catch (IOException e) { LOG.warn(e); } final File projectSystemRoot = getProjectSystemDirectory(project); if (projectSystemRoot != null) { cmdLine.addParameter("-Djava.io.tmpdir=" + FileUtil.toSystemIndependentName(projectSystemRoot.getPath()) + "/" + TEMP_DIR_NAME); } for (BuildProcessParametersProvider provider : BuildProcessParametersProvider.EP_NAME.getExtensionList(project)) { final List<String> args = provider.getVMArguments(); cmdLine.addParameters(args); } @SuppressWarnings("UnnecessaryFullyQualifiedName") final Class<?> launcherClass = org.jetbrains.jps.cmdline.Launcher.class; final List<String> launcherCp = new ArrayList<>(); launcherCp.add(ClasspathBootstrap.getResourcePath(launcherClass)); launcherCp.addAll(BuildProcessClasspathManager.getLauncherClasspath(project)); if (compilerPath != null) { // can be null in case of jdk9 launcherCp.add(compilerPath); } boolean includeBundledEcj = shouldIncludeEclipseCompiler(projectConfig); File customEcjPath = null; if (includeBundledEcj) { final String path = EclipseCompilerConfiguration.getOptions(project, EclipseCompilerConfiguration.class).ECJ_TOOL_PATH; if (!StringUtil.isEmptyOrSpaces(path)) { customEcjPath = new File(path); if (customEcjPath.exists()) { includeBundledEcj = false; } else { throw new ExecutionException("Path to eclipse ecj compiler does not exist: " + customEcjPath.getAbsolutePath()); //customEcjPath = null; } } } ClasspathBootstrap.appendJavaCompilerClasspath(launcherCp, includeBundledEcj); if (customEcjPath != null) { launcherCp.add(customEcjPath.getAbsolutePath()); } cmdLine.addParameter("-classpath"); cmdLine.addParameter(classpathToString(launcherCp)); cmdLine.addParameter(launcherClass.getName()); final List<String> cp = ClasspathBootstrap.getBuildProcessApplicationClasspath(); cp.addAll(myClasspathManager.getBuildProcessPluginsClasspath(project)); if (isProfilingMode) { cp.add(workDirectory.resolve("yjp-controller-api-redist.jar").toString()); } cmdLine.addParameter(classpathToString(cp)); cmdLine.addParameter(BuildMain.class.getName()); cmdLine.addParameter(Boolean.valueOf(System.getProperty("java.net.preferIPv6Addresses", "false"))? "::1" : "127.0.0.1"); cmdLine.addParameter(Integer.toString(port)); cmdLine.addParameter(sessionId.toString()); cmdLine.addParameter(PathKt.getSystemIndependentPath(workDirectory)); cmdLine.setWorkDirectory(workDirectory.toFile()); try { ApplicationManager.getApplication().getMessageBus().syncPublisher(BuildManagerListener.TOPIC).beforeBuildProcessStarted(project, sessionId); } catch (Throwable e) { LOG.error(e); } final OSProcessHandler processHandler = new OSProcessHandler(cmdLine) { @Override protected boolean shouldDestroyProcessRecursively() { return true; } @NotNull @Override protected BaseOutputReader.Options readerOptions() { return BaseOutputReader.Options.BLOCKING; } }; processHandler.addProcessListener(new ProcessAdapter() { @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { // re-translate builder's output to idea.log final String text = event.getText(); if (!StringUtil.isEmptyOrSpaces(text)) { if (ProcessOutputTypes.SYSTEM.equals(outputType)) { if (LOG.isDebugEnabled()) { LOG.debug("BUILDER_PROCESS [" + outputType + "]: " + text.trim()); } } else { LOG.info("BUILDER_PROCESS [" + outputType + "]: " + text.trim()); } } } }); if (debugPort > 0) { processHandler.putUserData(COMPILER_PROCESS_DEBUG_PORT, debugPort); } return processHandler; } private static boolean shouldIncludeEclipseCompiler(CompilerConfiguration config) { if (config instanceof CompilerConfigurationImpl) { final BackendCompiler javaCompiler = ((CompilerConfigurationImpl)config).getDefaultCompiler(); final String compilerId = javaCompiler != null? javaCompiler.getId() : null; return JavaCompilers.ECLIPSE_ID.equals(compilerId) || JavaCompilers.ECLIPSE_EMBEDDED_ID.equals(compilerId); } return true; } @NotNull public Path getBuildSystemDirectory() { return PathManagerEx.getAppSystemDir().resolve(SYSTEM_ROOT); } @NotNull public static File getBuildLogDirectory() { return new File(PathManager.getLogPath(), "build-log"); } @Nullable public File getProjectSystemDirectory(Project project) { final String projectPath = getProjectPath(project); return projectPath != null ? Utils.getDataStorageRoot(getBuildSystemDirectory().toFile(), projectPath) : null; } private static File getUsageFile(@NotNull File projectSystemDir) { return new File(projectSystemDir, "ustamp"); } private static void updateUsageFile(@Nullable Project project, @NotNull File projectSystemDir) { File usageFile = getUsageFile(projectSystemDir); StringBuilder content = new StringBuilder(); try { synchronized (USAGE_STAMP_DATE_FORMAT) { content.append(USAGE_STAMP_DATE_FORMAT.format(System.currentTimeMillis())); } if (project != null && !project.isDisposed()) { final String projectFilePath = project.getProjectFilePath(); if (!StringUtil.isEmptyOrSpaces(projectFilePath)) { content.append("\n").append(FileUtil.toCanonicalPath(projectFilePath)); } } FileUtil.writeToFile(usageFile, content.toString()); } catch (Throwable e) { LOG.info(e); } } @Nullable private static Pair<Date, File> readUsageFile(File usageFile) { try { List<String> lines = FileUtil.loadLines(usageFile, StandardCharsets.UTF_8.name()); if (!lines.isEmpty()) { final String dateString = lines.get(0); final Date date; synchronized (USAGE_STAMP_DATE_FORMAT) { date = USAGE_STAMP_DATE_FORMAT.parse(dateString); } final File projectFile = lines.size() > 1? new File(lines.get(1)) : null; return Pair.create(date, projectFile); } } catch (Throwable e) { LOG.info(e); } return null; } private void stopListening() { myListenPort = -1; myChannelRegistrar.close(); } private int startListening() { BuiltInServerManager builtInServerManager = BuiltInServerManager.getInstance(); builtInServerManager.waitForStart(); ServerBootstrap bootstrap = ((BuiltInServerManagerImpl)builtInServerManager).createServerBootstrap(); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(@NotNull Channel channel) { channel.pipeline().addLast(myChannelRegistrar, new ProtobufVarint32FrameDecoder(), new ProtobufDecoder(CmdlineRemoteProto.Message.getDefaultInstance()), new ProtobufVarint32LengthFieldPrepender(), new ProtobufEncoder(), myMessageDispatcher); } }); Channel serverChannel = bootstrap.bind(InetAddress.getLoopbackAddress(), 0).syncUninterruptibly().channel(); myChannelRegistrar.setServerChannel(serverChannel, false); return ((InetSocketAddress)serverChannel.localAddress()).getPort(); } private static String classpathToString(List<String> cp) { StringBuilder builder = new StringBuilder(); for (String file : cp) { if (builder.length() > 0) { builder.append(File.pathSeparator); } builder.append(FileUtil.toCanonicalPath(file)); } return builder.toString(); } public boolean isBuildProcessDebuggingEnabled() { return myBuildProcessDebuggingEnabled; } public void setBuildProcessDebuggingEnabled(boolean buildProcessDebuggingEnabled) { myBuildProcessDebuggingEnabled = buildProcessDebuggingEnabled; if (myBuildProcessDebuggingEnabled) { cancelAllPreloadedBuilds(); } } private abstract class BuildManagerPeriodicTask implements Runnable { private final Alarm myAlarm; private final AtomicBoolean myInProgress = new AtomicBoolean(false); private final Runnable myTaskRunnable = () -> { try { runTask(); } finally { myInProgress.set(false); } }; BuildManagerPeriodicTask() { myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, BuildManager.this); } final void schedule() { cancelPendingExecution(); final int delay = Math.max(100, getDelay()); myAlarm.addRequest(this, delay); } void cancelPendingExecution() { myAlarm.cancelAllRequests(); } protected boolean shouldPostpone() { return false; } protected abstract int getDelay(); protected abstract void runTask(); @Override public final void run() { if (!HeavyProcessLatch.INSTANCE.isRunning() && myFileChangeCounter <= 0 && !shouldPostpone() && !myInProgress.getAndSet(true)) { try { ApplicationManager.getApplication().executeOnPooledThread(myTaskRunnable); } catch (RejectedExecutionException ignored) { // we were shut down myInProgress.set(false); } catch (Throwable e) { myInProgress.set(false); throw new RuntimeException(e); } } else { schedule(); } } } private static class NotifyingMessageHandler extends DelegatingMessageHandler { private final Project myProject; private final BuilderMessageHandler myDelegateHandler; private final boolean myIsAutomake; NotifyingMessageHandler(@NotNull Project project, @NotNull BuilderMessageHandler delegateHandler, final boolean isAutomake) { myProject = project; myDelegateHandler = delegateHandler; myIsAutomake = isAutomake; } @Override protected BuilderMessageHandler getDelegateHandler() { return myDelegateHandler; } @Override public void buildStarted(@NotNull UUID sessionId) { super.buildStarted(sessionId); try { ApplicationManager .getApplication().getMessageBus().syncPublisher(BuildManagerListener.TOPIC).buildStarted(myProject, sessionId, myIsAutomake); } catch (Throwable e) { LOG.error(e); } } @Override public void sessionTerminated(@NotNull UUID sessionId) { try { super.sessionTerminated(sessionId); } finally { try { ApplicationManager.getApplication().getMessageBus().syncPublisher(BuildManagerListener.TOPIC).buildFinished(myProject, sessionId, myIsAutomake); } catch (Throwable e) { LOG.error(e); } } } } private static final class StdOutputCollector extends ProcessAdapter { private final Appendable myOutput; private int myStoredLength; StdOutputCollector(@NotNull Appendable outputSink) { myOutput = outputSink; } @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { String text; synchronized (this) { if (myStoredLength > 16384) { return; } text = event.getText(); if (StringUtil.isEmptyOrSpaces(text)) { return; } myStoredLength += text.length(); } try { myOutput.append(text); } catch (IOException ignored) { } } } private class ProjectWatcher implements ProjectManagerListener { private final Map<Project, MessageBusConnection> myConnections = new HashMap<>(); @Override public void projectOpened(@NotNull final Project project) { if (ApplicationManager.getApplication().isUnitTestMode()) return; final MessageBusConnection conn = project.getMessageBus().connect(); myConnections.put(project, conn); conn.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() { @Override public void rootsChanged(@NotNull final ModuleRootEvent event) { final Object source = event.getSource(); if (source instanceof Project) { clearState((Project)source); } } }); conn.subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionListener() { @Override public void processStarting(@NotNull String executorId, @NotNull ExecutionEnvironment env) { cancelAutoMakeTasks(env.getProject()); // make sure to cancel all automakes waiting in the build queue } @Override public void processStarted(@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler) { // make sure to cancel all automakes added to the build queue after processStaring and before this event cancelAutoMakeTasks(env.getProject()); } @Override public void processNotStarted(@NotNull String executorId, @NotNull ExecutionEnvironment env) { // augmenting reaction to processTerminated(): in case any automakes were canceled before process start scheduleAutoMake(); } @Override public void processTerminated(@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler, int exitCode) { scheduleAutoMake(); } }); conn.subscribe(CompilerTopics.COMPILATION_STATUS, new CompilationStatusListener() { private final Set<String> myRootsToRefresh = new THashSet<>(FileUtil.PATH_HASHING_STRATEGY); @Override public void automakeCompilationFinished(int errors, int warnings, @NotNull CompileContext compileContext) { if (!compileContext.getProgressIndicator().isCanceled()) { refreshSources(compileContext); } } @Override public void compilationFinished(boolean aborted, int errors, int warnings, @NotNull CompileContext compileContext) { refreshSources(compileContext); } private void refreshSources(CompileContext compileContext) { if (project.isDisposed()) { return; } final Set<String> candidates = new THashSet<>(FileUtil.PATH_HASHING_STRATEGY); synchronized (myRootsToRefresh) { candidates.addAll(myRootsToRefresh); myRootsToRefresh.clear(); } if (compileContext.isAnnotationProcessorsEnabled()) { // annotation processors may have re-generated code final CompilerConfiguration config = CompilerConfiguration.getInstance(project); for (Module module : compileContext.getCompileScope().getAffectedModules()) { if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { final String productionPath = CompilerPaths.getAnnotationProcessorsGenerationPath(module, false); if (productionPath != null) { candidates.add(productionPath); } final String testsPath = CompilerPaths.getAnnotationProcessorsGenerationPath(module, true); if (testsPath != null) { candidates.add(testsPath); } } } } if (!candidates.isEmpty()) { ApplicationManager.getApplication().executeOnPooledThread(() -> { if (project.isDisposed()) { return; } CompilerUtil.refreshOutputRoots(candidates); LocalFileSystem lfs = LocalFileSystem.getInstance(); Set<VirtualFile> toRefresh = ReadAction.compute(() -> { if (project.isDisposed()) { return Collections.emptySet(); } else { ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); return candidates.stream() .map(lfs::findFileByPath) .filter(root -> root != null && fileIndex.isInSourceContent(root)) .collect(Collectors.toSet()); } }); if (!toRefresh.isEmpty()) { lfs.refreshFiles(toRefresh, true, true, null); } }); } } @Override public void fileGenerated(@NotNull String outputRoot, @NotNull String relativePath) { synchronized (myRootsToRefresh) { myRootsToRefresh.add(outputRoot); } } }); final String projectPath = getProjectPath(project); Disposer.register(project, () -> { cancelPreloadedBuilds(projectPath); myProjectDataMap.remove(projectPath); }); StartupManager.getInstance(project).registerPostStartupActivity(() -> { runCommand(() -> { final File projectSystemDir = getProjectSystemDirectory(project); if (projectSystemDir != null) { updateUsageFile(project, projectSystemDir); } }); scheduleAutoMake(); // run automake after project opened }); } @Override public void projectClosingBeforeSave(@NotNull Project project) { cancelAutoMakeTasks(project); } @Override public void projectClosing(@NotNull Project project) { cancelPreloadedBuilds(getProjectPath(project)); for (TaskFuture<?> future : cancelAutoMakeTasks(project)) { future.waitFor(500, TimeUnit.MILLISECONDS); } } @Override public void projectClosed(@NotNull Project project) { myProjectDataMap.remove(getProjectPath(project)); final MessageBusConnection conn = myConnections.remove(project); if (conn != null) { conn.disconnect(); } } } private static class ProjectData { @NotNull final ExecutorService taskQueue; private final Set<InternedPath> myChanged = new THashSet<>(); private final Set<InternedPath> myDeleted = new THashSet<>(); private long myNextEventOrdinal; private boolean myNeedRescan = true; private ProjectData(@NotNull ExecutorService taskQueue) { this.taskQueue = taskQueue; } void addChanged(Collection<String> paths) { if (!myNeedRescan) { for (String path : paths) { final InternedPath _path = InternedPath.create(path); myDeleted.remove(_path); myChanged.add(_path); } } } void addDeleted(Collection<String> paths) { if (!myNeedRescan) { for (String path : paths) { final InternedPath _path = InternedPath.create(path); myChanged.remove(_path); myDeleted.add(_path); } } } CmdlineRemoteProto.Message.ControllerMessage.FSEvent createNextEvent() { final CmdlineRemoteProto.Message.ControllerMessage.FSEvent.Builder builder = CmdlineRemoteProto.Message.ControllerMessage.FSEvent.newBuilder(); builder.setOrdinal(++myNextEventOrdinal); for (InternedPath path : myChanged) { builder.addChangedPaths(path.getValue()); } myChanged.clear(); for (InternedPath path : myDeleted) { builder.addDeletedPaths(path.getValue()); } myDeleted.clear(); return builder.build(); } boolean getAndResetRescanFlag() { final boolean rescan = myNeedRescan; myNeedRescan = false; return rescan; } void dropChanges() { if (LOG.isDebugEnabled()) { LOG.debug("Project build state cleared: " + getThreadTrace(Thread.currentThread(), 20)); } myNeedRescan = true; myNextEventOrdinal = 0L; myChanged.clear(); myDeleted.clear(); } } private abstract static class InternedPath { protected final int[] myPath; /** * @param path assuming system-independent path with forward slashes */ InternedPath(String path) { final IntArrayList list = new IntArrayList(); final StringTokenizer tokenizer = new StringTokenizer(path, "/", false); while(tokenizer.hasMoreTokens()) { final String element = tokenizer.nextToken(); list.add(FileNameCache.storeName(element)); } myPath = list.toArray(); } public abstract String getValue(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InternedPath path = (InternedPath)o; return Arrays.equals(myPath, path.myPath); } @Override public int hashCode() { return Arrays.hashCode(myPath); } public static InternedPath create(String path) { return path.startsWith("/")? new XInternedPath(path) : new WinInternedPath(path); } } private static class WinInternedPath extends InternedPath { private WinInternedPath(String path) { super(path); } @Override public String getValue() { if (myPath.length == 1) { final String name = FileNameCache.getVFileName(myPath[0]).toString(); // handle case of windows drive letter return name.length() == 2 && name.endsWith(":")? name + "/" : name; } final StringBuilder buf = new StringBuilder(); for (int element : myPath) { if (buf.length() > 0) { buf.append("/"); } buf.append(FileNameCache.getVFileName(element)); } return buf.toString(); } } private static class XInternedPath extends InternedPath { private XInternedPath(String path) { super(path); } @Override public String getValue() { if (myPath.length > 0) { final StringBuilder buf = new StringBuilder(); for (int element : myPath) { buf.append("/").append(FileNameCache.getVFileName(element)); } return buf.toString(); } return "/"; } } private static final class DelegateFuture implements TaskFuture { @Nullable private TaskFuture<?>[] myDelegates; private Boolean myRequestedCancelState; @NotNull private synchronized TaskFuture<?>[] getDelegates() { TaskFuture<?>[] delegates = myDelegates; while (delegates == null) { try { wait(); } catch (InterruptedException ignored) { } delegates = myDelegates; } return delegates; } private synchronized boolean setDelegates(@NotNull TaskFuture<?>... delegates) { if (myDelegates == null) { try { myDelegates = delegates; if (myRequestedCancelState != null) { for (TaskFuture<?> delegate : delegates) { delegate.cancel(myRequestedCancelState); } } } finally { notifyAll(); } return true; } return false; } @Override public synchronized boolean cancel(boolean mayInterruptIfRunning) { Future<?>[] delegates = myDelegates; if (delegates == null) { myRequestedCancelState = mayInterruptIfRunning; return true; } Stream.of(delegates).forEach(delegate -> delegate.cancel(mayInterruptIfRunning)); return isDone(); } @Override public void waitFor() { Stream.of(getDelegates()).forEach(TaskFuture::waitFor); } @Override public boolean waitFor(long timeout, TimeUnit unit) { Stream.of(getDelegates()).forEach(delegate -> delegate.waitFor(timeout, unit)); return isDone(); } @Override public boolean isCancelled() { final Future<?>[] delegates; synchronized (this) { delegates = myDelegates; if (delegates == null) { return myRequestedCancelState != null; } } return Stream.of(delegates).anyMatch(Future::isCancelled); } @Override public boolean isDone() { final Future<?>[] delegates; synchronized (this) { delegates = myDelegates; if (delegates == null) { return false; } } return Stream.of(delegates).allMatch(Future::isDone); } @Override public Object get() throws InterruptedException, java.util.concurrent.ExecutionException { for (Future<?> delegate : getDelegates()) { delegate.get(); } return null; } @Override public Object get(long timeout, @NotNull TimeUnit unit) throws InterruptedException, java.util.concurrent.ExecutionException, TimeoutException { for (Future<?> delegate : getDelegates()) { delegate.get(timeout, unit); } return null; } } private class CancelBuildSessionAction<T extends BuilderMessageHandler> implements RequestFuture.CancelAction<T> { @Override public void cancel(RequestFuture<T> future) { myMessageDispatcher.cancelSession(future.getRequestID()); notifySessionTerminationIfNeeded(future.getRequestID(), null); } } static final class MyDocumentListener implements DocumentListener { @Override public void documentChanged(@NotNull DocumentEvent e) { if (ApplicationManager.getApplication().isUnitTestMode() || !Registry.is("compiler.document.save.enabled", false)) { return; } Document document = e.getDocument(); if (!FileDocumentManager.getInstance().isDocumentUnsaved(document)) { return; } VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file != null && file.isInLocalFileSystem()) { getInstance().scheduleProjectSave(); } } } }
package com.sometrik.framework; import android.content.Context; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; public class FWLayout extends LinearLayout implements NativeMessageHandler{ private Context context; public FWLayout(Context context) { super(context); this.context = context; list(); } @Override public int getElementId() { return this.getId(); } private void list(){ FrameWork.addToViewList(this); } private void createButton(final int id, String text){ Button button = new Button(context); button.setId(id); button.setText(text); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { FrameWork frame = (FrameWork)context; Message message = Message.obtain(frame.mainHandler, 2, id); message.sendToTarget(); } }); this.addView(button); } @Override public void handleMessage(NativeMessage message) { System.out.println("Message FWLayout " + this.getId()); switch(message.getMessage()){ case CREATE_BUTTON: createButton(message.getChildInternalId(), message.getTextValue()); break; case CREATE_PICKER: Spinner spinner = new Spinner(context); spinner.setId(message.getChildInternalId()); this.addView(spinner); break; case CREATE_LINEAR_LAYOUT: System.out.println("FWLayout " + this.getId() + " creating layout"); FWLayout layout = new FWLayout(context); layout.setId(message.getChildInternalId()); this.addView(layout); break; case CREATE_OPENGL_VIEW: break; case CREATE_TEXTFIELD: System.out.println("FWLayout " + this.getId() + " creating textfield"); EditText editText = new EditText(context); editText.setId(message.getChildInternalId()); editText.setText(message.getTextValue()); this.addView(editText); break; case CREATE_TEXTLABEL: System.out.println("FWLayout " + this.getId() + " creating textlabel"); TextView textView = new TextView(context); textView.setId(message.getChildInternalId()); textView.setText(message.getTextValue()); this.addView(textView); break; case SET_ATTRIBUTE: break; default: System.out.println("Message couldn't be handled by Element"); break; } } }
package org.cyclops.cyclopscore.inventory.container; import com.google.common.collect.Lists; import net.minecraft.entity.player.InventoryPlayer; import org.apache.commons.lang3.tuple.Pair; import org.cyclops.cyclopscore.inventory.IGuiContainerProvider; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * An inventory container that has a scrollbar and searchfield. * Terminology: * row: The row index from visible elements. * elementIndex: The element index in all available elements * visible: Currently on-screen by the user, maximum amount of elements is determined by the pageSize * filtered: All items that are browsable by the user, might be more than the pageSize allows what leads to a scrollbar. * unfiltered: All items, pattern searching will happen in this list. * @author rubensworks */ public abstract class ScrollingInventoryContainer<E> extends ExtendedInventoryContainer { private final List<E> unfilteredItems; private List<Pair<Integer, E>> filteredItems; // Pair: original index - item private final List<E> visibleItems; private final IItemPredicate<E> itemSearchPredicate; /** * Make a new instance. * * @param inventory The player inventory. * @param guiProvider The gui provider. * @param items All items to potentially show in this list. * @param filterer The predicate that is used to filter on the given items. */ @SuppressWarnings("unchecked") public ScrollingInventoryContainer(InventoryPlayer inventory, IGuiContainerProvider guiProvider, List<E> items, IItemPredicate<E> filterer) { super(inventory, guiProvider); this.unfilteredItems = Lists.newArrayList(items); this.filteredItems = Lists.newLinkedList(); this.visibleItems = (List<E>) Arrays.asList(new Object[getPageSize() * getColumns()]); for(int i = 0; i < getPageSize(); i++) { this.visibleItems.set(i, null); } this.itemSearchPredicate = filterer; } protected List<E> getUnfilteredItems() { return this.unfilteredItems; } protected List<Pair<Integer, E>> getFilteredItems() { return this.filteredItems; } public int getUnfilteredItemCount() { return getUnfilteredItems().size(); } public int getFilteredItemCount() { return getFilteredItems().size(); } /** * @return The maximum amount of columns to show. */ public int getColumns() { return 1; } /** * @return The stepsize for scrolling. */ public int getScrollStepSize() { return getColumns(); } /** * Scroll to the given relative position. * @param scroll A value between 0 and 1. */ public void scrollTo(float scroll) { onScroll(); int elements = (getFilteredItemCount() + getColumns() - 1) - getPageSize() * getColumns(); int firstElement = (int)((double)(scroll * (float)elements) + 0.5D); firstElement -= firstElement % getScrollStepSize(); if(firstElement < 0) firstElement = 0; for(int i = 0; i < getPageSize(); i++) { for(int j = 0; j < getColumns(); j++) { int index = i * getColumns() + j; int elementIndex = index + firstElement; this.visibleItems.set(index, null); if(elementIndex < getFilteredItemCount()) { Pair<Integer, E> filteredItem = getFilteredItems().get(elementIndex); enableElementAt(index, filteredItem.getLeft(), filteredItem.getRight()); } } } } protected void onScroll() { } /** * @return The allowed page size. */ public abstract int getPageSize(); /** * After scrolling, this will be called to make items visible. * @param visibleIndex The visible item index. * @param elementIndex The absolute element index. * @param element The element to show. */ protected void enableElementAt(int visibleIndex, int elementIndex, E element) { this.visibleItems.set(visibleIndex, element); } /** * Check if the given element is visible. * @param row The row the the given element is at. * @return If it is visible. */ public boolean isElementVisible(int row) { return row < getPageSize() && getVisibleElement(row) != null; } /** * Get the currently visible element at the given row. * @param row The row the the given element is at. * @return The elements */ public E getVisibleElement(int row) { if(row >= visibleItems.size()) return null; return this.visibleItems.get(row); } /** * Update the filtered items. * @param searchString The input string to search by. */ public void updateFilter(String searchString) { Pattern pattern; try { pattern = Pattern.compile(".*" + searchString.toLowerCase() + ".*"); } catch (PatternSyntaxException e) { pattern = Pattern.compile(".*"); } this.filteredItems = filter(getUnfilteredItems(), itemSearchPredicate, pattern); scrollTo(0); // Reset scroll, will also refresh items on-screen. } protected static <E> List<Pair<Integer, E>> filter(List<E> input, IItemPredicate<E> predicate, Pattern pattern) { List<Pair<Integer, E>> filtered = Lists.newLinkedList(); int i = 0; for(E item : input) { if(predicate.apply(item, pattern)) { filtered.add(Pair.of(i, item)); } i++; } return filtered; } /** * Predicate for matching items used to search. * @param <E> The type of item. */ public static interface IItemPredicate<E> { /** * Check if the given item matches a string pattern. * @param item The item to check. * @param pattern The pattern to check. * @return If the item matches */ public boolean apply(E item, Pattern pattern); } }
package org.jbehave.core.embedder; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.failures.FailureStrategy; import org.jbehave.core.failures.PendingStepFound; import org.jbehave.core.failures.PendingStepStrategy; import org.jbehave.core.failures.SilentlyAbsorbingFailure; import org.jbehave.core.model.ExamplesTable; import org.jbehave.core.model.GivenStories; import org.jbehave.core.model.GivenStory; import org.jbehave.core.model.Scenario; import org.jbehave.core.model.Story; import org.jbehave.core.reporters.StoryReporter; import org.jbehave.core.steps.CandidateSteps; import org.jbehave.core.steps.Step; import org.jbehave.core.steps.StepCollector; import org.jbehave.core.steps.StepCollector.Stage; import org.jbehave.core.steps.StepResult; /** * Runs a {@link Story}, given a {@link Configuration} and a list of * {@link CandidateSteps}, describing the results to the {@link StoryReporter}. * * @author Elizabeth Keogh * @author Mauro Talevi * @author Paul Hammant */ public class StoryRunner { private State state = new FineSoFar(); private FailureStrategy currentStrategy; private PendingStepStrategy pendingStepStrategy; private StoryReporter reporter; private FailureStrategy failureStrategy; private Throwable storyFailure; private StepCollector stepCollector; private String reporterStoryPath; /** * Run steps before or after a collection of stories. Steps are execute only * <b>once</b> per collection of stories. * * @param configuration the Configuration used to find the steps to run * @param candidateSteps List of CandidateSteps containing the candidate * steps methods * @param stage the Stage */ public void runBeforeOrAfterStories(Configuration configuration, List<CandidateSteps> candidateSteps, Stage stage) { runSteps(configuration.stepCollector().collectBeforeOrAfterStoriesSteps(candidateSteps, stage)); } /** * Runs a Story with the given configuration and steps. * * @param configuration the Configuration used to run story * @param candidateSteps the List of CandidateSteps containing the candidate * steps methods * @param story the Story to run * @throws Throwable if failures occurred and FailureStrategy dictates it to * be re-thrown. */ public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story) throws Throwable { run(configuration, candidateSteps, story, MetaFilter.EMPTY, false, new HashMap<String, String>()); } /** * Runs a Story with the given configuration and steps, applying the given meta filter. * * @param configuration the Configuration used to run story * @param candidateSteps the List of CandidateSteps containing the candidate * steps methods * @param story the Story to run * @param filter the Filter to apply to the story Meta * @throws Throwable if failures occurred and FailureStrategy dictates it to * be re-thrown. */ public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter) throws Throwable { run(configuration, candidateSteps, story, filter, false, new HashMap<String, String>()); } private void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter, boolean givenStory, Map<String, String> storyParameters) throws Throwable { stepCollector = configuration.stepCollector(); reporter = reporterFor(configuration, story, givenStory); pendingStepStrategy = configuration.pendingStepStrategy(); failureStrategy = configuration.failureStrategy(); if (!filter.allow(story.getMeta())) { reporter.storyNotAllowed(story, filter.asString()); return; } resetFailureState(givenStory); if (isDryRun(candidateSteps)) { reporter.dryRun(); } reporter.beforeStory(story, givenStory); runStorySteps(candidateSteps, story, givenStory, StepCollector.Stage.BEFORE); for (Scenario scenario : story.getScenarios()) { // scenario also inherits meta from story if (!filter.allow(scenario.getMeta().inheritFrom(story.getMeta()))) { reporter.scenarioNotAllowed(scenario, filter.asString()); continue; } reporter.beforeScenario(scenario.getTitle()); reporter.scenarioMeta(scenario.getMeta()); // run given stories, if any runGivenStories(configuration, candidateSteps, scenario, filter); if (isParametrisedByExamples(scenario)) { // run parametrised scenarios by examples runParametrisedScenariosByExamples(candidateSteps, scenario); } else { // run as plain old scenario runScenarioSteps(candidateSteps, scenario, storyParameters); } reporter.afterScenario(); } runStorySteps(candidateSteps, story, givenStory, StepCollector.Stage.AFTER); reporter.afterStory(givenStory); currentStrategy.handleFailure(storyFailure); } public Story storyOfPath(Configuration configuration, String storyPath) { String storyAsText = configuration.storyLoader().loadStoryAsText(storyPath); return configuration.storyParser().parseStory(storyAsText, storyPath); } private boolean isDryRun(List<CandidateSteps> candidateSteps) { for (CandidateSteps steps : candidateSteps) { if (steps.configuration().dryRun()) { return true; } } return false; } private StoryReporter reporterFor(Configuration configuration, Story story, boolean givenStory) { if (givenStory) { return configuration.storyReporter(reporterStoryPath); } else { // store parent story path for reporting reporterStoryPath = story.getPath(); return configuration.storyReporter(reporterStoryPath); } } private void resetFailureState(boolean givenStory) { if (givenStory) { // do not reset failure state for given stories return; } currentStrategy = new SilentlyAbsorbingFailure(); storyFailure = null; } private void runGivenStories(Configuration configuration, List<CandidateSteps> candidateSteps, Scenario scenario, MetaFilter filter) throws Throwable { GivenStories givenStories = scenario.getGivenStories(); if (givenStories.getPaths().size() > 0) { reporter.givenStories(givenStories); for (GivenStory givenStory : givenStories.getStories()) { // run given story, using any parameters if provided Story story = storyOfPath(configuration, givenStory.getPath()); run(configuration, candidateSteps, story, filter, true, givenStory.getParameters()); } } } private boolean isParametrisedByExamples(Scenario scenario) { return scenario.getExamplesTable().getRowCount() > 0 && !scenario.getGivenStories().requireParameters(); } private void runParametrisedScenariosByExamples(List<CandidateSteps> candidateSteps, Scenario scenario) { ExamplesTable table = scenario.getExamplesTable(); reporter.beforeExamples(scenario.getSteps(), table); for (Map<String, String> scenarioParameters : table.getRows()) { reporter.example(scenarioParameters); runScenarioSteps(candidateSteps, scenario, scenarioParameters); } reporter.afterExamples(); } private void runStorySteps(List<CandidateSteps> candidateSteps, Story story, boolean givenStory, Stage stage) { runSteps(stepCollector.collectBeforeOrAfterStorySteps(candidateSteps, story, stage, givenStory)); } private void runScenarioSteps(List<CandidateSteps> candidateSteps, Scenario scenario, Map<String, String> parameters) { runSteps(stepCollector.collectScenarioSteps(candidateSteps, scenario, parameters)); } /** * Runs a list of steps, while keeping state * * @param steps the Steps to run */ private void runSteps(List<Step> steps) { if (steps == null || steps.size() == 0) return; state = new FineSoFar(); for (Step step : steps) { state.run(step); } } private class SomethingHappened implements State { public void run(Step step) { StepResult result = step.doNotPerform(); result.describeTo(reporter); } } private final class FineSoFar implements State { public void run(Step step) { StepResult result = step.perform(); result.describeTo(reporter); Throwable scenarioFailure = result.getFailure(); if (scenarioFailure != null) { state = new SomethingHappened(); storyFailure = mostImportantOf(storyFailure, scenarioFailure); currentStrategy = strategyFor(storyFailure); } } private Throwable mostImportantOf(Throwable failure1, Throwable failure2) { return failure1 == null ? failure2 : failure1 instanceof PendingStepFound ? (failure2 == null ? failure1 : failure2) : failure1; } private FailureStrategy strategyFor(Throwable failure) { if (failure instanceof PendingStepFound) { return pendingStepStrategy; } else { return failureStrategy; } } } private interface State { void run(Step step); } @Override public String toString() { return this.getClass().getSimpleName(); } }
package org.cyclops.integrateddynamics.core.evaluate.variable; import com.google.common.collect.Lists; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import lombok.ToString; import net.minecraft.nbt.INBT; import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocationException; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import org.cyclops.cyclopscore.helper.Helpers; import org.cyclops.integrateddynamics.api.advancement.criterion.ValuePredicate; import org.cyclops.integrateddynamics.api.evaluate.EvaluationException; import org.cyclops.integrateddynamics.api.evaluate.operator.IOperator; import org.cyclops.integrateddynamics.api.evaluate.variable.IValue; import org.cyclops.integrateddynamics.api.evaluate.variable.IValueType; import org.cyclops.integrateddynamics.api.evaluate.variable.IValueTypeNamed; import org.cyclops.integrateddynamics.api.evaluate.variable.IValueTypeUniquelyNamed; import org.cyclops.integrateddynamics.core.evaluate.operator.Operators; import org.cyclops.integrateddynamics.core.helper.L10NValues; import org.cyclops.integrateddynamics.core.logicprogrammer.ValueTypeLPElementBase; import org.cyclops.integrateddynamics.core.logicprogrammer.ValueTypeOperatorLPElement; import javax.annotation.Nullable; import java.util.List; /** * Value type with operator values. * @author rubensworks */ public class ValueTypeOperator extends ValueTypeBase<ValueTypeOperator.ValueOperator> implements IValueTypeNamed<ValueTypeOperator.ValueOperator>, IValueTypeUniquelyNamed<ValueTypeOperator.ValueOperator> { private static final String SIGNATURE_LINK = "->"; public ValueTypeOperator() { super("operator", Helpers.RGBToInt(43, 231, 47), TextFormatting.DARK_GREEN, ValueTypeOperator.ValueOperator.class); } @Override public ValueOperator getDefault() { return ValueOperator.of(Operators.GENERAL_IDENTITY); } @Override public ITextComponent toCompactString(ValueOperator value) { return value.getRawValue().getLocalizedNameFull(); } @Override public INBT serialize(ValueOperator value) { return Operators.REGISTRY.serialize(value.getRawValue()); } @Override public ValueOperator deserialize(INBT value) { IOperator operator; try { operator = Operators.REGISTRY.deserialize(value); } catch (EvaluationException e) { throw new IllegalArgumentException(e.getMessage()); } if (operator != null) { return ValueOperator.of(operator); } throw new IllegalArgumentException(String.format("Value \"%s\" could not be parsed to an operator.", value)); } @Override public void loadTooltip(List<ITextComponent> lines, boolean appendOptionalInfo, @Nullable ValueOperator value) { super.loadTooltip(lines, appendOptionalInfo, value); if (value != null) { lines.add(new TranslationTextComponent(L10NValues.VALUETYPEOPERATOR_TOOLTIP_SIGNATURE) .appendSibling(getSignature(value.getRawValue()))); } } @Override public ValueTypeLPElementBase createLogicProgrammerElement() { return new ValueTypeOperatorLPElement(); } @Override public ValuePredicate<ValueOperator> deserializeValuePredicate(JsonObject element, @Nullable IValue value) { JsonElement jsonElement = element.get("operator"); String operatorName = jsonElement != null && !jsonElement.isJsonNull() ? jsonElement.getAsString() : null; IOperator operator = null; if (operatorName != null) { try { operator = Operators.REGISTRY.getOperator(new ResourceLocation(operatorName)); } catch (ResourceLocationException e) { throw new JsonSyntaxException("Invalid operator name '" + operator + "'"); } if (operator == null) { throw new JsonSyntaxException("Could not find the operator '" + operator + "'"); } } return new ValueOperatorPredicate(this, value, operator); } @Override public ValueOperator materialize(ValueOperator value) throws EvaluationException { return ValueOperator.of(value.getRawValue().materialize()); } /** * Pretty formatted signature of an operator. * @param operator The operator. * @return The signature. */ public static ITextComponent getSignature(IOperator operator) { return getSignatureLines(operator, false) .stream() .reduce(new StringTextComponent(""), (a, b) -> a.appendText(" ").appendSibling(b)); } /** * Pretty formatted signature of an operator. * @param inputTypes The input types. * @param outputType The output types. * @return The signature. */ public static ITextComponent getSignature(IValueType[] inputTypes, IValueType outputType) { return getSignatureLines(inputTypes, outputType, false) .stream() .reduce((prev, next) -> prev.appendText(" ").appendSibling(next)) .orElseGet(() -> new StringTextComponent("")); } protected static ITextComponent switchSignatureLineContext(List<ITextComponent> lines, ITextComponent sb) { lines.add(sb); return new StringTextComponent(""); } /** * Pretty formatted signature of an operator. * @param inputTypes The input types. * @param outputType The output types. * @param indent If the lines should be indented. * @return The signature. */ public static List<ITextComponent> getSignatureLines(IValueType[] inputTypes, IValueType outputType, boolean indent) { List<ITextComponent> lines = Lists.newArrayList(); ITextComponent sb = new StringTextComponent(""); boolean first = true; for (IValueType inputType : inputTypes) { if (first) { first = false; } else { sb = switchSignatureLineContext(lines, sb); sb.appendText((indent ? " " : "") + SIGNATURE_LINK + " "); } sb.applyTextStyle(inputType.getDisplayColorFormat()) .appendSibling(new TranslationTextComponent(inputType.getTranslationKey())) .applyTextStyle(TextFormatting.RESET); } sb = switchSignatureLineContext(lines, sb); sb.appendText((indent ? " " : "") + SIGNATURE_LINK + " ") .applyTextStyle(outputType.getDisplayColorFormat()) .appendSibling(new TranslationTextComponent(outputType.getTranslationKey())) .applyTextStyle(TextFormatting.RESET); switchSignatureLineContext(lines, sb); return lines; } /** * Pretty formatted signature of an operator. * @param operator The operator. * @param indent If the lines should be indented. * @return The signature. */ public static List<ITextComponent> getSignatureLines(IOperator operator, boolean indent) { return getSignatureLines(operator.getInputTypes(), operator.getOutputType(), indent); } @Override public String getName(ValueTypeOperator.ValueOperator a) { return a.getRawValue().getLocalizedNameFull().getString(); } @Override public String getUniqueName(ValueOperator a) { return a.getRawValue().getUniqueName().toString(); } @ToString public static class ValueOperator extends ValueBase { private final IOperator value; private ValueOperator(IOperator value) { super(ValueTypes.OPERATOR); this.value = value; } public static ValueOperator of(IOperator value) { return new ValueOperator(value); } public IOperator getRawValue() { return value; } @Override public boolean equals(Object o) { return o == this || (o instanceof ValueOperator && value.equals(((ValueOperator) o).value)); } @Override public int hashCode() { return 37 + value.hashCode(); } } public static class ValueOperatorPredicate extends ValuePredicate<ValueOperator> { private final IOperator operator; public ValueOperatorPredicate(@Nullable IValueType valueType, @Nullable IValue value, @Nullable IOperator operator) { super(valueType, value); this.operator = operator; } @Override protected boolean testTyped(ValueOperator value) { return super.testTyped(value) && (operator == null || (value.getRawValue() == operator)); } } }
package de.otto.edison.jobs.controller; import de.otto.edison.jobs.domain.JobInfo; import de.otto.edison.jobs.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Optional; import static de.otto.edison.jobs.controller.JobRepresentation.representationOf; import static de.otto.edison.jobs.controller.UrlHelper.baseUriOf; import static java.net.URI.create; import static java.util.stream.Collectors.toList; import static javax.servlet.http.HttpServletResponse.*; import static org.springframework.web.bind.annotation.RequestMethod.*; @RestController public class JobsController { private static final Logger LOG = LoggerFactory.getLogger(JobsController.class); public static final int JOB_VIEW_COUNT = 100; @Autowired private JobService jobService; @Value("${server.contextPath}") private String serverContextPath; public JobsController() { } JobsController(final JobService jobService) { this.jobService = jobService; } @RequestMapping(value = "/internal/jobs", method = GET, produces = "text/html") public ModelAndView getJobsAsHtml(@RequestParam(value = "type", required = false) String type, HttpServletRequest request) { final List<JobRepresentation> jobRepresentations = jobService.findJobs(Optional.ofNullable(type), JOB_VIEW_COUNT) .stream() .map((j) -> representationOf(j, true, baseUriOf(request))) .collect(toList()); final ModelAndView modelAndView = new ModelAndView("jobs"); modelAndView.addObject("jobs", jobRepresentations); return modelAndView; } @RequestMapping(value = "/internal/jobs", method = GET, produces = "application/json") public List<JobRepresentation> getJobsAsJson(@RequestParam(value = "type", required = false) String type, @RequestParam(value = "count", defaultValue = "1") int count, HttpServletRequest request) { return jobService.findJobs(Optional.ofNullable(type), count) .stream() .map((j) -> representationOf(j, false, baseUriOf(request))) .collect(toList()); } @RequestMapping(value = "/internal/jobs", method = DELETE) public void deleteJobs(@RequestParam(value = "type", required = false) String type) { jobService.deleteJobs(Optional.ofNullable(type)); } /** * Starts a new job of the specifed type, if no such job is currently running. * * The method will return immediately, without waiting for the job to complete. * * If a job with same type is running, the response will have HTTP status 409 CONFLICT, * otherwise HTTP 204 NO CONTENT is returned, together with the response header 'Location', * containing the full URL of the running job. * * @param jobType the type of the job * @throws IOException */ @RequestMapping( value = "/internal/jobs/{jobType}", method = POST) public void startJob(final @PathVariable String jobType, final HttpServletRequest request, final HttpServletResponse response) throws IOException { final Optional<URI> jobUri = jobService.startAsyncJob(jobType); if (jobUri.isPresent()) { response.setHeader("Location", baseUriOf(request) + jobUri.get().toString()); response.setStatus(SC_NO_CONTENT); } else { response.sendError(SC_CONFLICT); } } @RequestMapping(value = "/internal/jobs/{id}", method = GET, produces = "text/html") public ModelAndView findJobAsHtml(final HttpServletRequest request, final HttpServletResponse response) throws IOException { final URI uri = jobUriOf(request); final Optional<JobInfo> optionalJob = jobService.findJob(uri); if (optionalJob.isPresent()) { final ModelAndView modelAndView = new ModelAndView("job"); modelAndView.addObject("job", representationOf(optionalJob.get(), true, baseUriOf(request))); return modelAndView; } else { response.sendError(SC_NOT_FOUND, "Job not found"); return null; } } @RequestMapping(value = "/internal/jobs/{id}", method = GET, produces = "application/json") public JobRepresentation findJob(final HttpServletRequest request, final HttpServletResponse response) throws IOException { final URI uri = jobUriOf(request); final Optional<JobInfo> optionalJob = jobService.findJob(uri); if (optionalJob.isPresent()) { return representationOf(optionalJob.get(), false, baseUriOf(request)); } else { response.sendError(SC_NOT_FOUND, "Job not found"); return null; } } private void setCorsHeaders(final HttpServletResponse response) { response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Origin", "*"); } private URI jobUriOf(HttpServletRequest request) { String servletPath = request.getServletPath() != null ? request.getServletPath() : ""; if (servletPath.contains(".")) { return create(servletPath.substring(0, servletPath.lastIndexOf('.'))); } else { return create(servletPath); } } }
package jolie.monitoring.events; import jolie.monitoring.MonitoringEvent; import jolie.runtime.Value; public class ProtocolMessageEvent extends MonitoringEvent { public enum Protocol { SOAP( "soap" ), HTTP( "http" ); private final String protocol; Protocol( String protocol ) { this.protocol = protocol; } public String getProtocol() { return protocol; } } public static enum Field { PROTOCOL( "protocol" ), MESSAGE( "message" ), HEADER( "header" ), BODY( "body" ), PROCESSID( "processId" ), RAWID( "rawId" ); private final String id; Field( String name ) { this.id = name; } public String id() { return this.id; } } public static String protocol( Value value ) { return value.getFirstChild( Field.PROTOCOL.id() ).strValue(); } public static Value message( Value value ) { return value.getFirstChild( Field.MESSAGE.id() ); } public static String header( Value value ) { return value.getFirstChild( Field.MESSAGE.id() ).getFirstChild( Field.HEADER.id() ) .strValue(); } public static String body( Value value ) { return value.getFirstChild( Field.MESSAGE.id() ).getFirstChild( Field.BODY.id() ) .strValue(); } public static String rawId( Value value ) { return value.getFirstChild( Field.RAWID.id() ).strValue(); } public ProtocolMessageEvent( String body, String header, String processId, String rawId, ProtocolMessageEvent.Protocol protocol ) { super( "ProtocolMessage-".concat( protocol.getProtocol() ), Value.create() ); data().getFirstChild( Field.PROCESSID.id() ).setValue( processId ); data().getFirstChild( Field.PROTOCOL.id() ).setValue( protocol.getProtocol() ); data().getFirstChild( Field.MESSAGE.id() ).getFirstChild( Field.HEADER.id() ) .setValue( header ); data().getFirstChild( Field.MESSAGE.id() ).getFirstChild( Field.BODY.id() ) .setValue( body ); data().getFirstChild( Field.RAWID.id() ).setValue( rawId ); } }
package agaricus.applysrg; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; public class SymbolRangeEmitter { String sourceFilePath; public SymbolRangeEmitter(String sourceFilePath) { this.sourceFilePath = sourceFilePath; } /** * Emit range of package statement, declaring the package the file resides within */ public void emitPackageRange(PsiPackageStatement psiPackageStatement) { internalEmitPackageRange(psiPackageStatement.getPackageReference().getText(), psiPackageStatement.getPackageReference().getTextRange(), psiPackageStatement.getPackageName()); } /** * Emit range of import statement, including name of the imported package/class */ public void emitImportRange(PsiImportStatementBase psiImportStatement) { // Disabled for now - class references are handled differently in import statements // (must be fully qualified...) /* PsiJavaCodeReferenceElement psiJavaCodeReferenceElement = psiImportStatement.getImportReference(); String qualifiedName = psiJavaCodeReferenceElement.getQualifiedName(); // note, may be package.*? internalEmitClassRange(psiJavaCodeReferenceElement.getText(), psiJavaCodeReferenceElement.getTextRange(), qualifiedName); */ } /** * Emit class name declaration * @return Qualified class name, for referencing class members */ public String emitClassRange(PsiClass psiClass) { String className = psiClass.getQualifiedName(); internalEmitClassRange(psiClass.getNameIdentifier().getText(), psiClass.getNameIdentifier().getTextRange(),className); return className; } /** * Emit type reference element range * (This is for when types are used, not declared) * Only class name references will be emitted */ public void emitTypeRange(PsiTypeElement psiTypeElement) { if (psiTypeElement == null) { return; } PsiType psiType = psiTypeElement.getType(); // Go deeper.. reaching inside arrays // We want to report e.g. java.lang.String, not java.lang.String[] psiType = psiType.getDeepComponentType(); if (psiType instanceof PsiPrimitiveType) { // skip int, etc. - they're never going to be renamed return; } // Get identifier referencing this type PsiJavaCodeReferenceElement psiJavaCodeReferenceElement = psiTypeElement.getInnermostComponentReferenceElement(); if (psiJavaCodeReferenceElement == null) { // get this on '? extends T' System.out.println("WARNING: no code reference element for "+psiTypeElement); return; } PsiElement referenceNameElement = psiJavaCodeReferenceElement.getReferenceNameElement(); if (!(referenceNameElement instanceof PsiIdentifier)) { System.out.println("WARNING: unrecognized reference name element, not identifier: " + referenceNameElement); return; } PsiIdentifier psiIdentifier = (PsiIdentifier)referenceNameElement; // Get the "base" parent type name -- without any array brackets, or type parameters String baseTypeName = psiType.getInternalCanonicalText(); if (baseTypeName.contains("<")) { // Sorry I couldn't find a better way to do this.. // The PsiIdentifier range is correct, but it needs to be fully qualified, so it has to come from // a PsiType. getDeepComponentType() handles descending into arrays, but not parameterized types. TODO: make better baseTypeName = baseTypeName.replaceFirst("<.*", ""); } internalEmitClassRange(psiIdentifier.getText(),psiIdentifier.getTextRange(),baseTypeName); // Process type parameters, for example, Integer and Boolean in HashMap<Integer,Boolean> PsiReferenceParameterList psiReferenceParameterList = psiJavaCodeReferenceElement.getParameterList(); for (PsiTypeElement innerTypeElement: psiReferenceParameterList.getTypeParameterElements()) { emitTypeRange(innerTypeElement); } } /** * Emit field name range */ public void emitFieldRange(String className, PsiField psiField) { internalEmitFieldRange(psiField.getNameIdentifier().getText(),psiField.getNameIdentifier().getTextRange(),className,psiField.getName()); } /** * Emit method declaration name range * @return Method signature, for referencing method body members */ public String emitMethodRange(String className, PsiMethod psiMethod) { String signature = MethodSignatureHelper.makeTypeSignatureString(psiMethod); internalEmitMethodRange(psiMethod.getNameIdentifier().getText(),psiMethod.getNameIdentifier().getTextRange(),className,psiMethod.getName(),signature); return signature; } /** * Emit method parameter name declaration range */ public void emitParameterRange(String className, String methodName, String methodSignature, PsiParameter psiParameter, int parameterIndex) { if (psiParameter == null || psiParameter.getNameIdentifier() == null) { return; } internalEmitParameterRange(psiParameter.getNameIdentifier().getText(),psiParameter.getNameIdentifier().getTextRange(),className,methodName,methodSignature,psiParameter.getName(),parameterIndex); } /** * Emit local variable declaration name range * Local variables can occur in methods, initializers, ... */ public void emitLocalVariableRange(String className, String methodName, String methodSignature, PsiLocalVariable psiLocalVariable, int localVariableIndex) { internalEmitLocalVariable(psiLocalVariable.getNameIdentifier().getText(),psiLocalVariable.getNameIdentifier().getTextRange(),className,methodName,methodSignature,psiLocalVariable.getName(),localVariableIndex); } // Referenced names below (symbol uses, as opposed to declarations) /** * Emit referenced class name range */ public void emitReferencedClass(PsiElement nameElement, PsiClass psiClass) { internalEmitClassRange(nameElement.getText(),nameElement.getTextRange(),psiClass.getQualifiedName()); } /** * Emit referenced field name range */ public void emitReferencedField(PsiElement nameElement, PsiField psiField) { PsiClass psiClass = psiField.getContainingClass(); internalEmitFieldRange(nameElement.getText(),nameElement.getTextRange(),psiClass.getQualifiedName(),psiField.getName()); } /** * Emit referenced method name range, that is, a method call */ public void emitReferencedMethod(PsiElement nameElement, PsiMethod psiMethodCalled) { PsiClass psiClass = psiMethodCalled.getContainingClass(); internalEmitMethodRange(nameElement.getText(),nameElement.getTextRange(),psiClass.getQualifiedName(),psiMethodCalled.getName(),MethodSignatureHelper.makeTypeSignatureString(psiMethodCalled)); } /** * Emit referenced local variable name range * This includes both "local variables" declared in methods, and in foreach/catch sections ("parameters") */ public void emitReferencedLocalVariable(PsiElement nameElement, String className, String methodName, String methodSignature, PsiVariable psiVariable, int localVariableIndex) { internalEmitLocalVariable(nameElement.getText(),nameElement.getTextRange(),className,methodName,methodSignature,psiVariable.getName(),localVariableIndex); } /** * Emit referenced method parameter name range * Only includes _method_ parameters - for foreach/catch parameters see emitReferencedLocalVariable */ public void emitReferencedMethodParameter(PsiElement nameElement, String className, String methodName, String methodSignature, PsiParameter psiParameter, int index) { internalEmitParameterRange(nameElement.getText(),nameElement.getTextRange(),className,methodName,methodSignature,psiParameter.getName(),index); } // Field separator private final String FS = "|"; private String commonFields(String oldText, TextRange textRange) { // Include source filename for opening, textual range start/end, and old text for sanity check return "@"+FS+sourceFilePath+FS+textRange.getStartOffset()+FS+textRange.getEndOffset()+FS+oldText+FS; } // Methods to actually write the output // Everything goes through these methods private void internalEmitPackageRange(String oldText, TextRange textRange, String packageName) { System.out.println(commonFields(oldText, textRange)+"package"+FS+packageName); } private void internalEmitClassRange(String oldText, TextRange textRange, String className) { System.out.println(commonFields(oldText, textRange)+"class"+FS+className); } private void internalEmitFieldRange(String oldText, TextRange textRange, String className, String fieldName) { System.out.println(commonFields(oldText, textRange)+"field"+FS+className+FS+fieldName); } private void internalEmitMethodRange(String oldText, TextRange textRange, String className, String methodName, String methodSignature) { System.out.println(commonFields(oldText, textRange)+"method"+FS+className+FS+methodName+FS+methodSignature); } private void internalEmitParameterRange(String oldText, TextRange textRange, String className, String methodName, String methodSignature, String parameterName, int parameterIndex) { System.out.println(commonFields(oldText, textRange)+"param"+FS+className+FS+methodName+FS+methodSignature+FS+parameterName+FS+parameterIndex); } private void internalEmitLocalVariable(String oldText, TextRange textRange, String className, String methodName, String methodSignature, String variableName, int variableIndex) { System.out.println(commonFields(oldText, textRange)+"localvar"+FS+className+FS+methodName+FS+methodSignature+FS+variableName+FS+variableIndex); } }
package org.sagebionetworks.web.client.widget.entity.editor; import org.sagebionetworks.repo.model.Reference; import org.sagebionetworks.repo.model.attachment.UploadResult; import org.sagebionetworks.repo.model.attachment.UploadStatus; import org.sagebionetworks.web.client.DisplayConstants; import org.sagebionetworks.web.client.DisplayUtils; import org.sagebionetworks.web.client.DisplayUtils.SelectedHandler; import org.sagebionetworks.web.client.IconsImageBundle; import org.sagebionetworks.web.client.SageImageBundle; import org.sagebionetworks.web.client.widget.entity.browse.EntityFinder; import org.sagebionetworks.web.client.widget.entity.dialog.AddAttachmentDialog; import org.sagebionetworks.web.client.widget.entity.dialog.UploadFormPanel; import org.sagebionetworks.web.shared.WebConstants; import org.sagebionetworks.web.shared.WikiPageKey; import com.extjs.gxt.ui.client.Style.VerticalAlignment; import com.extjs.gxt.ui.client.event.ButtonEvent; import com.extjs.gxt.ui.client.event.Events; import com.extjs.gxt.ui.client.event.Listener; import com.extjs.gxt.ui.client.event.SelectionListener; import com.extjs.gxt.ui.client.event.TabPanelEvent; import com.extjs.gxt.ui.client.util.Margins; import com.extjs.gxt.ui.client.widget.Dialog; import com.extjs.gxt.ui.client.widget.HorizontalPanel; import com.extjs.gxt.ui.client.widget.Label; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.TabItem; import com.extjs.gxt.ui.client.widget.TabPanel; import com.extjs.gxt.ui.client.widget.Window; import com.extjs.gxt.ui.client.widget.button.Button; import com.extjs.gxt.ui.client.widget.form.AdapterField; import com.extjs.gxt.ui.client.widget.form.FormPanel; import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign; import com.extjs.gxt.ui.client.widget.form.TextField; import com.extjs.gxt.ui.client.widget.layout.FitLayout; import com.extjs.gxt.ui.client.widget.layout.FlowLayout; import com.extjs.gxt.ui.client.widget.layout.FormData; import com.google.gwt.core.client.GWT; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.ui.AbstractImagePrototype; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class ImageConfigViewImpl extends LayoutContainer implements ImageConfigView { private static final int DISPLAY_HEIGHT = 220; private Presenter presenter; SageImageBundle sageImageBundle; EntityFinder entityFinder; private UploadFormPanel uploadPanel; private IconsImageBundle iconsImageBundle; private TextField<String> urlField, nameField, entityField; TabItem externalTab,uploadTab, synapseTab; private HTMLPanel uploadStatusPanel; private String uploadedFileHandleName; private ImageParamsPanel uploadParamsPanel, synapseParamsPanel; TabPanel tabPanel; @Inject public ImageConfigViewImpl(IconsImageBundle iconsImageBundle, SageImageBundle sageImageBundle, EntityFinder entityFinder) { this.iconsImageBundle = iconsImageBundle; this.sageImageBundle = sageImageBundle; this.entityFinder = entityFinder; } @Override public void initView() { setLayout(new FitLayout()); uploadedFileHandleName = null; VerticalPanel externalLinkPanel = new VerticalPanel(); externalLinkPanel.add(getExternalLinkPanel()); externalLinkPanel.add(getExternalAltTextPanel()); tabPanel = new TabPanel(); tabPanel.setPlain(true); this.add(tabPanel); uploadTab = new TabItem(DisplayConstants.IMAGE_CONFIG_UPLOAD); uploadTab.addStyleName("pad-text"); uploadTab.setLayout(new FlowLayout()); tabPanel.add(uploadTab); externalTab = new TabItem(DisplayConstants.IMAGE_CONFIG_FROM_THE_WEB); externalTab.addStyleName("pad-text"); externalTab.setLayout(new FlowLayout()); externalTab.add(externalLinkPanel); tabPanel.add(externalTab); synapseTab = new TabItem(DisplayConstants.IMAGE_CONFIG_FROM_SYNAPSE); synapseTab.addStyleName("pad-text"); synapseTab.setLayout(new FlowLayout()); FlowPanel synapseEntityPanel = new FlowPanel(); synapseEntityPanel.add(getSynapseEntityPanel()); synapseParamsPanel = new ImageParamsPanel(); synapseEntityPanel.add(synapseParamsPanel); synapseTab.add(synapseEntityPanel); tabPanel.add(synapseTab); this.setHeight(DISPLAY_HEIGHT); this.layout(true); } private FormPanel getSynapseEntityPanel() { final FormPanel panel = new FormPanel(); panel.setHeaderVisible(false); panel.setFrame(false); panel.setBorders(false); panel.setShadow(false); panel.setLabelAlign(LabelAlign.RIGHT); panel.setBodyBorder(false); panel.setLabelWidth(88); FormData basicFormData = new FormData(); basicFormData.setWidth(330); Margins margins = new Margins(10, 10, 0, 0); basicFormData.setMargins(margins); entityField = new TextField<String>(); entityField.setFieldLabel(DisplayConstants.IMAGE_FILE_ENTITY); entityField.setAllowBlank(false); entityField.setRegex(WebConstants.VALID_ENTITY_ID_REGEX); entityField.getMessages().setRegexText(DisplayConstants.INVALID_SYNAPSE_ID_MESSAGE); panel.add(entityField, basicFormData); Button findEntitiesButton = new Button(DisplayConstants.FIND_IMAGE_ENTITY, AbstractImagePrototype.create(iconsImageBundle.magnify16())); findEntitiesButton.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { entityFinder.configure(false); final Window window = new Window(); DisplayUtils.configureAndShowEntityFinderWindow(entityFinder, window, new SelectedHandler<Reference>() { @Override public void onSelected(Reference selected) { if(selected.getTargetId() != null) { entityField.setValue(DisplayUtils.createEntityVersionString(selected)); window.hide(); } else { showErrorMessage(DisplayConstants.PLEASE_MAKE_SELECTION); } } }); } }); AdapterField buttonField = new AdapterField(findEntitiesButton); buttonField.setLabelSeparator(""); panel.add(buttonField, basicFormData); return panel; } @Override public String getUploadedFileHandleName() { return uploadedFileHandleName; } @Override public void setUploadedFileHandleName(String uploadedFileHandleName) { this.uploadedFileHandleName = uploadedFileHandleName; uploadPanel.getFileUploadField().setValue(uploadedFileHandleName); } @Override public String getAlignment() { if (isSynapseEntity()) return synapseParamsPanel.getAlignment(); else return uploadParamsPanel.getAlignment(); } @Override public String getScale() { if (isSynapseEntity()) return synapseParamsPanel.getScale(); else return uploadParamsPanel.getScale(); } @Override public void setAlignment(String alignment) { if (isSynapseEntity()) synapseParamsPanel.setAlignment(alignment); else uploadParamsPanel.setAlignment(alignment); } @Override public void setScale(String scale) { if (isSynapseEntity()) synapseParamsPanel.setScale(scale); else uploadParamsPanel.setScale(scale); } private HorizontalPanel getExternalLinkPanel() { HorizontalPanel hp = new HorizontalPanel(); hp.setVerticalAlign(VerticalAlignment.MIDDLE); urlField = new TextField<String>(); urlField.setAllowBlank(false); urlField.setRegex(WebConstants.VALID_URL_REGEX); urlField.getMessages().setRegexText(DisplayConstants.IMAGE_CONFIG_INVALID_URL_MESSAGE); Label urlLabel = new Label(DisplayConstants.IMAGE_CONFIG_URL_LABEL); urlLabel.setWidth(90); urlField.setWidth(350); hp.add(urlLabel); hp.add(urlField); hp.addStyleName("margin-top-left-10"); return hp; } private HorizontalPanel getExternalAltTextPanel() { HorizontalPanel hp = new HorizontalPanel(); hp.setVerticalAlign(VerticalAlignment.MIDDLE); nameField = new TextField<String>(); nameField.setAllowBlank(false); nameField.setRegex(WebConstants.VALID_WIDGET_NAME_REGEX); nameField.getMessages().setRegexText(DisplayConstants.IMAGE_CONFIG_INVALID_ALT_TEXT_MESSAGE); Label label = new Label(DisplayConstants.IMAGE_CONFIG_ALT_TEXT); label.setWidth(90); nameField.setWidth(350); hp.add(label); hp.add(nameField); hp.addStyleName("margin-top-left-10"); return hp; } @Override public void configure(WikiPageKey wikiKey, Dialog window) { uploadTab.removeAll(); //update the uploadPanel initUploadPanel(wikiKey, window); this.setHeight(DISPLAY_HEIGHT); this.layout(true); } private void initUploadPanel(WikiPageKey wikiKey, final Dialog window) { String wikiIdParam = wikiKey.getWikiPageId() == null ? "" : "&" + WebConstants.WIKI_ID_PARAM_KEY + "=" + wikiKey.getWikiPageId(); String baseURl = GWT.getModuleBaseURL()+"filehandle?" + WebConstants.WIKI_OWNER_ID_PARAM_KEY + "=" + wikiKey.getOwnerObjectId() + "&" + WebConstants.WIKI_OWNER_TYPE_PARAM_KEY + "=" + wikiKey.getOwnerObjectType() + wikiIdParam; //The ok/submitting button will be enabled when required images are uploaded //or when another tab (external or synapse) is viewed window.getButtonById(Dialog.OK).disable(); Listener uploadTabChangeListener = new Listener<TabPanelEvent>() { @Override public void handleEvent(TabPanelEvent be) { if(uploadedFileHandleName != null) { window.getButtonById(Dialog.OK).enable(); } } }; Listener tabChangeListener = new Listener<TabPanelEvent>() { @Override public void handleEvent(TabPanelEvent be) { window.getButtonById(Dialog.OK).enable(); } }; uploadTab.addListener(Events.Select, uploadTabChangeListener); externalTab.addListener(Events.Select, tabChangeListener); synapseTab.addListener(Events.Select, tabChangeListener); uploadPanel = AddAttachmentDialog.getUploadFormPanel(baseURl, sageImageBundle, DisplayConstants.ATTACH_IMAGE_DIALOG_BUTTON_TEXT, 25, new AddAttachmentDialog.Callback() { @Override public void onSaveAttachment(UploadResult result) { if(result != null){ if (uploadStatusPanel != null) uploadTab.remove(uploadStatusPanel); if(UploadStatus.SUCCESS == result.getUploadStatus()){ //save close this dialog with a save uploadStatusPanel = new HTMLPanel(SafeHtmlUtils.fromSafeConstant(DisplayUtils.getIconHtml(iconsImageBundle.checkGreen16()) +" "+ DisplayConstants.UPLOAD_SUCCESSFUL_STATUS_TEXT)); //enable the ok button window.getButtonById(Dialog.OK).enable(); }else{ uploadStatusPanel = new HTMLPanel(SafeHtmlUtils.fromSafeConstant(DisplayUtils.getIconHtml(iconsImageBundle.error16()) +" "+ result.getMessage())); } uploadStatusPanel.addStyleName("margin-left-180"); uploadTab.add(uploadStatusPanel); layout(true); } uploadedFileHandleName = uploadPanel.getFileUploadField().getValue(); } }, null); FlowPanel container = new FlowPanel(); container.add(uploadPanel); uploadParamsPanel = new ImageParamsPanel(); container.add(uploadParamsPanel); uploadTab.add(container); layout(true); } @Override public void checkParams() throws IllegalArgumentException { if (isExternal()) { if (!urlField.isValid()) throw new IllegalArgumentException(urlField.getErrorMessage()); if (!nameField.isValid()) throw new IllegalArgumentException(nameField.getErrorMessage()); } else if (isSynapseEntity()) { if (!entityField.isValid()) throw new IllegalArgumentException(entityField.getErrorMessage()); } else { //must have been uploaded if (uploadedFileHandleName == null) throw new IllegalArgumentException(DisplayConstants.IMAGE_CONFIG_UPLOAD_FIRST_MESSAGE); else { //block if it looks like this is not a valid image type String extension = uploadedFileHandleName.substring(uploadedFileHandleName.lastIndexOf(".")+1); if (!DisplayUtils.isRecognizedImageContentType("image/"+extension)) { throw new IllegalArgumentException(DisplayConstants.IMAGE_CONFIG_FILE_TYPE_MESSAGE); } } } } @Override public Widget asWidget() { return this; } @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } @Override public void showErrorMessage(String message) { DisplayUtils.showErrorMessage(message); } @Override public void showLoading() { } @Override public void showInfo(String title, String message) { DisplayUtils.showInfo(title, message); } @Override public void clear() { } @Override public int getDisplayHeight() { return DISPLAY_HEIGHT; } @Override public int getAdditionalWidth() { return 130; } @Override public String getImageUrl() { return urlField.getValue(); } @Override public String getAltText() { return nameField.getValue(); } @Override public void setImageUrl(String url) { urlField.setValue(url); } @Override public String getSynapseId() { return entityField.getValue(); } @Override public void setSynapseId(String synapseId) { entityField.setValue(synapseId); tabPanel.setSelection(synapseTab); } @Override public boolean isExternal() { return externalTab.equals(tabPanel.getSelectedItem()); } @Override public boolean isSynapseEntity() { return synapseTab.equals(tabPanel.getSelectedItem()); } @Override public void setExternalVisible(boolean visible) { externalTab.setEnabled(visible); } /* * Private Methods */ }
package org.sagebionetworks.web.client.widget.entity.renderer; import org.sagebionetworks.repo.model.file.FileHandleAssociateType; import org.sagebionetworks.repo.model.file.FileHandleAssociation; import org.sagebionetworks.repo.model.file.FileResult; import org.sagebionetworks.web.client.PopupUtilsView; import org.sagebionetworks.web.client.RequestBuilderWrapper; import org.sagebionetworks.web.client.SynapseClientAsync; import org.sagebionetworks.web.client.SynapseJSNIUtils; import org.sagebionetworks.web.client.widget.asynch.PresignedURLAsyncHandler; import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert; import org.sagebionetworks.web.shared.WebConstants; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; /** * Widget used to show untrusted html preview content. Has an option to open the untrusted html in a new window (after confirmation) * @author jayhodgson * */ public class HtmlPreviewWidget implements IsWidget, HtmlPreviewView.Presenter { protected HtmlPreviewView view; protected PresignedURLAsyncHandler presignedURLAsyncHandler; protected FileHandleAssociation fha; protected SynapseAlert synAlert; protected RequestBuilderWrapper requestBuilder; protected SynapseJSNIUtils jsniUtils; protected String createdBy; protected SynapseClientAsync synapseClient; protected PopupUtilsView popupUtils; @Inject public HtmlPreviewWidget( HtmlPreviewView view, PresignedURLAsyncHandler presignedURLAsyncHandler, SynapseJSNIUtils jsniUtils, RequestBuilderWrapper requestBuilder, SynapseAlert synAlert, SynapseClientAsync synapseClient, PopupUtilsView popupUtils) { this.view = view; this.presignedURLAsyncHandler = presignedURLAsyncHandler; this.jsniUtils = jsniUtils; this.requestBuilder = requestBuilder; this.synAlert = synAlert; this.synapseClient = synapseClient; this.popupUtils = popupUtils; view.setSynAlert(synAlert); view.setPresenter(this); } public void renderHTML(final String rawHtml) { view.setRawHtml(rawHtml); synapseClient.isUserAllowedToRenderHTML(createdBy, new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable caught) { view.setLoadingVisible(false); String escapedContent = SafeHtmlUtils.htmlEscapeAllowEntities(rawHtml); view.setHtml(truncateLargeHtml(escapedContent)); view.setSanitizedWarningVisible(true); } @Override public void onSuccess(Boolean trustedUser) { view.setLoadingVisible(false); if (trustedUser) { view.setHtml(rawHtml); } else { // is the sanitized version the same as the original?? String sanitizedHtml = jsniUtils.sanitizeHtml(rawHtml); if (rawHtml.equals(sanitizedHtml)) { view.setHtml(rawHtml); } else { view.setHtml(truncateLargeHtml(sanitizedHtml)); view.setSanitizedWarningVisible(true); } } } public String truncateLargeHtml(String sanitizedHtml) { if (sanitizedHtml.length() > 20000) { return sanitizedHtml.substring(0, 20000) + "\n..."; } else { return sanitizedHtml; } } }); } public void configure(String synapseId, String fileHandleId, String fileHandleCreatedBy) { this.createdBy = fileHandleCreatedBy; fha = new FileHandleAssociation(); fha.setAssociateObjectId(synapseId); fha.setAssociateObjectType(FileHandleAssociateType.FileEntity); fha.setFileHandleId(fileHandleId); refreshContent(); } @Override public Widget asWidget() { return view.asWidget(); } public void refreshContent() { if (fha != null) { synAlert.clear(); view.setLoadingVisible(true); view.setSanitizedWarningVisible(false); presignedURLAsyncHandler.getFileResult(fha, new AsyncCallback<FileResult>() { @Override public void onSuccess(FileResult fileResult) { setPresignedUrl(fileResult.getPreSignedURL()); } @Override public void onFailure(Throwable ex) { view.setLoadingVisible(false); synAlert.handleException(ex); } }); } } public void setPresignedUrl(String url) { // by default, get url. requestBuilder.configure(RequestBuilder.GET, url.toString()); requestBuilder.setHeader(WebConstants.CONTENT_TYPE, WebConstants.TEXT_HTML_CHARSET_UTF8); try { requestBuilder.sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { int statusCode = response.getStatusCode(); if (statusCode == Response.SC_OK) { renderHTML(response.getText()); } else { onError(null, new IllegalArgumentException("Unable to retrieve. Reason: " + response.getStatusText())); } } @Override public void onError(Request request, Throwable exception) { view.setLoadingVisible(false); synAlert.handleException(exception); } }); } catch (final Exception e) { view.setLoadingVisible(false); synAlert.handleException(e); } } @Override public void onShowFullContent() { //confirm popupUtils.showConfirmDialog("", "Click \"OK\" to leave this page and open this content in a new window; this enables additional functionality, but should only be done if you trust the contents.", () -> { //user clicked yes view.openRawHtmlInNewWindow(); }); } }
package org.fidonet.jftn.engine.script; import org.apache.log4j.Logger; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class ScriptManager { private static Logger logger = Logger.getLogger(ScriptManager.class); private ScriptEngine jythonEngine; private Map<String, Object> scriptVariables; private String scriptFolder; public ScriptManager() { this("./scripts/"); } public ScriptManager(String scriptFolder) { scriptVariables = new HashMap<String, Object>(); this.scriptFolder = scriptFolder; ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); jythonEngine = scriptEngineManager.getEngineByExtension("py"); if (jythonEngine == null) { throw new VerifyError("Jython script engine is not found"); } File scriptsFolder = new File(scriptFolder); try { String fullScriptPath = scriptsFolder.getCanonicalPath(); logger.debug("Adding to PYTHON_PATH \""+fullScriptPath+"\" folder"); jythonEngine.eval(String.format("import sys; sys.path.append(\"%s\")", scriptsFolder.getCanonicalPath())); } catch (Exception e){ logger.error(e.getMessage(), e); } } private ScriptEngine getJythonScriptEngine() throws Exception { return jythonEngine; } public <T> T getInterface(Object object, Class<T> type) { return ((Invocable)jythonEngine).getInterface(object, type); } public void runScript(File script) throws Exception { InputStream inputStream = new FileInputStream(script); this.runScript(inputStream); } public void runScript(InputStream stream) throws Exception { InputStreamReader reader = new InputStreamReader(stream); ScriptEngine jythonEngine = getJythonScriptEngine(); if (!scriptVariables.isEmpty()) { for (String name : scriptVariables.keySet()) { jythonEngine.put(name, scriptVariables.get(name)); } } jythonEngine.eval(reader); } public void addScriptVar(String name, Object value) { if (name != null && value != null) { scriptVariables.put(name, value); } else { // TODO: Log warn } } public void removeScriptVar(String name, Object value) { if (name != null && value != null) { if (scriptVariables.get(name) != null) { scriptVariables.remove(name); } else { logger.warn("Variable was scoped already"); } } else { logger.warn("Variable cannot be scoped. Name or Values is specified."); } } public void reloadScripts() { File scriptFolderFile = new File(scriptFolder); File[] fileList = scriptFolderFile.listFiles(); if (fileList != null) { for (File file : fileList) { String fileName = file.getName(); if (fileName.indexOf(".py") == fileName.length()-3) { try { logger.debug("Loading " + file.getName()); runScript(file); } catch (Exception e) { logger.trace(e.getMessage(), e); } } } } } }
package pl.otwartapw.ldapauth.mock; import java.io.Serializable; import java.util.HashMap; import javax.annotation.Resource; import javax.enterprise.context.ApplicationScoped; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.otwartapw.ldapauth.api.UserDto; /** * Simple cache implementation with fixed size. * * @author Adam Kowalewski * @version 2015.10.15 */ @ApplicationScoped public class UserCache implements Serializable { private static final long serialVersionUID = 1L; private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource(lookup = "java:global/ldapauth-mock/usercache") private int cacheSize; private HashMap<String, UserDto> userMap; public UserCache() { userMap = new HashMap<>(); } /** * Adds given dataset to cache. Cache size check is implemented and will if required clear all * previous entries from cache. * * @param dto complete dataset for user. * @author Adam Kowalewski * @version 2015.10.03 */ public void addUser(UserDto dto) { if (userMap.size() >= cacheSize) { logger.info("Cache cleanup"); userMap.clear(); } userMap.put(dto.getsAMAccountName(), dto); logger.info("Cache status {}/{}", userMap.size(), cacheSize); } public HashMap<String, UserDto> getUserMap() { return userMap; } public void setUserMap(HashMap<String, UserDto> userList) { this.userMap = userList; } }
package com.kennyc.colorchooser; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.TextView; public class ColorChooserDialog extends BaseDialog implements AdapterView.OnItemClickListener, View.OnClickListener { private static final String KEY_BUILDER = "ColorChooserDialog#Builder"; private GridView grid; private Button positiveBtn; private ColorListener listener; private static ColorChooserDialog newInstance(Builder builder) { ColorChooserDialog dialog = new ColorChooserDialog(); Bundle args = new Bundle(1); args.putParcelable(KEY_BUILDER, builder); dialog.setArguments(args); dialog.listener = builder.listener; return dialog; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.color_chooser_layout, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Bundle args = getArguments(); if (args == null || args.getParcelable(KEY_BUILDER) == null) { throw new IllegalStateException("Did not receive the needed parameters to create dialog"); } Builder b = args.getParcelable(KEY_BUILDER); TextView title = (TextView) view.findViewById(R.id.color_chooser_title); Button negativeBtn = (Button) view.findViewById(R.id.color_chooser_neg); negativeBtn.setOnClickListener(this); positiveBtn = (Button) view.findViewById(R.id.color_chooser_pos); positiveBtn.setOnClickListener(this); grid = (GridView) view.findViewById(R.id.color_chooser_grid); grid.setOnItemClickListener(this); ColorAdapter adapter = new ColorAdapter(getActivity(), b.colors, b.showSelectedBorder); if (b.selectedColor != Color.TRANSPARENT) adapter.setSelectedColor(b.selectedColor); grid.setAdapter(adapter); if (!TextUtils.isEmpty(b.title)) { title.setText(b.title); } else { title.setVisibility(View.GONE); } if (!TextUtils.isEmpty(b.negativeButton)) { negativeBtn.setText(b.negativeButton); } else { negativeBtn.setVisibility(View.GONE); } if (!TextUtils.isEmpty(b.positiveButton)) { positiveBtn.setText(b.positiveButton); } else { positiveBtn.setVisibility(View.GONE); } } @Override public void onDestroyView() { listener = null; super.onDestroyView(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ColorAdapter adapter = (ColorAdapter) parent.getAdapter(); adapter.setSelectedPosition(position); } @Override public void onClick(View v) { if (listener == null) { dismiss(); return; } if (v == positiveBtn) { int color = ((ColorAdapter) grid.getAdapter()).getSelectedColor(); listener.onColorSelect(color); } dismiss(); } public interface ColorListener { /** * Callback when a color is selected from the dialog * * @param color */ void onColorSelect(int color); } public static class Builder implements Parcelable { private Resources resources; private int[] colors; private String title; private String negativeButton; private String positiveButton; private int selectedColor = Color.TRANSPARENT; private boolean showSelectedBorder = true; private ColorListener listener; /** * Create a builder factory for a {@link ColorChooserDialog} * * @param context */ public Builder(Context context) { this.resources = context.getResources(); } private Builder(Parcel in) { title = in.readString(); negativeButton = in.readString(); positiveButton = in.readString(); colors = in.createIntArray(); showSelectedBorder = in.readInt() == 1; selectedColor = in.readInt(); } /** * Sets the colors to be used in the picker * * @param colorArrayResource A string array from resources. The colors should be defined as such:<p/> * &lt;string-array&gt;<br/> * &lt;item&gt;#ffffff&lt;/item&gt;<br/> * &lt;item&gt;#000000&lt;/item&gt;<br/> * ...<br/> * ...<br/> * &lt;/string-array&gt; * @return */ public Builder colors(int colorArrayResource) { String[] array = resources.getStringArray(colorArrayResource); int length = array.length; int[] parsedColors = new int[length]; for (int i = 0; i < length; i++) { parsedColors[i] = Color.parseColor(array[i]); } return colors(parsedColors); } /** * Sets the colors to be used in the picker * * @param colors An array of color ints * @return */ public Builder colors(int[] colors) { if (colors == null || colors.length <= 0) { throw new IllegalArgumentException("colors == null or <= 0"); } this.colors = colors; return this; } /** * Sets which color should be pre-selected when first showing * * @param color * @return */ public Builder selectedColor(int color) { this.selectedColor = color; return this; } public Builder selectedColor(String color) { if (TextUtils.isEmpty(color)) throw new IllegalArgumentException("No color supplied"); return selectedColor(Color.parseColor(color)); } /** * Sets the title of the dialog * * @param title The string resource to use for the title * @return */ public Builder title(int title) { return title(resources.getString(title)); } /** * Sets the title of the dialog * * @param title Title to be used for the dialog * @return */ public Builder title(String title) { this.title = title; return this; } /** * Whether or not the circle icons will have a border around them when selected * * @param border * @return */ public Builder hasBorder(boolean border) { showSelectedBorder = border; return this; } /** * Sets the text for the negative Button * * @param negativeButton The string resource to use for the negative button * @return */ public Builder negativeButton(int negativeButton) { return negativeButton(resources.getString(negativeButton)); } /** * Sets the text for the negative Button * * @param negativeButton The string to use for the negative button * @return */ public Builder negativeButton(String negativeButton) { this.negativeButton = negativeButton; return this; } /** * Sets the text for the positive Button * * @param positiveButton The string resource to use for the negative button * @return */ public Builder positiveButton(int positiveButton) { return positiveButton(resources.getString(positiveButton)); } /** * Sets the text for the positive Button * * @param positiveButton The string to use for the negative button * @return */ public Builder positiveButton(String positiveButton) { this.positiveButton = positiveButton; return this; } public Builder listener(ColorListener listener) { this.listener = listener; return this; } public ColorChooserDialog build() { return newInstance(this); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(title); dest.writeString(negativeButton); dest.writeString(positiveButton); dest.writeIntArray(colors); dest.writeInt(showSelectedBorder ? 1 : 0); dest.writeInt(selectedColor); } public static final Parcelable.Creator<Builder> CREATOR = new Parcelable.Creator<Builder>() { public Builder createFromParcel(Parcel in) { return new Builder(in); } public Builder[] newArray(int size) { return new Builder[size]; } }; } }
package org.atlasapi.content; import static com.google.common.base.Preconditions.checkNotNull; import org.atlasapi.media.entity.ImageAspectRatio; import org.atlasapi.media.entity.ImageColor; import org.atlasapi.media.entity.ImageTheme; import org.atlasapi.media.entity.ImageType; import org.atlasapi.meta.annotations.FieldName; import org.joda.time.DateTime; import com.google.common.base.Predicate; import com.metabroadcast.common.media.MimeType; public class Image { public enum AspectRatio { SIXTEEN_BY_NINE("16x9"), FOUR_BY_THREE("4x3"); private final String name; private AspectRatio(String name) { this.name = name; } @FieldName("name") public String getName() { return name; } } public enum Color { COLOR("color"), BLACK_AND_WHITE("black_and_white"), SINGLE_COLOR("single_color"); private final String name; private Color(String name) { this.name = name; } @FieldName("name") public String getName() { return name; } } public enum Theme { DARK_OPAQUE("dark_opaque"), LIGHT_OPAQUE("light_opaque"), DARK_TRANSPARENT("dark_transparent"), LIGHT_TRANSPARENT("light_transparent"); private final String name; private Theme(String name) { this.name = name; } @FieldName("name") public String getName() { return name; } } public enum Type { PRIMARY("primary"), ADDITIONAL("additional"), BOX_ART("box_art"), POSTER("poster"), LOGO("logo"); private final String name; private Type(String name) { this.name = name; } @FieldName("name") public String getName() { return name; } } public static final Predicate<Image> IS_PRIMARY = new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getType() != null && input.getType().equals(Type.PRIMARY); } }; public static final Builder builder(Image base) { Builder builder = new Builder(base.getCanonicalUri()); builder.withHeight(base.height); builder.withWidth(base.width); builder.withType(base.type); builder.withColor(base.color); builder.withTheme(base.theme); builder.withAspectRatio(base.aspectRatio); builder.withMimeType(base.mimeType); builder.withAvailabilityStart(base.availabilityStart); builder.withAvailabilityEnd(base.availabilityEnd); return builder; } public static final Builder builder(String uri) { return new Builder(uri); } public static final class Builder { private String uri; private Integer height; private Integer width; private Type type; private Color color; private Theme theme; private AspectRatio aspectRatio; private MimeType mimeType; private DateTime availabilityStart; private DateTime availabilityEnd; private Boolean hasTitleArt; public Builder(String uri) { this.uri = uri; } public Builder withUri(String uri) { this.uri = uri; return this; } public Builder withHeight(Integer height) { this.height = height; return this; } public Builder withWidth(Integer width) { this.width = width; return this; } public Builder withType(Type type) { this.type = type; return this; } public Builder withColor(Color color) { this.color = color; return this; } public Builder withTheme(Theme theme) { this.theme = theme; return this; } public Builder withAspectRatio(AspectRatio aspectRatio) { this.aspectRatio = aspectRatio; return this; } public Builder withLegacyType(ImageType type) { if(type != null) { this.type = Image.Type.valueOf(type.toString()); } return this; } public Builder withLegacyColor(ImageColor color) { if(color != null) { this.color = Image.Color.valueOf(color.toString()); } return this; } public Builder withLegacyTheme(ImageTheme theme) { if(theme != null) { this.theme = Image.Theme.valueOf(theme.toString()); } return this; } public Builder withLegacyAspectRatio(ImageAspectRatio aspectRatio) { if(aspectRatio != null ) { this.aspectRatio = Image.AspectRatio.valueOf(aspectRatio.toString()); } return this; } public Builder withMimeType(MimeType mimeType) { this.mimeType = mimeType; return this; } public Builder withAvailabilityStart(DateTime availabilityStart) { this.availabilityStart = availabilityStart; return this; } public Builder withAvailabilityEnd(DateTime availabilityEnd) { this.availabilityEnd = availabilityEnd; return this; } public Builder withHasTitleArt(Boolean hasTitleArt) { this.hasTitleArt = hasTitleArt; return this; } public Image build() { Image image = new Image(uri); image.setHeight(height); image.setWidth(width); image.setType(type); image.setColor(color); image.setTheme(theme); image.setAspectRatio(aspectRatio); image.setMimeType(mimeType); image.setAvailabilityStart(availabilityStart); image.setAvailabilityEnd(availabilityEnd); image.setHasTitleArt(hasTitleArt); return image; } } private String uri; private Type type; private Color color; private Theme theme; private Integer height; private Integer width; private AspectRatio aspectRatio; private MimeType mimeType; private DateTime availabilityStart; private DateTime availabilityEnd; private Boolean hasTitleArt; public Image(String uri) { this.uri = checkNotNull(uri); } @FieldName("uri") public String getCanonicalUri() { return uri; } public void setCanonicalUri(String uri) { this.uri = uri; } @FieldName("height") public Integer getHeight() { return height; } public void setHeight(Integer height) { this.height = height; } @FieldName("width") public Integer getWidth() { return width; } public void setWidth(Integer width) { this.width = width; } @FieldName("type") public Type getType() { return type; } public void setType(Type type) { this.type = type; } @FieldName("color") public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } @FieldName("theme") public Theme getTheme() { return theme; } public void setTheme(Theme theme) { this.theme = theme; } @FieldName("aspect_ratio") public AspectRatio getAspectRatio() { return aspectRatio; } public void setAspectRatio(AspectRatio aspectRatio) { this.aspectRatio = aspectRatio; } @FieldName("mime_type") public MimeType getMimeType() { return mimeType; } public void setMimeType(MimeType mimeType) { this.mimeType = mimeType; } @FieldName("availability_start") public DateTime getAvailabilityStart() { return availabilityStart; } public void setAvailabilityStart(DateTime availabilityStart) { this.availabilityStart = availabilityStart; } @FieldName("availability_end") public DateTime getAvailabilityEnd() { return availabilityEnd; } public void setAvailabilityEnd(DateTime availabilityEnd) { this.availabilityEnd = availabilityEnd; } public Boolean getHasTitleArt() { return hasTitleArt; } public void setHasTitleArt(Boolean hasTitleArt) { this.hasTitleArt = hasTitleArt; } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that instanceof Image) { Image other = (Image) that; return uri.equals(other.uri); } return false; } @Override public int hashCode() { return uri.hashCode(); } public static final Predicate<Image> IS_AVAILABLE = new Predicate<Image>() { @Override public boolean apply(Image input) { return (input.getAvailabilityStart() == null || ! (new DateTime(input.getAvailabilityStart()).isAfterNow())) && (input.getAvailabilityEnd() == null || new DateTime(input.getAvailabilityEnd()).isAfterNow()); } }; }