answer
stringlengths
17
10.2M
package org.kingsski.kaas.service.organisation; import org.kingsski.kaas.database.organisation.Organisation; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * Defines the API for querying {@link Organisation}s */ @RestController public class OrganisationRestController { @Resource private OrganisationService organisationService; @GetMapping( path = "/organisations", produces = "application/json" ) public ResponseEntity organisations() { return ResponseEntity.ok(organisationService.getOrganisations()); } @GetMapping( path = "/organisation/{id:\\d+}", produces = "application/json" ) public ResponseEntity organisationById(@PathVariable("id") long id) { Organisation organisation = organisationService.getOrganisationById(id); if (organisation == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } return ResponseEntity.ok(organisationService.getOrganisationById(id)); } @GetMapping( path = "/organisation/{name:[A-Za-z]+.*}", produces = "application/json" ) public ResponseEntity organisationByName(@PathVariable("name") String name) { Organisation organisation = organisationService.getOrganisationByName(name); if (organisation == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } return ResponseEntity.ok(organisationService.getOrganisationByName(name)); } }
package com.htmlhifive.pitalium.image.util; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import com.htmlhifive.pitalium.image.model.CompareOption; import com.htmlhifive.pitalium.image.model.ComparedRectangleArea; import com.htmlhifive.pitalium.image.model.ComparisonParameterDefaults; import com.htmlhifive.pitalium.image.model.ComparisonParameters; import com.htmlhifive.pitalium.image.model.DefaultComparisonParameters; import com.htmlhifive.pitalium.image.model.DiffCategory; import com.htmlhifive.pitalium.image.model.DiffPoints; import com.htmlhifive.pitalium.image.model.ImageComparedResult; import com.htmlhifive.pitalium.image.model.ObjectGroup; import com.htmlhifive.pitalium.image.model.Offset; import com.htmlhifive.pitalium.image.model.SimilarityUnit; public class ImagePair { // after constructor, expectedImage and actualImage are assigned. // they can be sub-image of their own image to make their sizes the same. BufferedImage expectedImage; BufferedImage actualImage; private int width, height; // the size of intersection of two images int sizeRelationType; Offset offset; // Dominant offset between two images private List<Rectangle> rectangles; private List<ComparedRectangleArea> ComparedRectangles; private double entireSimilarity, minSimilarity; // Default criteria to split over-merged rectangle private static final int BORDER_WIDTH = 10; private static final int OVERMERGED_WIDTH = 200; private static final int OVERMERGED_HEIGHT = 300; private static final int SPLIT_ITERATION = 10; private static final boolean boundary_option = false; /** * Constructor implement all comparison steps, so that we can use ComparedRectangles as results after constructor. */ public ImagePair(BufferedImage expectedImage, BufferedImage actualImage) { double diffThreshold = ComparisonParameterDefaults.getDiffThreshold(); // Find dominant offset sizeRelationType = ImageUtils.getSizeRelationType(expectedImage.getWidth(), expectedImage.getHeight(), actualImage.getWidth(), actualImage.getHeight()); offset = ImageUtils.findDominantOffset(expectedImage, actualImage, diffThreshold); // assign (sub) image with same size this.expectedImage = ImageUtils.getDominantImage(expectedImage, actualImage, offset); this.actualImage = ImageUtils.getDominantImage(actualImage, expectedImage, offset); ComparedRectangles = new ArrayList<ComparedRectangleArea>(); width = Math.min(expectedImage.getWidth(), actualImage.getWidth()); height = Math.min(expectedImage.getHeight(), actualImage.getHeight()); entireSimilarity = 0; minSimilarity = 1; // assign dummy value to initialize } /** * Execute every comparison steps of two given images, build ComparedRectangles list, and calculate * entireSimilarity. */ public void compareImagePairAll() { prepare(); // compare two images using given rectangle areas and calculate all similarities doCategorize(); calcEntireSimilarity(); } public void prepare() { // initial group distance int group_distance = ComparisonParameterDefaults.getDefaultGroupDistance(); // Do not use sizeDiffPoints and consider only intersection area Rectangle entireFrame = new Rectangle(width, height); // build different areas rectangles = buildDiffAreas(entireFrame, group_distance); // split over-merged rectangles into smaller ones if possible SplitRectangles(rectangles, SPLIT_ITERATION, group_distance); ImageUtils.removeOverlappingRectangles(rectangles); ImageUtils.removeRedundantRectangles(rectangles, width, height); } public void doCategorize() { for (Rectangle rectangle : rectangles) { // initialize result rectangle ComparedRectangleArea resultRectangle = new ComparedRectangleArea(rectangle); Offset offset = null; // null means that when we calculate similarity, we try to find best match by moving actual sub-image Rectangle tightDiffArea = ImageUtils.getTightDiffArea(rectangle, width, height); /** if this rectangle is missing, set category 'MISSING' **/ if (Categorizer.checkMissing(expectedImage, actualImage, tightDiffArea)) { resultRectangle.setCategory(DiffCategory.MISSING); offset = new Offset(0, 0); // we fix the position of actual sub-image. /** if this rectangle is shift, then process shift information in CheckShift method **/ } else if (Categorizer.CheckShift(expectedImage, actualImage, ComparedRectangles, rectangle)) { // if shift, skip similarity calculation. continue; /** if this rectangle is image of sub-pixel rendered text, set category 'FONT' **/ } else if (Categorizer.CheckSubpixel(expectedImage, actualImage, rectangle)) { resultRectangle.setCategory(DiffCategory.TEXT); } /** calculate similarity **/ // try object detection for better performance Rectangle expectedObject = new Rectangle(rectangle); Rectangle actualObject = new Rectangle(rectangle); // if object detection succeed for both images. if (ImageUtils.getObjectRectangle(expectedImage, expectedObject) && ImageUtils.getObjectRectangle(actualImage, actualObject)) { int x1 = (int) expectedObject.getX(), y1 = (int) expectedObject.getY(), w1 = (int) expectedObject.getWidth(), h1 = (int) expectedObject.getHeight(), x2 = (int) actualObject.getX(), y2 = (int) actualObject.getY(), w2 = (int) actualObject.getWidth(), h2 = (int) actualObject.getHeight(); if (w1 == w2 && h1 == h2) { // case 1 : the same object size and the same location if (x1 == x2 && y1 == y2) { offset = new Offset(0, 0); // case 2 : the same object size but different location } else { offset = new Offset(x2 - x1, y2 - y1); SimilarityUnit unit = SimilarityUtils.calcSimilarity(expectedImage, actualImage, rectangle, resultRectangle, offset); double similarityThresDiff = unit.getSimilarityThresDiff(); // if so similar, regard them as the same objects with shifted location if (similarityThresDiff > ComparisonParameterDefaults.getShiftSimilarityThreshold()) { resultRectangle.setCategory(DiffCategory.SHIFT); resultRectangle.setXShift(x2 - x1); resultRectangle.setYShift(y2 - y1); resultRectangle.setSimilarityUnit(null); } else { resultRectangle.setSimilarityUnit(unit); } ComparedRectangles.add(resultRectangle); continue; } // case 3: different size } else { // check if two objects are the same but have different size if (Categorizer.checkScaling(expectedImage, actualImage, expectedObject, actualObject)) { resultRectangle.setCategory(DiffCategory.SCALING); double similarityFeatureMatrix = SimilarityUtils.calcSimilarityByFeatureMatrix(expectedImage, actualImage, expectedObject, actualObject); SimilarityUnit unit = SimilarityUtils.calcSimilarity(expectedImage, actualImage, rectangle, resultRectangle, offset, similarityFeatureMatrix); resultRectangle.setSimilarityUnit(unit); // insert the result rectangle into the list of ComparedRectangles ComparedRectangles.add(resultRectangle); continue; } } } // insert the result rectangle into the list of ComparedRectangles ComparedRectangles.add(resultRectangle); } } /** * calculate entireSimilarity between two images and find minimum similarity */ private void calcEntireSimilarity() { double entireDifference = 0; for (ComparedRectangleArea resultRectangle : ComparedRectangles) { // implement all similarity calculations and categorization, and then build ComparedRectangle SimilarityUnit unit = SimilarityUtils.calcSimilarity(expectedImage, actualImage, resultRectangle.toRectangle(), resultRectangle, offset); resultRectangle.setSimilarityUnit(unit); if (resultRectangle.getCategory() != DiffCategory.SHIFT && resultRectangle.getCategory() != null) { double similarityPixelByPixel = resultRectangle.getSimilarityUnit().getSimilarityPixelByPixel(); if (minSimilarity > similarityPixelByPixel) { minSimilarity = similarityPixelByPixel; } int rectangleArea = (int) (resultRectangle.getWidth() * resultRectangle.getHeight()); entireDifference += (1 - similarityPixelByPixel) * rectangleArea; } } entireSimilarity = 1 - entireDifference / (width * height); } /** * build different rectangles in the given frame area * * @param frame boundary area to build rectangles * @param group_distance distance for grouping * @return list of rectangles representing different area */ private List<Rectangle> buildDiffAreas(Rectangle frame, int group_distance) { List<ObjectGroup> objectGroups = buildObjectGroups(frame, group_distance, null); List<Rectangle> rectangles = ImageUtils.convertObjectGroupsToAreas(objectGroups); return rectangles; } /** * build object groups for different areas in the given frame area * * @param frame boundary area to build object * @param group_distance distance for grouping * @return list of object groups representing different area */ private List<ObjectGroup> buildObjectGroups(Rectangle frame, int group_distance, Offset offset) { // threshold for difference of color // if you want to compare STRICTLY, you should set this value as 0. double diffThreshold = ComparisonParameterDefaults.getDiffThreshold(); // base case for recursive building int base_bound = 50; if (frame.getWidth() < base_bound || frame.getHeight() < base_bound) { Rectangle actualFrame = frame; if (offset != null) { actualFrame.setLocation((int) frame.getX() + offset.getX(), (int) frame.getY() + offset.getY()); } ComparisonParameters params = new DefaultComparisonParameters(diffThreshold); CompareOption[] options = new CompareOption[] { new CompareOption(null, params) }; ImageComparedResult DP = ImageComparatorFactory.getInstance().getImageComparator(options) .compare(expectedImage, frame, actualImage, actualFrame); List<ObjectGroup> groups = ImageUtils.convertDiffPointsToObjectGroups((DiffPoints) DP, group_distance); // check boundary and update rectangles' positions if needed for (ObjectGroup g : groups) { Rectangle current = g.getRectangle(); Rectangle intersection = current.intersection(frame); current.setBounds(intersection); } return groups; } // divide into 4 sub-frames Rectangle nw, ne, sw, se; int x = (int) frame.getX(), y = (int) frame.getY(), w = (int) frame.getWidth(), h = (int) frame.getHeight(); int subW = Math.round(w / 2), subH = Math.round(h / 2); nw = new Rectangle(x, y, subW, subH); ne = new Rectangle(x + subW, y, w - subW, subH); sw = new Rectangle(x, y + subH, subW, h - subH); se = new Rectangle(x + subW, y + subH, w - subW, h - subH); // list of object groups built in each sub-frame List<ObjectGroup> NW, NE, SW, SE; NW = buildObjectGroups(nw, group_distance, offset); NE = buildObjectGroups(ne, group_distance, offset); SW = buildObjectGroups(sw, group_distance, offset); SE = buildObjectGroups(se, group_distance, offset); // merge 4 sub-frames List<ObjectGroup> mergeGroups = new ArrayList<ObjectGroup>(); mergeGroups.addAll(NW); mergeGroups.addAll(NE); mergeGroups.addAll(SW); mergeGroups.addAll(SE); // merge all possible object groups return ObjectGroup.mergeAllPossibleObjects(mergeGroups); } /** * Check if given rectangle is bigger than over-merged rectangle criteria * * @param rectangle Rectangle * @return true if it is over-merged */ private boolean canSplit(Rectangle rectangle) { int width = (int) rectangle.getWidth(), height = (int) rectangle.getHeight(); return (width >= OVERMERGED_WIDTH && height >= OVERMERGED_HEIGHT); } /** * Split rectangles which are over-merged into smaller ones if possible * * @param expectedImage * @param actualImage * @param rectangles list of Rectangles * @param splitIteration Iteration number for split implementation * @param group_distance distance for grouping */ private void SplitRectangles(List<Rectangle> rectangles, int splitIteration, int group_distance) { // Terminate recursion after splitIteration-times if (splitIteration < 1) { return; } int margin = (int) (group_distance / 2); // To extract ACTUAL different region int sub_margin = margin + BORDER_WIDTH; // Remove border from actual different region List<Rectangle> removeList = new ArrayList<Rectangle>(); List<Rectangle> addList = new ArrayList<Rectangle>(); // for sub-rectangles, we apply split_group_distance instead of group_distance int split_group_distance = ComparisonParameterDefaults.getSplitGroupDistance(); // split implementation for each rectangle for (Rectangle rectangle : rectangles) { // check if this rectangle can be split if (canSplit(rectangle)) { /** split is divided into two parts : inside sub-rectangle, boundary rectan gle **/ /* build inside rectangles */ // get sub rectangle by subtracting border information int subX = (int) rectangle.getX() + sub_margin; int subY = (int) rectangle.getY() + sub_margin; int subWidth = (int) rectangle.getWidth() - 2 * sub_margin; int subHeight = (int) rectangle.getHeight() - 2 * sub_margin; Rectangle subRectangle = new Rectangle(subX, subY, subWidth, subHeight); // use smaller group_distance to union Rectangle Area than what we used for the first different area recognition List<Rectangle> splitRectangles = buildDiffAreas(subRectangle, split_group_distance); /* build boundary rectangles */ // boundary area int boundary_margin = 1; // margin of boundary rectangle int padding = BORDER_WIDTH + 2 * boundary_margin; int x = (int) rectangle.getX() + margin - boundary_margin; int y = (int) rectangle.getY() + margin - boundary_margin; int width = (int) rectangle.getWidth() - 2 * margin + 2 * boundary_margin; int height = (int) rectangle.getHeight() - 2 * margin + 2 * boundary_margin; Rectangle leftBoundary = new Rectangle(x, subY, padding, subHeight); Rectangle rightBoundary = new Rectangle(x + width - padding, subY, padding, subHeight); Rectangle topBoundary = new Rectangle(subX, y, subWidth, padding); Rectangle bottomBoundary = new Rectangle(subX, y + height - padding, subWidth, padding); // build different area in boundary areas int minWidth = expectedImage.getWidth(), minHeight = expectedImage.getHeight(); ImageUtils.reshapeRect(leftBoundary, minWidth, minHeight); ImageUtils.reshapeRect(rightBoundary, minWidth, minHeight); ImageUtils.reshapeRect(topBoundary, minWidth, minHeight); ImageUtils.reshapeRect(bottomBoundary, minWidth, minHeight); List<Rectangle> boundaryList = new ArrayList<Rectangle>(); boundaryList.addAll(buildDiffAreas(leftBoundary, split_group_distance)); boundaryList.addAll(buildDiffAreas(rightBoundary, split_group_distance)); boundaryList.addAll(buildDiffAreas(topBoundary, split_group_distance)); boundaryList.addAll(buildDiffAreas(bottomBoundary, split_group_distance)); // if split succeed if (splitRectangles.size() != 1 || !subRectangle.equals(splitRectangles.get(0))) { // if there exists splitRectangle which is still over-merged, split it recursively SplitRectangles(splitRectangles, splitIteration - 1, split_group_distance); // Record the rectangles which will be removed and added for (Rectangle splitRectangle : splitRectangles) { // expand splitRectangle if it borders on subRectangle expand(subRectangle, splitRectangle, sub_margin); List<Rectangle> expansionRectangles = buildDiffAreas(splitRectangle, split_group_distance); // remove overlapping rectangles after expansion for (Rectangle boundaryRect : boundaryList) { for (Rectangle expansionRect : expansionRectangles) { Rectangle wrapper = new Rectangle((int) expansionRect.getX() - boundary_margin - 1, (int) expansionRect.getY() - boundary_margin - 1, (int) expansionRect.getWidth() + 2 * boundary_margin + 2, (int) expansionRect.getHeight() + 2 * boundary_margin + 2); if (wrapper.contains(boundaryRect)) { removeList.add(boundaryRect); break; } } } if (boundary_option) { addList.addAll(boundaryList); } boundaryList.clear(); addList.addAll(expansionRectangles); } removeList.add(rectangle); } } } // add recorded rectangles for (Rectangle rectangle : addList) { rectangles.add(rectangle); } // remove recorded rectangles for (Rectangle rectangle : removeList) { rectangles.remove(rectangle); } } /** * Expand the splitRectangle, if it borders on subRectangle, as much as border removed * * @param subRectangle Rectangle for checking expansion * @param splitRectangle Rectangle which is expanded * @param sub_margin how much border removed */ private void expand(Rectangle subRectangle, Rectangle splitRectangle, int sub_margin) { int subX = (int) subRectangle.getX(), subY = (int) subRectangle.getY(); int subWidth = (int) subRectangle.getWidth(), subHeight = (int) subRectangle.getHeight(); int splitX = (int) splitRectangle.getX(), splitY = (int) splitRectangle.getY(); int splitWidth = (int) splitRectangle.getWidth(), splitHeight = (int) splitRectangle.getHeight(); // Left-directional expansion if (splitX <= subX) { splitX = subX - sub_margin; splitWidth = splitWidth + sub_margin; } // Top-directional expansion if (splitY <= subY) { splitY = subY - sub_margin; splitHeight = splitHeight + sub_margin; } // Right-directional expansion if (splitX + splitWidth >= subX + subWidth) { splitWidth = subX + subWidth + sub_margin - splitX; } // Down-directional expansion if (splitY + splitHeight >= subY + subHeight) { splitHeight = subY + subHeight + sub_margin - splitY; } splitRectangle.setBounds(splitX, splitY, splitWidth, splitHeight); } /** * @return the list of result ComparedRectangles */ public List<ComparedRectangleArea> getComparedRectangles() { return ComparedRectangles; } /** * @return the similarity of entire area of two images */ public double getEntireSimilarity() { return entireSimilarity; } /** * @return the minimum similarity among all different area */ public double getMinSimilarity() { return minSimilarity; } public Offset getDominantOffset() { return offset; } /** * we need to decide which image of expected and actual is applied dominant offset. * * @return true if we need to apply dominant offset to expectedImage */ public boolean isExpectedMoved() { switch (sizeRelationType) { case 1: return false; case 2: return true; case 3: if (offset.getX() > 0) return true; else return false; case 4: if (offset.getX() > 0) return false; else return true; // never reach here default: return false; } } }
package nl.hermanbanken.rxfiddle.rewriting; import jdk.internal.org.objectweb.asm.Handle; import jdk.internal.org.objectweb.asm.MethodVisitor; import jdk.internal.org.objectweb.asm.Opcodes; import jdk.internal.org.objectweb.asm.Type; import nl.hermanbanken.rxfiddle.Hook; import java.util.ArrayList; import java.util.List; @SuppressWarnings("UnusedParameters") class UsageClassMethodVisitor extends MethodVisitor implements Opcodes { private final String visitedClass; private final String visitedMethod; private int visitedAccess; private int lineNumber; UsageClassMethodVisitor( MethodVisitor mv, String visitedClass, String visitedMethod, int visitedAccess) { super(Opcodes.ASM5, mv); this.visitedClass = visitedClass; this.visitedMethod = visitedMethod; this.visitedAccess = visitedAccess; } private Boolean shouldLog(String className, String methodName, String signature) { return shouldTrace(className, methodName, signature) || className.startsWith("rx/") && (methodName.equals("request") || methodName.equals("subscribe") || methodName.equals("unsafeSubscribe") || methodName.equals("unsubscribe") || methodName.equals("onNext") || methodName.equals("onError") || methodName.equals("onComplete")); } private static Boolean shouldTrace(String className, String methodName, String signature) { String returned = signature.substring(signature.lastIndexOf(')') + 1); return returned.equals("Lrx/Blocking;") || returned.equals("Lrx/Single;") || returned.equals("Lrx/Subscription;") || (returned.startsWith("Lrx/") && returned.endsWith("Observable;")) || (returned.startsWith("Lrx/") && returned.endsWith("Subscriber;")); } @Override public void visitLineNumber(int line, jdk.internal.org.objectweb.asm.Label label) { lineNumber = line; super.visitLineNumber(line, label); } @Override public void visitInvokeDynamicInsn( String method, String signature, Handle handle, Object... objects) { super.visitInvokeDynamicInsn(method, signature, handle, objects); } /** * Before calling the Rx method, log the call to Hook and maybe capture the invoke target * * Extracts the target of the method call if the argument list is only 1 long. * To support longer argument lists we need more logic than just SWAP / DUP opcodes, which is why it was postponed. * * @param access which visitMethod, from {@link Opcodes} * @param className which call * @param methodName which method * @param signature with which signature */ private void logUsageWithSubject( int access, String className, String methodName, String signature) { Type[] args = Type.getArgumentTypes(signature); // Find out if we can SWAP // Opcodes.SWAP cannot be used on Long or Doubles (as those use 2 stack entries) boolean canSwap = access == Opcodes.INVOKEVIRTUAL && args.length == 1 && !args[0].equals(Type.LONG_TYPE) && !args[0].equals(Type.DOUBLE_TYPE); if (canSwap) { super.visitInsn(Opcodes.SWAP); // swap to get self argument super.visitInsn(Opcodes.DUP); } else { super.visitInsn(Opcodes.ACONST_NULL); } // Annotate Rx ACCESS boolean fromLambda = (visitedAccess & Opcodes.ACC_SYNTHETIC) > 0; super.visitLdcInsn(className); super.visitLdcInsn(methodName); super.visitInsn(fromLambda ? ICONST_1 : ICONST_0); super.visitMethodInsn( Opcodes.INVOKESTATIC, Hook.Constants.CLASS_NAME, Hook.Constants.HOOK_METHOD_NAME, Hook.Constants.HOOK_METHOD_DESC, false); // Revert swap, if necessary if (canSwap) { super.visitInsn(Opcodes.SWAP); } } /** * Convenience method to debug log text at runtime: very handy to trace a VerifyError * @param log text to print */ @SuppressWarnings("unused") private void runtimeLog(String log) { mv.visitFieldInsn(GETSTATIC, "java/lang/System", "err", "Ljava/io/PrintStream;"); mv.visitLdcInsn(log); mv.visitMethodInsn( INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); } /** * Trace the entry of a method call */ private void traceEntry() { super.visitLdcInsn(visitedClass); super.visitLdcInsn(visitedMethod); super.visitLdcInsn(lineNumber); super.visitMethodInsn( Opcodes.INVOKESTATIC, Hook.Constants.CLASS_NAME, Hook.Constants.ENTER_METHOD_NAME, Hook.Constants.ENTER_METHOD_DESC, false); } /** * Trace the exit of a method call, capturing the return value */ private void traceExit() { super.visitInsn(Opcodes.DUP); super.visitMethodInsn( Opcodes.INVOKESTATIC, Hook.Constants.CLASS_NAME, Hook.Constants.LEAVE_METHOD_NAME, Hook.Constants.LEAVE_METHOD_DESC, false); } /** * visitMethodInstruction hook * * This method labels: * - the execution, by logging the class/method/line of the caller * * and by delegation to {@link #logUsageWithSubject(int, String, String, String)}: * - the invoke, by logging the class/method and optionally the target (if not static method) of the invoked * * @param access which visitMethod, from {@link Opcodes} * @param className which call * @param methodName which method * @param signature with which signature * @param isInterface whether the method is of a interface */ @Override public void visitMethodInsn( int access, String className, String methodName, String signature, boolean isInterface) { try { boolean shouldTrace = shouldTrace(className, methodName, signature); boolean shouldLog = shouldLog(className, methodName, signature); if (shouldTrace) traceEntry(); if (shouldLog) logUsageWithSubject(access, className, methodName, signature); // Call actual method super.visitMethodInsn(access, className, methodName, signature, isInterface); if (shouldTrace) traceExit(); } catch (Exception e) { System.out.println("Error " + e); } } } @SuppressWarnings({"unused", "WeakerAccess"}) class OpcodeLogDecorator { public enum Kind { Access, RawType, H, F, Ops } public static String resolve(int opcode, Kind kind) { String pool = null; switch (kind) { case Access: pool = "ACC_PUBLIC = 1;" + "ACC_PRIVATE = 2;" + "ACC_PROTECTED = 4;" + "ACC_STATIC = 8;" + "ACC_FINAL = 16;" + "ACC_SUPER = 32;" + "ACC_SYNCHRONIZED = 32;" + "ACC_VOLATILE = 64;" + "ACC_BRIDGE = 64;" + "ACC_VARARGS = 128;" + "ACC_TRANSIENT = 128;" + "ACC_NATIVE = 256;" + "ACC_INTERFACE = 512;" + "ACC_ABSTRACT = 1024;" + "ACC_STRICT = 2048;" + "ACC_SYNTHETIC = 4096;" + "ACC_ANNOTATION = 8192;" + "ACC_ENUM = 16384;" + "ACC_MANDATED = 32768;" + "ACC_DEPRECATED = 131072"; break; case RawType: pool = "T_BOOLEAN = 4;" + "T_CHAR = 5;" + "T_FLOAT = 6;" + "T_DOUBLE = 7;" + "T_BYTE = 8;" + "T_SHORT = 9;" + "T_INT = 10;" + "T_LONG = 11"; break; case H: pool = "H_GETFIELD = 1;" + "H_GETSTATIC = 2;" + "H_PUTFIELD = 3;" + "H_PUTSTATIC = 4;" + "H_INVOKEVIRTUAL = 5;" + "H_INVOKESTATIC = 6;" + "H_INVOKESPECIAL = 7;" + "H_NEWINVOKESPECIAL = 8;" + "H_INVOKEINTERFACE = 9"; break; case F: pool = "F_NEW = -1;" + "F_FULL = 0;" + "F_APPEND = 1;" + "F_CHOP = 2;" + "F_SAME = 3;" + "F_SAME1 = 4"; break; case Ops: pool = "NOP = 0;" + "ACONST_NULL = 1;" + "ICONST_M1 = 2;" + "ICONST_0 = 3;" + "ICONST_1 = 4;" + "ICONST_2 = 5;" + "ICONST_3 = 6;" + "ICONST_4 = 7;" + "ICONST_5 = 8;" + "LCONST_0 = 9;" + "LCONST_1 = 10;" + "FCONST_0 = 11;" + "FCONST_1 = 12;" + "FCONST_2 = 13;" + "DCONST_0 = 14;" + "DCONST_1 = 15;" + "BIPUSH = 16;" + "SIPUSH = 17;" + "LDC = 18;" + "ILOAD = 21;" + "LLOAD = 22;" + "FLOAD = 23;" + "DLOAD = 24;" + "ALOAD = 25;" + "IALOAD = 46;" + "LALOAD = 47;" + "FALOAD = 48;" + "DALOAD = 49;" + "AALOAD = 50;" + "BALOAD = 51;" + "CALOAD = 52;" + "SALOAD = 53;" + "ISTORE = 54;" + "LSTORE = 55;" + "FSTORE = 56;" + "DSTORE = 57;" + "ASTORE = 58;" + "IASTORE = 79;" + "LASTORE = 80;" + "FASTORE = 81;" + "DASTORE = 82;" + "AASTORE = 83;" + "BASTORE = 84;" + "CASTORE = 85;" + "SASTORE = 86;" + "POP = 87;" + "POP2 = 88;" + "DUP = 89;" + "DUP_X1 = 90;" + "DUP_X2 = 91;" + "DUP2 = 92;" + "DUP2_X1 = 93;" + "DUP2_X2 = 94;" + "SWAP = 95;" + "IADD = 96;" + "LADD = 97;" + "FADD = 98;" + "DADD = 99;" + "ISUB = 100;" + "LSUB = 101;" + "FSUB = 102;" + "DSUB = 103;" + "IMUL = 104;" + "LMUL = 105;" + "FMUL = 106;" + "DMUL = 107;" + "IDIV = 108;" + "LDIV = 109;" + "FDIV = 110;" + "DDIV = 111;" + "IREM = 112;" + "LREM = 113;" + "FREM = 114;" + "DREM = 115;" + "INEG = 116;" + "LNEG = 117;" + "FNEG = 118;" + "DNEG = 119;" + "ISHL = 120;" + "LSHL = 121;" + "ISHR = 122;" + "LSHR = 123;" + "IUSHR = 124;" + "LUSHR = 125;" + "IAND = 126;" + "LAND = 127;" + "IOR = 128;" + "LOR = 129;" + "IXOR = 130;" + "LXOR = 131;" + "IINC = 132;" + "I2L = 133;" + "I2F = 134;" + "I2D = 135;" + "L2I = 136;" + "L2F = 137;" + "L2D = 138;" + "F2I = 139;" + "F2L = 140;" + "F2D = 141;" + "D2I = 142;" + "D2L = 143;" + "D2F = 144;" + "I2B = 145;" + "I2C = 146;" + "I2S = 147;" + "LCMP = 148;" + "FCMPL = 149;" + "FCMPG = 150;" + "DCMPL = 151;" + "DCMPG = 152;" + "IFEQ = 153;" + "IFNE = 154;" + "IFLT = 155;" + "IFGE = 156;" + "IFGT = 157;" + "IFLE = 158;" + "IF_ICMPEQ = 159;" + "IF_ICMPNE = 160;" + "IF_ICMPLT = 161;" + "IF_ICMPGE = 162;" + "IF_ICMPGT = 163;" + "IF_ICMPLE = 164;" + "IF_ACMPEQ = 165;" + "IF_ACMPNE = 166;" + "GOTO = 167;" + "JSR = 168;" + "RET = 169;" + "TABLESWITCH = 170;" + "LOOKUPSWITCH = 171;" + "IRETURN = 172;" + "LRETURN = 173;" + "FRETURN = 174;" + "DRETURN = 175;" + "ARETURN = 176;" + "RETURN = 177;" + "GETSTATIC = 178;" + "PUTSTATIC = 179;" + "GETFIELD = 180;" + "PUTFIELD = 181;" + "INVOKEVIRTUAL = 182;" + "INVOKESPECIAL = 183;" + "INVOKESTATIC = 184;" + "INVOKEINTERFACE = 185;" + "INVOKEDYNAMIC = 186;" + "NEW = 187;" + "NEWARRAY = 188;" + "ANEWARRAY = 189;" + "ARRAYLENGTH = 190;" + "ATHROW = 191;" + "CHECKCAST = 192;" + "INSTANCEOF = 193;" + "MONITORENTER = 194;" + "MONITOREXIT = 195;" + "MULTIANEWARRAY = 197;" + "IFNULL = 198;" + "IFNONNULL = 199"; break; } List<String> bits = new ArrayList<>(); bits.add("" + opcode); String[] opts = pool.split(";"); for (String opt : opts) { int i = new Integer(opt.split("=")[1].trim()); if (i == opcode) return opt; if ((i & opcode) > 0) bits.add(opt.split(" =")[0]); } if (bits.size() > 1) { return bits.toString(); } return "not found"; } }
package net.floodlightcontroller.queuepusher; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Utils { static class Queue { public int qid; public String uuid; public Queue(int qid, String uuid) { this.qid = qid; this.uuid = uuid; } } protected static Logger logger = LoggerFactory.getLogger(Utils.class); public static final String OVS = "ovs-vsctl"; public static int qid = 0; private static List<Integer> idsInUse = Collections.synchronizedList(new ArrayList<Integer>()); private static Map<String, Integer> uuidToQoSId = Collections.synchronizedMap(new HashMap<String, Integer>()); private static Map<String, String> uuidToPort = Collections.synchronizedMap(new HashMap<String, String>()); private static Map<String, String> switchPortWithQueue = Collections.synchronizedMap(new HashMap<String, String>()); private static Map<String, List<Queue>> qosUuidToQueues = Collections.synchronizedMap(new HashMap<String, List<Queue>>()); private Utils() { } /** * Creates a new slice * * @param switchid DPID of the switch * @param port Port on the switch to apply the queue * @param rate Max rate of the queue * @return */ public static QueuePusherResponse createSlice(String switchid, String port, int rate, boolean dummy) { if(!Utils.checkOVS()) return new QueuePusherResponse(QueuePusherResponseCode.OVS_NOT_FOUND); if(switchid == null) return new QueuePusherResponse(QueuePusherResponseCode.INVALID_ARGUMENTS); String qosuiid = switchPortWithQueue.get(switchid+port); Object[] sw = QueuePusherSwitchMapper.getMatch(switchid); if(dummy) return new QueuePusherResponse(QueuePusherResponseCode.QP_DUMMY); do { qid++; } while(idsInUse.contains(qid)); idsInUse.add(qid); String cmd = Utils.OVS + " --db=tcp:" + (String)sw[0] + ":9091"; if(qosuiid != null) { cmd += " set qos " + qosuiid + " type=linux-htb other-config:max-rate=10000000000000000000000000 queues:" + qid + "=@lequeue " + "-- --id=@lequeue create queue other-config:max-rate=" + rate; } else { cmd += " set port " + port + " qos=@leqos -- --id=@leqos " + "create qos type=linux-htb other-config:max-rate=10000000000000000000000000 queues:" + qid + "=@lequeue " + "-- --id=@lequeue create queue other-config:max-rate=" + rate; } if(qid <= 0) qid = 1; logger.info("RUNNING: "+cmd); Object[] rsp = Utils.eval(cmd); if((Integer)rsp[0] == 0 && ((String)rsp[1]).length() == 74 && qosuiid == null) { switchPortWithQueue.put(switchid+port, ((String)rsp[1]).substring(0, 36)); uuidToQoSId.put(((String)rsp[1]).substring(0, 36), qid); uuidToPort.put(((String)rsp[1]).substring(0, 36), port); } if((Integer)rsp[0] == 0) { List<Queue> installedQueues; if(qosuiid == null) { installedQueues = new ArrayList<Queue>(); installedQueues.add(new Queue(qid, ((String)rsp[1]).substring(36, 72))); qosUuidToQueues.put(((String)rsp[1]).substring(0, 36), installedQueues); } else { installedQueues = qosUuidToQueues.get(qosuiid); installedQueues.add(new Queue(qid, ((String)rsp[1]).substring(0, 36))); } } if(qosuiid == null) { qosuiid = ""; } else { qosuiid += "\n"; } return new QueuePusherResponse((Integer)rsp[0] == 0 ? QueuePusherResponseCode.SUCCESS : QueuePusherResponseCode.CREATE_FAIL, qosuiid+(String)rsp[1], (String)rsp[2], qid); } /** * Deletes a QoS slice * * @param switchid Switch DPID * @param uuid Queue name * @return */ public static QueuePusherResponse deleteQoS(String switchid, String qosuuid, String queueuuid, boolean dummy) { if(!Utils.checkOVS()) return new QueuePusherResponse(QueuePusherResponseCode.OVS_NOT_FOUND); if(qosuuid == null || queueuuid == null) return new QueuePusherResponse(QueuePusherResponseCode.INVALID_ARGUMENTS); Object[] sw = QueuePusherSwitchMapper.getMatch(switchid); if(dummy) return new QueuePusherResponse(QueuePusherResponseCode.QP_DUMMY); String port = uuidToPort.remove(qosuuid); String cmd = ""; if(port != null) { cmd = Utils.OVS + " --db=tcp:" + (String)sw[0] + ":9091 -- clear Port " + port + " qos"; logger.info("RUNNING: "+cmd); Utils.eval(cmd); } else { logger.warn("Port matching returned NULL"); } String newQosUuid = null; Object[] rsp = new Object[] { (int)1, "Floodlight returned NULL ip address" }; if(sw[0] != null) { cmd = Utils.OVS + " --db=tcp:" + (String)sw[0] + ":9091 -- destroy QoS " + qosuuid; logger.info("RUNNING: "+cmd); rsp = Utils.eval(cmd); cmd = Utils.OVS + " --db=tcp:" + (String)sw[0] + ":9091 -- destroy queue " + queueuuid; logger.info("RUNNING: "+cmd); Utils.eval(cmd); if((Integer)rsp[0] == 0) { try { int qid = uuidToQoSId.remove(qosuuid); idsInUse.remove(qid); } catch(Exception ex) { } } switchPortWithQueue.remove(switchid+port); newQosUuid = reinstateQueues(switchid, port, qosuuid, queueuuid); if(newQosUuid == null) { newQosUuid = ""; } else { newQosUuid += "\n"; } } else { logger.warn("Floodlight returned NULL ip address"); } return new QueuePusherResponse((Integer)rsp[0] == 0 ? QueuePusherResponseCode.SUCCESS : QueuePusherResponseCode.DELETE_FAIL, newQosUuid+(String)rsp[1], (String)rsp[2]); } private static String reinstateQueues(String switchid, String port, String qosuuid, String removedQueue) { Object[] sw = QueuePusherSwitchMapper.getMatch(switchid); String cmd = Utils.OVS + " --db=tcp:" + (String)sw[0] + ":9091 set port " + port + " qos=@leqos -- --id=@leqos " + "create qos type=linux-htb other-config:max-rate=10000000000000000000000000 queues="; List<Queue> installedQueues = qosUuidToQueues.remove(qosuuid); Queue toRemove = null; boolean start = true; for(Queue q : installedQueues) { if(!removedQueue.equalsIgnoreCase(q.uuid)) { cmd += (start ? "" : ",")+q.qid+"="+q.uuid; start = false; } else { toRemove = q; } } installedQueues.remove(toRemove); logger.info("RUNNING: "+cmd); Object[] rsp = Utils.eval(cmd); if((Integer)rsp[0] == 0) { switchPortWithQueue.put(switchid+port, ((String)rsp[1]).substring(0, 36)); uuidToQoSId.put(((String)rsp[1]).substring(0, 36), qid); uuidToPort.put(((String)rsp[1]).substring(0, 36), port); qosUuidToQueues.put(((String)rsp[1]).substring(0, 36), installedQueues); return ((String)rsp[1]).substring(0, 36); } else { return null; } } /** * Modifies a QoS slice * * @param switchid Switch DPID * @param uuid UUID of the queue to modify * @param rate New rate of the queue * @return */ public static QueuePusherResponse modifySlice(String switchid, String qosuuid, String queueuuid, int rate, boolean dummy) { deleteQoS(switchid, qosuuid, queueuuid, dummy); return createSlice(switchid, QueuePusherSwitchMapper.portMatcher.get(queueuuid), rate, dummy); } /** * Checks the existence of OVS binary on the system PATH * * @return Successful execution */ public static boolean checkOVS() { Runtime rt = Runtime.getRuntime(); Process proc = null; try { proc = rt.exec("which " + OVS); proc.waitFor(); return proc.exitValue() == 0 ? true : false; } catch (InterruptedException e) { return false; } catch(IOException e) { return false; } } /** * Runs the given command * * @param cmd Command to execute * @return 0: (int)exit code 1: (string)stdout 2: (string)stderr */ public static Object[] eval(String cmd) { Object[] rsp = new Object[3]; Runtime rt = Runtime.getRuntime(); Process proc = null; try { proc = rt.exec(cmd); proc.waitFor(); rsp[0] = proc.exitValue(); } catch (IOException e) { rsp[0] = 1; } catch(InterruptedException e) { rsp[0] = 1; } finally { if(proc == null) { rsp[0] = 1; } else { try { BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String temp; StringBuilder sb = new StringBuilder(); while((temp = stdout.readLine()) != null) { sb.append(temp+"\n"); } rsp[1] = sb.toString(); sb = new StringBuilder(); while((temp = stderr.readLine()) != null) { sb.append(temp+"\n"); } rsp[2] = sb.toString(); } catch(IOException e) { rsp[0] = 1; } } } return rsp; } }
package com.intellij.openapi.command; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * A class for defining 'command' scopes. Every undoable change should be executed as part of a command. Commands can nest, in such a case * only the outer-most command is taken into account. Commands with the same 'group id' are merged for undo/redo purposes. 'Transparent' * actions (commands) are similar to usual commands but don't create a separate undo/redo step - they are undone/redone together with a * 'adjacent' non-transparent commands. */ public abstract class CommandProcessor { public static CommandProcessor getInstance() { return ServiceManager.getService(CommandProcessor.class); } /** * @deprecated use {@link #executeCommand(Project, Runnable, String, Object)} */ @Deprecated public abstract void executeCommand(@NotNull Runnable runnable, @Nullable String name, @Nullable Object groupId); public abstract void executeCommand(@Nullable Project project, @NotNull Runnable runnable, @Nullable String name, @Nullable Object groupId); public abstract void executeCommand(@Nullable Project project, @NotNull Runnable runnable, @Nullable String name, @Nullable Object groupId, @Nullable Document document); public abstract void executeCommand(@Nullable Project project, @NotNull Runnable runnable, @Nullable String name, @Nullable Object groupId, @NotNull UndoConfirmationPolicy confirmationPolicy); public abstract void executeCommand(@Nullable Project project, @NotNull Runnable command, @Nullable String name, @Nullable Object groupId, @NotNull UndoConfirmationPolicy confirmationPolicy, @Nullable Document document); /** * @param shouldRecordCommandForActiveDocument {@code false} if the action is not supposed to be recorded into the currently open document's history. * Examples of such actions: Create New File, Change Project Settings etc. * Default is {@code true}. */ public abstract void executeCommand(@Nullable Project project, @NotNull Runnable command, @Nullable String name, @Nullable Object groupId, @NotNull UndoConfirmationPolicy confirmationPolicy, boolean shouldRecordCommandForActiveDocument); public abstract void setCurrentCommandName(@Nullable String name); public abstract void setCurrentCommandGroupId(@Nullable Object groupId); @Nullable public abstract Runnable getCurrentCommand(); @Nullable public abstract String getCurrentCommandName(); @Nullable public abstract Object getCurrentCommandGroupId(); @Nullable public abstract Project getCurrentCommandProject(); /** * Defines a scope which contains undoable actions, for which there won't be a separate undo/redo step - they will be undone/redone along * with 'adjacent' command. */ public abstract void runUndoTransparentAction(@NotNull Runnable action); /** * @see #runUndoTransparentAction(Runnable) */ public abstract boolean isUndoTransparentActionInProgress(); public abstract void markCurrentCommandAsGlobal(@Nullable Project project); public abstract void addAffectedDocuments(@Nullable Project project, @NotNull Document... docs); public abstract void addAffectedFiles(@Nullable Project project, @NotNull VirtualFile... files); /** * @deprecated use {@link CommandListener#TOPIC} */ @Deprecated public abstract void addCommandListener(@NotNull CommandListener listener); /** * @deprecated use {@link CommandListener#TOPIC} */ @Deprecated public void addCommandListener(@NotNull CommandListener listener, @NotNull Disposable parentDisposable) { ApplicationManager.getApplication().getMessageBus().connect(parentDisposable).subscribe(CommandListener.TOPIC, listener); } /** * @deprecated use {@link CommandListener#TOPIC} */ @Deprecated public abstract void removeCommandListener(@NotNull CommandListener listener); }
package com.intellij.testFramework; import com.intellij.diagnostic.PerformanceWatcher; import com.intellij.execution.process.ProcessIOExecutorService; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.ShutDownTracker; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.newvfs.persistent.FlushingDaemon; import com.intellij.util.ObjectUtils; import com.intellij.util.ReflectionUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import org.jetbrains.io.NettyUtil; import org.junit.Assert; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.ForkJoinWorkerThread; import java.util.concurrent.TimeUnit; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import java.util.stream.Collectors; /** * @author cdr */ public class ThreadTracker { private static final Logger LOG = Logger.getInstance(ThreadTracker.class); private final Map<String, Thread> before; private final boolean myDefaultProjectInitialized; @TestOnly public ThreadTracker() { before = getThreads(); myDefaultProjectInitialized = ProjectManagerEx.getInstanceEx().isDefaultProjectInitialized(); } private static final Method getThreads = ObjectUtils.notNull(ReflectionUtil.getDeclaredMethod(Thread.class, "getThreads")); @NotNull public static Map<String, Thread> getThreads() { Thread[] threads; try { // faster than Thread.getAllStackTraces().keySet() threads = (Thread[])getThreads.invoke(null); } catch (Exception e) { throw new RuntimeException(e); } return ContainerUtil.newMapFromValues(ContainerUtil.iterate(threads), Thread::getName); } // contains prefixes of the thread names which are known to be long-running (and thus exempted from the leaking threads detection) private static final Set<String> wellKnownOffenders = new THashSet<>(); static { List<String> offenders = Arrays.asList( "AWT-EventQueue-", "AWT-Shutdown", "AWT-Windows", "Batik CleanerThread", "CompilerThread0", "External compiler", "Finalizer", FlushingDaemon.NAME, "IDEA Test Case Thread", "Image Fetcher ", "Java2D Disposer", "JobScheduler FJ pool ", "JPS thread pool", "Keep-Alive-Timer", "main", "Monitor Ctrl-Break", "Netty ", "ObjectCleanerThread", "Reference Handler", "RMI TCP Connection", "Signal Dispatcher", "timer-int", //serverIm, "timer-sys", //clientim, "TimerQueue", "UserActivityMonitor thread", "VM Periodic Task Thread", "VM Thread", "YJPAgent-Telemetry" ); List<String> sorted = offenders.stream().sorted(String::compareToIgnoreCase).collect(Collectors.toList()); if (!offenders.equals(sorted)) { String proper = StringUtil.join(ContainerUtil.map(sorted, s -> '"' + s + '"'), ",\n").replaceAll('"'+FlushingDaemon.NAME+'"', "FlushingDaemon.NAME"); throw new AssertionError("Thread names must be sorted (for ease of maintainance). Something like this will do:\n" + proper); } wellKnownOffenders.addAll(offenders); Application application = ApplicationManager.getApplication(); // LeakHunter might be accessed first time after Application is already disposed (during test framework shutdown). if (!application.isDisposed()) { longRunningThreadCreated(application, "Periodic tasks thread", "ApplicationImpl pooled thread ", ProcessIOExecutorService.POOLED_THREAD_PREFIX); } try { // init zillions of timers in e.g. MacOSXPreferencesFile Preferences.userRoot().flush(); } catch (BackingStoreException e) { throw new RuntimeException(e); } } // marks Thread with this name as long-running, which should be ignored from the thread-leaking checks public static void longRunningThreadCreated(@NotNull Disposable parentDisposable, @NotNull final String... threadNamePrefixes) { wellKnownOffenders.addAll(Arrays.asList(threadNamePrefixes)); Disposer.register(parentDisposable, () -> wellKnownOffenders.removeAll(Arrays.asList(threadNamePrefixes))); } @TestOnly public void checkLeak() throws AssertionError { ApplicationManager.getApplication().assertIsDispatchThread(); NettyUtil.awaitQuiescenceOfGlobalEventExecutor(100, TimeUnit.SECONDS); ShutDownTracker.getInstance().waitFor(100, TimeUnit.SECONDS); try { if (myDefaultProjectInitialized != ProjectManagerEx.getInstanceEx().isDefaultProjectInitialized()) return; // compare threads by name because BoundedTaskExecutor reuses application thread pool for different bounded pools, leaks of which we want to find Map<String, Thread> all = getThreads(); Map<String, Thread> after = new HashMap<>(all); after.keySet().removeAll(before.keySet()); Map<Thread, StackTraceElement[]> stackTraces = ContainerUtil.map2Map(after.values(), thread -> Pair.create(thread, thread.getStackTrace())); for (final Thread thread : after.values()) { if (thread == Thread.currentThread()) continue; ThreadGroup group = thread.getThreadGroup(); if (group != null && "system".equals(group.getName()))continue; if (!thread.isAlive()) continue; long start = System.currentTimeMillis(); //if (thread.isAlive()) { // System.err.println("waiting for " + thread + "\n" + ThreadDumper.dumpThreadsToString()); StackTraceElement[] traceBeforeWait = thread.getStackTrace(); if (shouldIgnore(thread, traceBeforeWait)) continue; int WAIT_SEC = 10; StackTraceElement[] stackTrace = traceBeforeWait; while (System.currentTimeMillis() < start + WAIT_SEC*1_000) { UIUtil.dispatchAllInvocationEvents(); // give blocked thread opportunity to die if it's stuck doing invokeAndWait() // afters some time the submitted task can finish and the thread become idle pool stackTrace = thread.getStackTrace(); if (shouldIgnore(thread, stackTrace)) break; } //long elapsed = System.currentTimeMillis() - start; //if (elapsed > 1_000) { // System.err.println("waited for " + thread + " for " + elapsed+"ms"); // check once more because the thread name may be set via race stackTraces.put(thread, stackTrace); if (shouldIgnore(thread, stackTrace)) continue; all.keySet().removeAll(after.keySet()); Map<Thread, StackTraceElement[]> otherStackTraces = ContainerUtil.map2Map(all.values(), t -> Pair.create(t, t.getStackTrace())); String trace = PerformanceWatcher.printStacktrace("", thread, stackTrace); String traceBefore = PerformanceWatcher.printStacktrace("", thread, traceBeforeWait); String internalDiagnostic = stackTrace.length < 5 ? "stackTrace.length: "+stackTrace.length : "(diagnostic: " + "0: "+ stackTrace[0].getClassName() + " : "+ stackTrace[0].getClassName().equals("sun.misc.Unsafe") + " . " +stackTrace[0].getMethodName() +" : "+ stackTrace[0].getMethodName().equals("unpark") + " 2: "+ stackTrace[2].getClassName() +" : "+ stackTrace[2].getClassName().equals("java.util.concurrent.FutureTask") + " . " + stackTrace[2].getMethodName() +" : " +stackTrace[2].getMethodName().equals("finishCompletion") + ")"; Assert.fail("Thread leaked: " +traceBefore + (trace.equals(traceBefore) ? "" : "(its trace after "+WAIT_SEC+" seconds wait:) "+trace)+ internalDiagnostic + "\n\nLeaking threads dump:\n" + dumpThreadsToString(after, stackTraces) + "\n----\nAll other threads dump:\n" + dumpThreadsToString(all, otherStackTraces)); } } finally { before.clear(); } } private static String dumpThreadsToString(Map<String, Thread> after, Map<Thread, StackTraceElement[]> stackTraces) { StringBuilder f = new StringBuilder(); after.forEach((name, thread) -> { f.append("\"" + name + "\" (" + (thread.isAlive() ? "alive" : "dead") + ") " + thread.getState() + "\n"); for (StackTraceElement element : stackTraces.get(thread)) { f.append("\tat " + element + "\n"); } f.append("\n"); }); return f.toString(); } private static boolean shouldIgnore(@NotNull Thread thread, @NotNull StackTraceElement[] stackTrace) { if (!thread.isAlive()) return true; if (isWellKnownOffender(thread.getName())) return true; if (stackTrace.length == 0) { return true; // ignore threads with empty stack traces for now. Seems they are zombies unwilling to die. } return isIdleApplicationPoolThread(stackTrace) || isIdleCommonPoolThread(thread, stackTrace) || isFutureTaskAboutToFinish(stackTrace) || isCoroutineSchedulerPoolThread(thread, stackTrace); } private static boolean isWellKnownOffender(@NotNull String threadName) { return ContainerUtil.exists(wellKnownOffenders, threadName::contains); } // true if somebody started new thread via "executeInPooledThread()" and then the thread is waiting for next task private static boolean isIdleApplicationPoolThread(@NotNull StackTraceElement[] stackTrace) { //noinspection UnnecessaryLocalVariable boolean insideTPEGetTask = Arrays.stream(stackTrace) .anyMatch(element -> element.getMethodName().equals("getTask") && element.getClassName().equals("java.util.concurrent.ThreadPoolExecutor")); return insideTPEGetTask; } private static boolean isIdleCommonPoolThread(@NotNull Thread thread, @NotNull StackTraceElement[] stackTrace) { if (!ForkJoinWorkerThread.class.isAssignableFrom(thread.getClass())) { return false; } //noinspection UnnecessaryLocalVariable boolean insideAwaitWork = Arrays.stream(stackTrace) .anyMatch(element -> element.getMethodName().equals("awaitWork") && element.getClassName().equals("java.util.concurrent.ForkJoinPool")); return insideAwaitWork; } // in newer JDKs strange long hangups observed in Unsafe.unpark: // "Document Committing Pool" (alive) TIMED_WAITING // at sun.misc.Unsafe.unpark(Native Method) // at java.util.concurrent.locks.LockSupport.unpark(LockSupport.java:141) // at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:372) // at java.util.concurrent.FutureTask.set(FutureTask.java:233) // at java.util.concurrent.FutureTask.run(FutureTask.java:274) // at com.intellij.util.concurrency.BoundedTaskExecutor.doRun(BoundedTaskExecutor.java:207) // at com.intellij.util.concurrency.BoundedTaskExecutor.access$100(BoundedTaskExecutor.java:29) // at com.intellij.util.concurrency.BoundedTaskExecutor$1.lambda$run$0(BoundedTaskExecutor.java:185) // at com.intellij.util.concurrency.BoundedTaskExecutor$1$$Lambda$157/1473781324.run(Unknown Source) // at com.intellij.util.ConcurrencyUtil.runUnderThreadName(ConcurrencyUtil.java:208) // at com.intellij.util.concurrency.BoundedTaskExecutor$1.run(BoundedTaskExecutor.java:181) // at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) // at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) // at java.lang.Thread.run(Thread.java:748) private static boolean isFutureTaskAboutToFinish(@NotNull StackTraceElement[] stackTrace) { if (stackTrace.length < 5) { return false; } return stackTrace[0].getClassName().equals("sun.misc.Unsafe") && stackTrace[0].getMethodName().equals("unpark") && stackTrace[2].getClassName().equals("java.util.concurrent.FutureTask") && stackTrace[2].getMethodName().equals("finishCompletion"); } private static boolean isCoroutineSchedulerPoolThread(@NotNull Thread thread, @NotNull StackTraceElement[] stackTrace) { if (!"kotlinx.coroutines.scheduling.CoroutineScheduler$Worker".equals(thread.getClass().getName())) { return false; } //noinspection UnnecessaryLocalVariable boolean insideCpuWorkerIdle = Arrays.stream(stackTrace) .anyMatch(element -> element.getMethodName().equals("cpuWorkerIdle") && element.getClassName().equals("kotlinx.coroutines.scheduling.CoroutineScheduler$Worker")); return insideCpuWorkerIdle; } public static void awaitJDIThreadsTermination(int timeout, @NotNull TimeUnit unit) { awaitThreadTerminationWithParentParentGroup("JDI main", timeout, unit); } private static void awaitThreadTerminationWithParentParentGroup(@NotNull final String grandThreadGroup, int timeout, @NotNull TimeUnit unit) { long start = System.currentTimeMillis(); while (System.currentTimeMillis() < start + unit.toMillis(timeout)) { Thread jdiThread = ContainerUtil.find(getThreads().values(), thread -> { ThreadGroup group = thread.getThreadGroup(); return group != null && group.getParent() != null && grandThreadGroup.equals(group.getParent().getName()); }); if (jdiThread == null) { break; } try { long timeLeft = start + unit.toMillis(timeout) - System.currentTimeMillis(); LOG.debug("Waiting for the "+jdiThread+" for " + timeLeft+"ms"); jdiThread.join(timeLeft); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }
import com.sun.star.beans.XPropertySet; import com.sun.star.frame.DispatchDescriptor; import com.sun.star.frame.FrameSearchFlag; import com.sun.star.frame.XController; import com.sun.star.frame.XDesktop; import com.sun.star.frame.XDispatch; import com.sun.star.frame.XDispatchProvider; import com.sun.star.frame.XFrame; import com.sun.star.frame.XModel; import com.sun.star.frame.XStatusListener; import com.sun.star.lang.XInitialization; import com.sun.star.lang.XServiceInfo; import com.sun.star.lang.XSingleComponentFactory; import com.sun.star.lib.uno.helper.WeakBase; import com.sun.star.registry.XRegistryKey; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; import com.sun.star.lib.uno.helper.Factory; public class InspectorAddon { /** This class implements the component. At least the interfaces XServiceInfo, * XTypeProvider, and XInitialization should be provided by the service. */ public static class InspectorAddonImpl extends WeakBase implements XDispatchProvider, XInitialization, XServiceInfo { private static XModel xModel = null; org.openoffice.XInstanceInspector xInstInspector = null; // Dispatcher oDispatcher = null; XFrame m_xFrame = null; private static final String[] m_serviceNames = { "org.openoffice.InstanceInspectorAddon", "com.sun.star.frame.ProtocolHandler" }; ; private XComponentContext m_xContext = null; /** Creates a new instance of InspectorAddon */ public InspectorAddonImpl(XComponentContext _xContext) { m_xContext = _xContext; } public XDispatch queryDispatch( com.sun.star.util.URL aURL, String sTargetFrameName, int iSearchFlags ) { XDispatch xRet = null; if ( aURL.Protocol.compareTo("org.openoffice.Office.addon.Inspector:") == 0 ) { if ( aURL.Path.compareTo( "inspect" ) == 0 ){ // Todo: Check if the frame is already administered (use hashtable) xRet = new Dispatcher(m_xFrame); } } return xRet; } public XDispatch[] queryDispatches( DispatchDescriptor[] seqDescripts ) { int nCount = seqDescripts.length; XDispatch[] lDispatcher = new XDispatch[nCount]; for( int i=0; i<nCount; ++i ) lDispatcher[i] = queryDispatch( seqDescripts[i].FeatureURL, seqDescripts[i].FrameName, seqDescripts[i].SearchFlags ); return lDispatcher; } public void initialize( Object[] object ) throws com.sun.star.uno.Exception { if ( object.length > 0 ){ m_xFrame = ( XFrame ) UnoRuntime.queryInterface(XFrame.class, object[ 0 ] ); } } public class Dispatcher implements XDispatch{ private XFrame m_xFrame = null; private XModel xModel = null; public Dispatcher(XFrame _xFrame){ m_xFrame = _xFrame; if (m_xFrame != null){ XController xController = m_xFrame.getController(); if (xController != null){ xModel = xController.getModel(); } } } // XDispatch public void dispatch( com.sun.star.util.URL _aURL, com.sun.star.beans.PropertyValue[] aArguments ) { try{ if ( _aURL.Protocol.compareTo("org.openoffice.Office.addon.Inspector:") == 0 ){ if ( _aURL.Path.equals("inspect")){ Object oUnoInspectObject = xModel; com.sun.star.lang.XMultiComponentFactory xMCF = m_xContext.getServiceManager(); if (xInstInspector == null){ Object obj= xMCF.createInstanceWithContext("org.openoffice.InstanceInspector", m_xContext); xInstInspector = (org.openoffice.XInstanceInspector)UnoRuntime.queryInterface(org.openoffice.XInstanceInspector.class, obj); } if ((m_xFrame == null) || (xModel == null)){ Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", m_xContext); m_xFrame = (XFrame) UnoRuntime.queryInterface(XFrame.class, oDesktop); oUnoInspectObject = m_xFrame; } XPropertySet xFramePropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, m_xFrame); String sTitle = (String) xFramePropertySet.getPropertyValue("Title"); String[] sTitleList = sTitle.split(" - "); if (sTitleList.length > 0){ sTitle = sTitleList[0]; } xInstInspector.inspect(oUnoInspectObject, sTitle); } } } catch( Exception e ) { System.err.println( e + e.getMessage()); e.printStackTrace(System.out); }} public void addStatusListener( XStatusListener xControl, com.sun.star.util.URL aURL ) { } public void removeStatusListener( XStatusListener xControl, com.sun.star.util.URL aURL ) { } } public static String[] getServiceNames() { return m_serviceNames; } // Implement the interface XServiceInfo /** Get all supported service names. * @return Supported service names. */ public String[] getSupportedServiceNames() { return getServiceNames(); } // Implement the interface XServiceInfo /** Test, if the given service will be supported. * @param sService Service name. * @return Return true, if the service will be supported. */ public boolean supportsService( String sServiceName ) { int len = m_serviceNames.length; for( int i=0; i < len; i++) { if ( sServiceName.equals( m_serviceNames[i] ) ) return true; } return false; } // Implement the interface XServiceInfo /** Get the implementation name of the component. * @return Implementation name of the component. */ public String getImplementationName() { return InspectorAddonImpl.class.getName(); } } /** * Gives a factory for creating the service. * This method is called by the <code>JavaLoader</code> * <p> * @return returns a <code>XSingleComponentFactory</code> for creating * the component * @param sImplName the name of the implementation for which a * service is desired * @see com.sun.star.comp.loader.JavaLoader */ public static XSingleComponentFactory __getComponentFactory( String sImplName ) { XSingleComponentFactory xFactory = null; if ( sImplName.equals( InspectorAddonImpl.class.getName() ) ) xFactory = Factory.createComponentFactory(InspectorAddonImpl.class, InspectorAddonImpl.getServiceNames()); return xFactory; } /** * Writes the service information into the given registry key. * This method is called by the <code>JavaLoader</code> * <p> * @return returns true if the operation succeeded * @param regKey the registryKey * @see com.sun.star.comp.loader.JavaLoader */ public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) { return Factory.writeRegistryServiceInfo(InspectorAddonImpl.class.getName(), InspectorAddonImpl.getServiceNames(), regKey); } // __create( XComponentContext ){ }
package org.eclipse.n4js.resource; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.eclipse.core.resources.IResourceStatus; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.impl.NotificationImpl; import org.eclipse.emf.common.util.AbstractEList; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.SegmentSequence; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.common.util.WrappedException; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.URIConverter; import org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl; import org.eclipse.emf.ecore.resource.impl.ResourceImpl; import org.eclipse.emf.ecore.util.EContentAdapter; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.n4js.N4JSGlobals; import org.eclipse.n4js.conversion.AbstractN4JSStringValueConverter; import org.eclipse.n4js.conversion.LegacyOctalIntValueConverter; import org.eclipse.n4js.conversion.N4JSStringValueConverter; import org.eclipse.n4js.conversion.RegExLiteralConverter; import org.eclipse.n4js.n4JS.N4JSFactory; import org.eclipse.n4js.n4JS.N4JSPackage; import org.eclipse.n4js.n4JS.Script; import org.eclipse.n4js.parser.InternalSemicolonInjectingParser; import org.eclipse.n4js.projectModel.IN4JSCore; import org.eclipse.n4js.scoping.diagnosing.N4JSScopingDiagnostician; import org.eclipse.n4js.scoping.utils.CanLoadFromDescriptionHelper; import org.eclipse.n4js.ts.scoping.builtin.BuiltInSchemeRegistrar; import org.eclipse.n4js.ts.types.SyntaxRelatedTElement; import org.eclipse.n4js.ts.types.TModule; import org.eclipse.n4js.ts.types.TypesPackage; import org.eclipse.n4js.utils.EcoreUtilN4; import org.eclipse.n4js.utils.emf.ProxyResolvingEObjectImpl; import org.eclipse.n4js.utils.emf.ProxyResolvingResource; import org.eclipse.xtext.diagnostics.DiagnosticMessage; import org.eclipse.xtext.diagnostics.ExceptionDiagnostic; import org.eclipse.xtext.nodemodel.INode; import org.eclipse.xtext.nodemodel.SyntaxErrorMessage; import org.eclipse.xtext.parser.IParseResult; import org.eclipse.xtext.resource.IDerivedStateComputer; import org.eclipse.xtext.resource.IEObjectDescription; import org.eclipse.xtext.resource.IFragmentProvider; import org.eclipse.xtext.resource.IResourceDescription; import org.eclipse.xtext.resource.IResourceDescriptions; import org.eclipse.xtext.resource.XtextSyntaxDiagnostic; import org.eclipse.xtext.resource.XtextSyntaxDiagnosticWithRange; import org.eclipse.xtext.util.CancelIndicator; import org.eclipse.xtext.util.IResourceScopeCache; import org.eclipse.xtext.util.OnChangeEvictingCache; import org.eclipse.xtext.util.Triple; import com.google.common.base.Throwables; import com.google.inject.Inject; /** * Special resource that stores the N4JS AST in slot 0, and types exported by this module as containments of a * {@link TModule} in slot 1. * <p> * Usually, the root elements of the contents are no proxies. Thus, these elements are not resolved by the default * contents implementations ({@link org.eclipse.emf.ecore.resource.impl.ResourceImpl.ContentsEList} etc.). As the first * slot, the actual AST, could be a proxy (we usually do not want to parse the AST if we want to access the type * information), and thus it must be able to resolve this first element. This is transparently done in the custom * contents class {@link ModuleAwareContentsList}. */ public class N4JSResource extends PostProcessingAwareResource implements ProxyResolvingResource { private final class ModuleAwareContentsList extends ContentsEList<EObject> { private static final long serialVersionUID = 1L; public ModuleAwareContentsList() { } /** * If the first element, that is the AST, is requested (index == 0) and if it is a proxy (because the resource * has not really been loaded but created with the type information from the xtext index), then this element is * actually loaded and the type information, formally loaded from the IObjectDescrition's user data is replace * with the newly retrieved information. * * In all other cases {@link AbstractEList#resolve(int, Object)} will be invoked. */ @Override protected EObject resolve(int index, EObject object) { if (index == 0 && !aboutToBeUnloaded && isASTProxy(object)) { EObject result = demandLoadResource(object); return result; } return super.resolve(index, object); } /** * Do not propagate any notifications that the AST has been modified or loaded, if the given object is the * proxified AST. */ @Override protected void didAdd(int index, EObject object) { if (index == 0 && isASTProxy(object)) return; super.didAdd(index, object); } /** * Don't announce any notification but keep the inverse references in sync. * * @param object * the to-be-added object */ protected void sneakyAdd(EObject object) { sneakyGrow(size + 1); assign(size, validate(size, object)); size++; inverseAdd(object, null); } /** * Creates a new array for the content. The calculation of its new size is optimized related to the last size * and the minimum required size. This method is called by {@link ModuleAwareContentsList#sneakyAdd(EObject)} * and {@link ModuleAwareContentsList#sneakyAdd(int, EObject)}. * * @param minimumCapacity * the expected minimumCapacity of the list. */ private void sneakyGrow(int minimumCapacity) { int oldCapacity = data == null ? 0 : data.length; if (minimumCapacity > oldCapacity) { Object oldData[] = data; // This seems to be a pretty sweet formula that supports good // growth. // Adding an object to a list will create a list of capacity 4, // which is just about the average list size. int newCapacity = oldCapacity + oldCapacity / 2 + 4; if (newCapacity < minimumCapacity) { newCapacity = minimumCapacity; } data = newData(newCapacity); if (oldData != null) { System.arraycopy(oldData, 0, data, 0, size); } } } /** * Don't announce any notification but keep the inverse references in sync. * * @param index * the index where the object should be added to * @param object * the to-be-added object */ protected void sneakyAdd(int index, EObject object) { sneakyGrow(size + 1); EObject validatedObject = validate(index, object); if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } assign(index, validatedObject); ++size; inverseAdd(object, null); } /* Copied and stripped down from super.clear() */ /** * Avoid changes to the mod counter and events */ protected void sneakyClear() { List<EObject> collection = new UnmodifiableEList<>(size, data); sneakyDoClear(); for (Iterator<EObject> i = collection.iterator(); i.hasNext();) { inverseRemove(i.next(), null); } } private void sneakyDoClear() { data = null; size = 0; } } private static final Logger logger = Logger.getLogger(N4JSResource.class); /** artificial fragment to use for the URL of the proxified first slot */ public static final String AST_PROXY_FRAGMENT = ":astProxy"; /** * Set by the dirty state support to announce an upcoming unloading request. */ private boolean aboutToBeUnloaded; /** * Set to true while we are currently discarding an adapter. */ private boolean removingAdapters; @Inject private N4JSScopingDiagnostician scopingDiagnostician; @Inject private BuiltInSchemeRegistrar registrar; @Inject private IN4JSCore n4jsCore; @Inject private CanLoadFromDescriptionHelper canLoadFromDescriptionHelper; @Inject private IDerivedStateComputer myDerivedStateComputer; /* * Even though the constructor is empty, it simplifies debugging (allows to set a breakpoint) thus we keep it here. */ /** * Public default constructor. */ public N4JSResource() { super(); } /** * Tells if this resource had its AST loaded from source after its TModule was created and has thus an AST that was * reconciled with a pre-existing TModule. This can happen when * <ol> * <li>an AST is loaded from source after the TModule was loaded from the index (usually triggered by client code * via <code>#getContents(0)</code> or {@link SyntaxRelatedTElement#getAstElement()}). * <li>an AST is re-loaded after it was loaded from source and then unloaded via {@link #unloadAST()}. * </ol> */ public boolean isReconciled() { final TModule module = getModule(); return module != null && module.isReconciled(); } @Override protected URIConverter getURIConverter() { return getResourceSet() == null ? createNewURIConverter() : getResourceSet().getURIConverter(); } private URIConverter createNewURIConverter() { URIConverter result = new ExtensibleURIConverterImpl(); registrar.registerScheme(result); return result; } @Override public synchronized EList<EObject> getContents() { if (!removingAdapters) { return super.getContents(); } else { return doGetContents(); } } /** * Create a customized contents list, to handle a proxified first slot and a second slot holding the types model. */ @Override protected EList<EObject> doGetContents() { if (contents == null) { contents = new ModuleAwareContentsList(); } return contents; } @Override public EList<Adapter> eAdapters() { if (eAdapters == null) { eAdapters = new EAdapterList<Adapter>(this) { @Override protected void didRemove(int index, Adapter oldObject) { boolean wasRemoving = removingAdapters; try { removingAdapters = true; super.didRemove(index, oldObject); } finally { removingAdapters = wasRemoving; } } }; } return eAdapters; } /** * Populate the contents list from the serialized type data of an {@link IEObjectDescription}. See * {@link #isLoadedFromDescription()} for details on resources that are being loaded from a description. * * @param description * the description that carries the type data in its user data */ public boolean loadFromDescription(IResourceDescription description) { if (isLoaded) throw new IllegalStateException("Resource was already loaded"); boolean wasDeliver = eDeliver(); try { eSetDeliver(false); ModuleAwareContentsList theContents = (ModuleAwareContentsList) getContents(); if (!theContents.isEmpty()) throw new IllegalStateException("There is already something in the contents list: " + theContents); InternalEObject astProxy = (InternalEObject) N4JSFactory.eINSTANCE.createScript(); astProxy.eSetProxyURI(URI.createURI("#" + AST_PROXY_FRAGMENT)); theContents.sneakyAdd(astProxy); boolean didLoadModule = false; Iterable<IEObjectDescription> modules = description.getExportedObjectsByType(TypesPackage.Literals.TMODULE); for (IEObjectDescription module : modules) { TModule deserializedModule = UserdataMapper.getDeserializedModuleFromDescription(module, getURI()); if (deserializedModule != null) { theContents.sneakyAdd(deserializedModule); didLoadModule = true; break; } } // TODO: It is possible that TModule is null (e.g. if a module becomes invalid and thus // ResourceDescriptionWithoutUserData is created and stored in the index). // In that case, contents has an AST proxy without TModule. Is this an allowed state?? if (didLoadModule) { fullyInitialized = true; // TModule loaded from index had been fully post-processed prior to serialization fullyPostProcessed = true; return true; } else { return false; } } finally { eSetDeliver(wasDeliver); } } /** * Returns true iff the receiving resource is in the intermediate state of having the module loaded from the index * (or created in some other way) but the AST is still unloaded, i.e. the contents list contains an * {@link #isASTProxy(EObject) AST proxy} at index 0 and a non-proxy TModule at index 1. * <p> * Some notes: * <ol> * <li>here, "loaded from description" means "loaded from IResourceDescription / IEObjectDescription" or "loaded * from Xtext index". * <li>once the resource is fully loaded, i.e. also the AST has been loaded, this method will return {@code false}. * <li>while in the loaded-from-description state, the {@link #isLoaded() isLoaded} flag may be {@code true} or * {@code false}. This means, from the outside, such a resource may seem to be loaded or unloaded. * </ol> * Thus, an N4JSResource has 4 states and the following table shows what the {@link #getContents() contents} list * contains in each of those states: * <!-- @formatter:off --> * <table border=1> * <tr><th colspan=2 rowspan=2></th><th colspan=2>isLoadedFromDescription</th></tr> * <tr><th>false</th><th>true</th></tr> * <tr><th rowspan=2>isLoaded</th><th>false</th><td>empty</td><td>AST proxy + TModule</td></tr> * <tr><th>true</th><td>AST + TModule</td><td>AST proxy + TModule</td></tr> * </table> * <!-- @formatter:on --> * Note how the {@link #isLoaded() isLoaded} flag does not have any impact on the resource's actual contents in case * {@code isLoadedFromDescription} is {@code true}. */ public boolean isLoadedFromDescription() { final Script script = getScript(); final TModule module = getModule(); return script != null && module != null && isASTProxy(script) && !module.eIsProxy(); } /** * Adds just a check, that a not loaded resource is not allowed to be saved. */ @Override public void doSave(OutputStream outputStream, Map<?, ?> options) throws IOException { if (!isLoaded()) { throw new IllegalStateException("Attempt to save a resource that was not loaded: " + getURI()); } super.doSave(outputStream, options); } /** * * Discards the current content of the resource, sets the parser result as first slot, installs derived state (this * will build up the second slot again) and sends notifications that proxies have been resolved. The resource will * be even loaded if its already marked as loaded. * * If the second slot, that is the TModule, was already loaded and we just resolved the AST, then the existing * TModule is kept in the resource and rewired to the resolved AST. * * @param object * the object which resource should be loaded * @return the loaded/resolved object */ private EObject demandLoadResource(EObject object) { TModule oldModule = null; EObject oldScript = null; ModuleAwareContentsList myContents = ((ModuleAwareContentsList) contents); try { oldModule = discardStateFromDescription(false); if (!myContents.isEmpty()) { oldScript = myContents.basicGet(0); myContents.sneakyClear(); } // now everything is removed from the resource and contents is empty // stop sending notifications eSetDeliver(false); if (isLoaded) { // Loads the resource even its marked as being already loaded isLoaded = false; } superLoad(null); // manually send the notification eSetDeliver(true); EObject result = getParseResult().getRootASTElement(); if (myContents.isEmpty()) { myContents.sneakyAdd(0, result); if (oldModule != null) { myContents.sneakyAdd(oldModule); } forceInstallDerivedState(false); } else { if (myContents.size() == 1) { if (oldModule != null) { myContents.sneakyAdd(oldModule); } } installDerivedState(false); } if (oldScript != null) { notifyProxyResolved(0, oldScript); } fullyPostProcessed = false; return result; } catch (IOException | IllegalStateException ioe) { if (myContents.isEmpty()) { myContents.sneakyAdd(oldScript); myContents.sneakyAdd(oldModule); } Throwable cause = ioe.getCause(); if (cause instanceof CoreException) { IStatus status = ((CoreException) cause).getStatus(); if (IResourceStatus.RESOURCE_NOT_FOUND == status.getCode()) { return object; } } logger.error("Error in demandLoadResource for " + getURI(), ioe); return object; } } @SuppressWarnings("restriction") private void superLoad(Map<?, ?> options) throws IOException { super.load(options); } private void forceInstallDerivedState(boolean preIndexingPhase) { if (!isLoaded) throw new IllegalStateException("The resource must be loaded, before installDerivedState can be called."); fullyInitialized = false; isInitializing = false; installDerivedState(preIndexingPhase); } /** * Creates a custom notification and sends it for proxy and loaded object. Registers adapters to loaded object. * * @param idx * index in the contents list (first or second slot) * @param oldProxy * the proxified object before being loaded */ protected void notifyProxyResolved(int idx, EObject oldProxy) { if (eNotificationRequired() && idx < contents.size()) { EObject newObject = contents.basicGet(idx); Notification notification = new NotificationImpl(Notification.RESOLVE, oldProxy, newObject) { @Override public Object getNotifier() { return N4JSResource.this; } @Override public int getFeatureID(Class<?> expectedClass) { return RESOURCE__CONTENTS; } }; eNotify(notification); for (Adapter adapter : eAdapters()) { if (adapter instanceof EContentAdapter && !newObject.eAdapters().contains(adapter)) { newObject.eAdapters().add(adapter); } } } } /** * See {@link ModuleAwareContentsList#sneakyAdd(EObject)}. */ public void sneakyAddToContent(EObject object) { ((ModuleAwareContentsList) contents).sneakyAdd(object); } /** * Overridden to make sure that we add the root AST element sneakily to the resource list to make sure that no * accidental proxy resolution happens and that we do not increment the modification counter of the contents list. */ @Override protected void updateInternalState(IParseResult newParseResult) { setParseResult(newParseResult); EObject newRootAstElement = newParseResult.getRootASTElement(); if (newRootAstElement != null && !getContents().contains(newRootAstElement)) { // do not increment the modification counter here sneakyAddToContent(newRootAstElement); } reattachModificationTracker(newRootAstElement); clearErrorsAndWarnings(); addSyntaxErrors(); doLinking(); // make sure that the cache adapter is installed on this resource IResourceScopeCache cache = getCache(); if (cache instanceof OnChangeEvictingCache) { ((OnChangeEvictingCache) cache).getOrCreate(this); } } /** * Minor optimization, do no lazily create warnings and error objects. */ @Override protected void clearErrorsAndWarnings() { if (warnings != null) warnings.clear(); if (errors != null) errors.clear(); } /** * Ensures that state is discarded before loading (i.e. the second slot is unloaded). */ @Override protected void doLoad(InputStream inputStream, Map<?, ?> options) throws IOException { if (contents != null && !contents.isEmpty()) { discardStateFromDescription(true); } super.doLoad(inputStream, options); } @Override protected void doUnload() { aboutToBeUnloaded = false; super.doUnload(); // These are cleared when linking takes place., but we eagerly clear them here as a memory optimization. clearLazyProxyInformation(); } /** * Unloads the AST, but leaves the type model intact. Calling this method puts this resource into the same state as * if it was loaded from the index. * * <ul> * <li>The AST is discarded and all references to it are proxified.</li> * <li>The parse result (node model) is set to <code>null</code>.</li> * <li>All errors and warnings are cleared.</li> * <li>The flags are set as follows: * <ul> * <li><code>reconciled</code> is <code>false</code></li> * <li><code>fullyInitialized</code> remains unchanged</li> * <li><code>fullyPostProcessed</code> is set to the same value as <code>fullyInitialized</code></li> * <li><code>aboutToBeUnloaded</code> is <code>false</code></li> * <li><code>isInitializing</code> is <code>false</code></li> * <li><code>isLoading</code> is <code>false</code></li> * <li><code>isLoaded</code> is <code>false</code></li> * <li><code>isPostProcessing</code> is <code>false</code></li> * <li><code>isUpdating</code> is <code>false</code></li> * <li><code>isLoadedFromStorage</code> is unchanged due to API restrictions</li> * </ul> * </li> * <li>Finally, all lazy proxy information is cleared by calling {@link #clearLazyProxyInformation()}.</li> * </ul> * Calling this method takes the resources either to the same state as if it was just created, or to the same state * as if it was just loaded from a resource description, depending on which state the resource is in. * <ul> * <li>If the resource was just <b>created</b>, then it will remain so.</li> * <li>If the resource was <b>loaded</b>, then it will be taken back to the <b>created</b> state.</li> * <li>If the resource was <b>initialized</b>, then it will be taken to the <b>loaded from description</b> * state.</li> * <li>If the resource was <b>fully processed</b>, then it will be taken to the <b>loaded from description</b> * state.</li> * <li>If the resource was <b>loaded from description</b>, then it will remain so.</li> * </ul> */ public void unloadAST() { if (getScript() == null || getScript().eIsProxy()) { // We are either freshly created and not loaded or we are loaded from resource description and thus already // have an AST proxy. return; } // Discard AST and proxify all references. discardAST(); // Discard the parse result (node model). setParseResult(null); // Clear errors and warnings. getErrors().clear(); getWarnings().clear(); fullyPostProcessed = fullyInitialized; aboutToBeUnloaded = false; isInitializing = false; isLoading = false; isLoaded = false; isPostProcessing = false; isUpdating = false; // We cannot call this method because it is not API. We leave this comment as documentation that the flag // isLoadedFromStorage should be false at this point. // setIsLoadedFromStorage(false); // These are cleared when linking takes place., but we eagerly clear them here as a memory optimization. clearLazyProxyInformation(); // clear flag 'reconciled' in TModule (if required) final TModule module = getModule(); if (module != null && module.isReconciled()) { EcoreUtilN4.doWithDeliver(false, () -> { module.setReconciled(false); }, module); } } /** * Sends a is loaded notification if the content is not empty and sets the resource being fully initialized but does * not actually invoke load. Load is only called when the content is empty. This behavior prevents loading the * resource when e.g. calling EcoreUtil.resolve which would try to load the resource as its first slot is marked as * proxy. */ @Override public void load(Map<?, ?> options) throws IOException { if (contents != null && !contents.isEmpty()) { Notification notification = setLoaded(true); if (notification != null) { eNotify(notification); } setModified(false); fullyInitialized = contents.size() > 1; } else { superLoad(options); } } /** * To prepare unloading. */ public void forceSetLoaded() { isLoaded = true; aboutToBeUnloaded = true; } /** * Discard the AST and proxify all referenced nodes. Does nothing if the AST is already unloaded. */ private void discardAST() { EObject script = getScript(); if (script != null && !script.eIsProxy()) { // Create a proxy for the AST. InternalEObject scriptProxy = (InternalEObject) EcoreUtil.create(script.eClass()); scriptProxy.eSetProxyURI(EcoreUtil.getURI(script)); TModule module = null; ModuleAwareContentsList theContents = (ModuleAwareContentsList) contents; if (isFullyInitialized()) { module = getModule(); if (module != null && !module.eIsProxy()) { proxifyASTReferences(module); module.setAstElement(scriptProxy); } } // Unload the AST. unloadElements(theContents.subList(0, 1)); theContents.sneakyClear(); if (module != null) { theContents.sneakyAdd(scriptProxy); theContents.sneakyAdd(module); } else { // there was no module (not even a proxy) // -> don't add the script proxy // (i.e. transition from resource load state "Loaded" to "Created", not to "Loaded from Description") } getCache().clear(this); } } private void proxifyASTReferences(EObject object) { if (object instanceof SyntaxRelatedTElement) { SyntaxRelatedTElement element = (SyntaxRelatedTElement) object; EObject astElement = element.getAstElement(); if (astElement != null && !astElement.eIsProxy()) { InternalEObject proxy = (InternalEObject) EcoreUtil.create(astElement.eClass()); proxy.eSetProxyURI(EcoreUtil.getURI(astElement)); element.setAstElement(proxy); } } for (EObject child : object.eContents()) { proxifyASTReferences(child); } } protected TModule discardStateFromDescription(boolean unload) { ModuleAwareContentsList theContents = (ModuleAwareContentsList) contents; if (theContents != null && !theContents.isEmpty()) { if (theContents.size() == 2) { EObject eObject = theContents.get(1); if (eObject instanceof TModule) { TModule module = (TModule) eObject; if (unload) { getUnloader().unloadRoot(module); } return module; } getUnloader().unloadRoot(eObject); return null; } else if (theContents.size() > 2) { throw new IllegalStateException("Unexpected size: " + theContents); } } return null; } /** * Specialized to allow reconciliation of the TModule. We need to handle invocations of * {@link #installDerivedState(boolean)} where the contents list does already contain two elements. */ @SuppressWarnings("restriction") @Override public void installDerivedState(boolean preIndexingPhase) { if (!isLoaded) throw new IllegalStateException("The resource must be loaded, before installDerivedState can be called."); if (!fullyInitialized && !isInitializing && !isLoadedFromStorage()) { // set fully initialized to true, so we don't try initializing again on error. boolean newFullyInitialized = true; try { isInitializing = true; if (myDerivedStateComputer != null) { EList<EObject> roots = doGetContents(); // change is here, the super class has a check that there is no derived state yet // but we want to reconcile it thus we need to allow two root elements if (roots.size() > 2) { throw new IllegalStateException( "The resource should not have more than two root elements, but: " + roots); } try { myDerivedStateComputer.installDerivedState(this, preIndexingPhase); } catch (Throwable e) { if (operationCanceledManager.isOperationCanceledException(e)) { doDiscardDerivedState(); // on cancellation we should try to initialize again next time newFullyInitialized = false; operationCanceledManager.propagateAsErrorIfCancelException(e); } throw Throwables.propagate(e); } } } catch (RuntimeException e) { getErrors().add(new ExceptionDiagnostic(e)); throw e; } finally { fullyInitialized = newFullyInitialized; isInitializing = false; try { getCache().clear(this); } catch (RuntimeException e) { // don't rethrow as there might have been an exception in the try block. logger.error(e.getMessage(), e); } } } } private void unloadElements(List<EObject> toBeUnloaded) { for (EObject object : toBeUnloaded) { getUnloader().unloadRoot(object); } } /** * If this resource contains an AST proxy a custom URI fragment calculation is provided. This prevents registering * an adapter that later would trigger loading the resource, which we do not want. */ @Override public String getURIFragment(EObject eObject) { if (eDeliver()) { if (contents != null && !contents.isEmpty() && isASTProxy(contents.basicGet(0))) { return defaultGetURIFragment(eObject); } return super.getURIFragment(eObject); } else { return defaultGetURIFragment(eObject); } } /** * Invoked from {@link ProxyResolvingEObjectImpl#eResolveProxy(InternalEObject)} whenever an EMF proxy inside an * N4JSResource is being resolved. The receiving resource is the resource containing the proxy, not necessarily the * resource the proxy points to. * * @param proxy * the proxy to resolve. * @param objectContext * the {@code EObject} contained in this resource that holds the given proxy. */ @Override public EObject doResolveProxy(InternalEObject proxy, EObject objectContext) { // step 1: trigger post processing of the resource containing 'proxy' iff it is the first proxy being resolved // (if another proxy has been resolved before, post processing will already be running/completed, and in that // case the next line will simply do nothing, cf. #performPostProcessing()) this.performPostProcessing(); // step 2: now turn to resolving the proxy at hand final URI targetUri = proxy.eProxyURI(); final boolean isLazyLinkingProxy = getEncoder().isCrossLinkFragment(this, targetUri.fragment()); if (!isLazyLinkingProxy) { // we have an ordinary EMF proxy (not one of Xtext's lazy linking proxies) ... final ResourceSet resSet = getResourceSet(); final URI targetResourceUri = targetUri.trimFragment(); final String targetFileExt = targetResourceUri.fileExtension(); if (N4JSGlobals.N4JS_FILE_EXTENSION.equals(targetFileExt) || N4JSGlobals.N4JSD_FILE_EXTENSION.equals(targetFileExt) || N4JSGlobals.N4JSX_FILE_EXTENSION.equals(targetFileExt)) { // proxy is pointing into an .n4js or .n4jsd file ... // check if we can work with the TModule from the index or if it is mandatory to load from source final boolean canLoadFromDescription = !targetUri.fragment().startsWith("/0") && canLoadFromDescriptionHelper.canLoadFromDescription(targetResourceUri, getResourceSet()); if (canLoadFromDescription) { final String targetFragment = targetUri.fragment(); final Resource targetResource = resSet.getResource(targetResourceUri, false); // special handling // if targetResource is not loaded yet, try to load it from index first if (targetResource == null) { if (targetFragment != null && (targetFragment.equals("/1") || targetFragment.startsWith("/1/"))) { // uri points to a TModule element in a resource not yet contained in our resource set // --> try to load target resource from index final IResourceDescriptions index = n4jsCore.getXtextIndex(resSet); final IResourceDescription resDesc = index.getResourceDescription(targetResourceUri); if (resDesc != null) { // next line will add the new resource to resSet.resources n4jsCore.loadModuleFromIndex(resSet, resDesc, false); } } } } // standard behavior: // obtain target EObject from targetResource in the usual way // (might load targetResource from disk if it wasn't loaded from index above) final EObject targetObject = resSet.getEObject(targetUri, true); // special handling // if targetResource exists, make sure it is post-processed *iff* this resource is post-processed // (only relevant in case targetResource wasn't loaded from index, because after loading from index it // is always marked as fullyPostProcessed==true) if (targetObject != null && (this.isProcessing() || this.isFullyProcessed())) { final Resource targetResource2 = targetObject.eResource(); if (targetResource2 instanceof N4JSResource) { // no harm done, if already running/completed ((N4JSResource) targetResource2).performPostProcessing(); } } // return resolved target object return targetObject != null ? targetObject : proxy; // important: return proxy itself if unresolvable! } } // we will get here if // a) we have an Xtext lazy linking proxy or // b) targetUri points to an n4ts resource or some other, non-N4JS resource // --> above special handling not required, so just apply EMF's default resolution behavior return EcoreUtil.resolve(proxy, this); } /** * Copied from {@link ResourceImpl#getEObjectForURIFragmentRootSegment(String)} only differs, that instead of * getContent contents is accessed directly. */ @Override protected EObject getEObjectForURIFragmentRootSegment(String uriFragmentRootSegment) { if (contents != null && !contents.isEmpty()) { if (isASTProxy(contents.basicGet(0))) { int position = 0; if (uriFragmentRootSegment.length() > 0) { try { // e.g. uriFragmentRootSegment could something like /1 position = Integer.parseInt(uriFragmentRootSegment); } catch (NumberFormatException exception) { throw new WrappedException(exception); } } // avoid invocation of getContent if (position < contents.size() && position >= 1) { return contents.get(position); } if (position >= 1 && isLoaded && isASTProxy(contents.basicGet(0)) && contents.size() == 1) { // requested position exceeds contents length // apparently we have an astProxy at index 0 but no module // was deserialized from the index // try to obtain the module from a freshly loaded ast // Note: this would be a good place to track when a proxified AST is being reloaded. contents.get(0); } } } return super.getEObjectForURIFragmentRootSegment(uriFragmentRootSegment); } /** * We don't use a {@link IFragmentProvider} here. The implementation is a complete copied from * {@link ResourceImpl#getURIFragment} * * @param eObject * the object the URI fragment should be calculated for. * @return the calculated URI fragment */ private String defaultGetURIFragment(EObject eObject) { // Copied from ResourceImpl.getURIFragment to avoid the caching // mechanism which will add a content // adapter which in turn will resolve / load the resource (while the // purpose of all the code is to // avoid resource loading) InternalEObject internalEObject = (InternalEObject) eObject; if (internalEObject.eDirectResource() == this || unloadingContents != null && unloadingContents.contains(internalEObject)) { return "/" + getURIFragmentRootSegment(eObject); } else { SegmentSequence.Builder builder = SegmentSequence.newBuilder("/"); boolean isContained = false; for (InternalEObject container = internalEObject .eInternalContainer(); container != null; container = internalEObject .eInternalContainer()) { builder.append(container.eURIFragmentSegment(internalEObject.eContainingFeature(), internalEObject)); internalEObject = container; if (container.eDirectResource() == this || unloadingContents != null && unloadingContents.contains(container)) { isContained = true; break; } } if (!isContained) { return "/-1"; } builder.append(getURIFragmentRootSegment(internalEObject)); builder.append(""); builder.reverse(); // This comment also resides in ResourceImpl.getURIFragment: // Note that we convert it to a segment sequence because the // most common use case is that callers of this method will call // URI.appendFragment. // By creating the segment sequence here, we ensure that it's // found in the cache. return builder.toSegmentSequence().toString(); } } /** * * @param object * the EObject to check * @return true, if the given object is a proxy and its fragment starts with {@link N4JSResource#AST_PROXY_FRAGMENT} * . */ protected boolean isASTProxy(EObject object) { if (object.eIsProxy()) { String fragment = EcoreUtil.getURI(object).fragment(); return fragment.equals(AST_PROXY_FRAGMENT); } return false; } @Override public Triple<EObject, EReference, INode> getLazyProxyInformation(int idx) { // note: following line was copied from the old index-URI implementation (the one that used field "uris") // to make the new implementation behave as the old one; whether doing a demand load here actually // makes sense remains to be reconsidered (see IDEBUG-257 and IDEBUG-233) ... contents.get(0); // trigger demand load if necessary return super.getLazyProxyInformation(idx); } /** * This is aware of warnings from the {@link N4JSStringValueConverter}. * * Issues from the parser are commonly treated as errors but here we want to create a warning. */ @Override protected void addSyntaxErrors() { if (isValidationDisabled()) return; // EList.add unnecessarily checks for uniqueness by default // so we use #addUnique below to save some CPU cycles for heavily broken // models BasicEList<Diagnostic> errorList = (BasicEList<Diagnostic>) getErrors(); BasicEList<Diagnostic> warningList = (BasicEList<Diagnostic>) getWarnings(); for (INode error : getParseResult().getSyntaxErrors()) { XtextSyntaxDiagnostic diagnostic = createSyntaxDiagnostic(error); String code = diagnostic.getCode(); if (AbstractN4JSStringValueConverter.WARN_ISSUE_CODE.equals(code) || RegExLiteralConverter.ISSUE_CODE.equals(code) || LegacyOctalIntValueConverter.ISSUE_CODE.equals(code)) { warningList.addUnique(diagnostic); } else if (!InternalSemicolonInjectingParser.SEMICOLON_INSERTED.equals(code)) { errorList.addUnique(diagnostic); } } } private XtextSyntaxDiagnostic createSyntaxDiagnostic(INode error) { SyntaxErrorMessage syntaxErrorMessage = error.getSyntaxErrorMessage(); if (org.eclipse.xtext.diagnostics.Diagnostic.SYNTAX_DIAGNOSTIC_WITH_RANGE.equals(syntaxErrorMessage .getIssueCode())) { String[] issueData = syntaxErrorMessage.getIssueData(); if (issueData.length == 1) { String data = issueData[0]; int colon = data.indexOf(':'); return new XtextSyntaxDiagnosticWithRange(error, Integer.valueOf(data.substring(0, colon)), Integer.valueOf(data.substring(colon + 1)), null) { @Override public int getLine() { return getNode().getTotalStartLine(); } }; } } return new XtextSyntaxDiagnostic(error); } // FIXME the following method should no longer be required once TypingASTWalker is fully functional @Override protected EObject handleCyclicResolution(Triple<EObject, EReference, INode> triple) throws AssertionError { // Don't throw exception for cyclic resolution of IdentifierRef.id or PropertyAccess.property // since this is currently unavoidable because type system and scoping don't work together // but have independent control flow logic. // This JS snippet will cause trouble: // function(a){ return a.b } // System.err.println("CYCLIC RESOLUTION FOR: " + NodeModelUtils.getTokenText(triple.getThird())); if (N4JSPackage.Literals.IDENTIFIER_REF__ID == triple.getSecond() || N4JSPackage.Literals.PARAMETERIZED_PROPERTY_ACCESS_EXPRESSION__PROPERTY == triple.getSecond()) { return null; } return super.handleCyclicResolution(triple); } /** * Convenience method to fully resolve all lazy cross-references and perform post-processing on the containing * N4JSResource of 'object'. Does nothing if 'object' is not contained in an N4JSResource. */ public static final void postProcessContainingN4JSResourceOf(EObject object) { if (object != null) postProcess(object.eResource()); } /** * Convenience method to fully resolve all lazy cross-references and perform post-processing on the N4JSResource * 'resource'. Does nothing if 'resource' is <code>null</code> or not an N4JSResource. */ public static final void postProcess(Resource resource) { if (resource instanceof N4JSResource && resource.isLoaded()) ((N4JSResource) resource).performPostProcessing(); } @Override public void performPostProcessing(CancelIndicator cancelIndicator) { // make sure post-processing is never performed in pre-linking phase final TModule module = getModule(); final boolean isPreLinkingPhase = module != null && module.isPreLinkingPhase(); if (!isPreLinkingPhase) { super.performPostProcessing(cancelIndicator); } } @Override public void resolveLazyCrossReferences(CancelIndicator mon) { // called from builder before resource descriptions are created + called from validator final Script script = getScriptResolved(); // need to be called before resolve() since that one injects a proxy // at resource.content[0] super.resolveLazyCrossReferences(mon); if (script != null) { // FIXME freezing of used imports tracking can/should now be moved to N4JSPostProcessor or ASTProcessor EcoreUtilN4.doWithDeliver(false, // freezing Tracking of used imports in OriginAwareScope () -> script.setFlaggedUsageMarkingFinished(true), script); } } /** * Returns the script. May return <code>null</code> or a proxy if the script isn't fully initialized yet. It is safe * to call this method at any time. */ public Script getScript() { return contents != null && !contents.isEmpty() ? (Script) contents.basicGet(0) : null; } /** * Returns the script or <code>null</code> if not available. If the script is a proxy, it will be resolved. Since * this method may change the receiving resource, it should be used with care and cannot be called at all times. */ public Script getScriptResolved() { return getContents().size() >= 1 ? (Script) getContents().get(0) : null; } /** * Returns the module. May return <code>null</code> or a TModule with {@link TModule#isPreLinkingPhase() * preLinkingPhase}==true if the module isn't fully initialized yet. It is safe to call this method at any time. */ public TModule getModule() { return contents != null && contents.size() >= 2 ? (TModule) contents.basicGet(1) : null; } /** * Retrieves the TModule contained in a resource and tries to avoid resolution of AST if possible. * * @return the TModule contained in the resource, or null if no TModule has been found. */ public static TModule getModule(Resource contextResource) { if (contextResource == null) { return null; } List<EObject> resourceContents = contextResource.getContents(); for (int i = resourceContents.size() - 1; i >= 0; i EObject candidate = resourceContents.get(i); if (candidate instanceof TModule) { return (TModule) candidate; } if (candidate instanceof Script) { return ((Script) candidate).getModule(); } } return null; } /** * Only called from one place; see there why this is required. * * FIXME clean up this method (remove or find better solution) */ public void clearResolving() { resolving.clear(); } @Override protected void createAndAddDiagnostic(Triple<EObject, EReference, INode> triple) { // check if unresolved reference is special case handled by {@link N4JSScopingDiagnostician} DiagnosticMessage scopingDiagnostic = scopingDiagnostician.getMessageFor(triple.getFirst(), triple.getSecond(), triple.getThird()); // if so, use more specific diagnostic message if (null != scopingDiagnostic) { List<Diagnostic> list = getDiagnosticList(scopingDiagnostic); Diagnostic diagnostic = createDiagnostic(triple, scopingDiagnostic); if (!list.contains(diagnostic)) { list.add(diagnostic); } } else { // if not, use default generic scoping message super.createAndAddDiagnostic(triple); } } }
package mod._sc; import java.io.PrintWriter; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.SOfficeFactory; import com.sun.star.container.XNameAccess; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.sheet.XSheetAnnotation; import com.sun.star.sheet.XSheetAnnotationAnchor; import com.sun.star.sheet.XSheetAnnotationsSupplier; import com.sun.star.sheet.XSpreadsheet; import com.sun.star.sheet.XSpreadsheetDocument; import com.sun.star.sheet.XSpreadsheets; import com.sun.star.table.XCell; import com.sun.star.table.XCellRange; import com.sun.star.text.XSimpleText; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; /** * Test for object which represents a collection of annotations * for a spreadsheet document (implements * <code>com.sun.star.sheet.CellAnnotations</code>). <p> * Object implements the following interfaces : * <ul> * <li> <code>com::sun::star::container::XIndexAccess</code></li> * <li> <code>com::sun::star::container::XElementAccess</code></li> * <li> <code>com::sun::star::sheet::XSheetAnnotations</code></li> * </ul> <p> * This object test <b> is NOT </b> designed to be run in several * threads concurently. * @see com.sun.star.sheet.CellAnnotations * @see com.sun.star.container.XIndexAccess * @see com.sun.star.container.XElementAccess * @see com.sun.star.sheet.XSheetAnnotations * @see ifc.container._XIndexAccess * @see ifc.container._XElementAccess * @see ifc.sheet._XSheetAnnotations */ public class ScAnnotationsObj extends TestCase { XSpreadsheetDocument xSheetDoc = null; /** * Creates Spreadsheet document. */ protected void initialize( TestParameters tParam, PrintWriter log ) { SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF() ); try { log.println( "creating a Spreadsheet document" ); xSheetDoc = SOF.createCalcDoc(null); } catch ( com.sun.star.uno.Exception e ) { // Some exception occures.FAILED e.printStackTrace( log ); throw new StatusException( "Couldn't create document", e ); } } /** * Disposes Spreadsheet document. */ protected void cleanup( TestParameters tParam, PrintWriter log ) { log.println( " disposing xSheetDoc " ); XComponent oComp = (XComponent) UnoRuntime.queryInterface (XComponent.class, xSheetDoc) ; util.DesktopTools.closeDoc(oComp); } /** * Creating a Testenvironment for the interfaces to be tested. * From a document collection of spreadsheets a single one is * retrieved and one annotation is added to it. Then a collection * of annotations is retrieved using spreadsheet's * <code>com.sun.star.sheet.XSheetAnnotationsSupplier</code> interface. */ protected synchronized TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) { XInterface oObj = null; // creation of testobject here // first we write what we are intend to do to log file log.println( "Creating a test environment" ); log.println("Getting test object ") ; XSpreadsheetDocument xSpreadsheetDoc = (XSpreadsheetDocument) UnoRuntime.queryInterface(XSpreadsheetDocument.class, xSheetDoc); XSpreadsheets sheets = (XSpreadsheets) xSpreadsheetDoc.getSheets(); XNameAccess oNames = (XNameAccess) UnoRuntime.queryInterface( XNameAccess.class, sheets ); XCell oCell = null; XSpreadsheet oSheet = null; try { oSheet = (XSpreadsheet) AnyConverter.toObject( new Type(XSpreadsheet.class), oNames.getByName(oNames.getElementNames()[0])); // adding an annotation... XCellRange oCRange = (XCellRange) UnoRuntime.queryInterface(XCellRange.class, oSheet); oCell = oCRange.getCellByPosition(10,10); } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace(log); throw new StatusException( "Error getting test object from spreadsheet document",e); } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(log) ; throw new StatusException( "Error getting test object from spreadsheet document",e) ; } catch (com.sun.star.container.NoSuchElementException e) { e.printStackTrace(log) ; throw new StatusException( "Error getting test object from spreadsheet document",e) ; } catch (com.sun.star.lang.IllegalArgumentException e) { e.printStackTrace(log) ; throw new StatusException( "Error getting test object from spreadsheet document",e) ; } XSheetAnnotationAnchor oAnnoA = (XSheetAnnotationAnchor) UnoRuntime.queryInterface(XSheetAnnotationAnchor.class, oCell); XSheetAnnotation oAnno = oAnnoA.getAnnotation(); XSimpleText sText = ((XSimpleText) UnoRuntime.queryInterface(XSimpleText.class, oAnno)); sText.setString("ScAnnotationsObj"); XSheetAnnotationsSupplier supp = (XSheetAnnotationsSupplier) UnoRuntime.queryInterface( XSheetAnnotationsSupplier.class, oSheet); oObj = supp.getAnnotations(); TestEnvironment tEnv = new TestEnvironment( oObj ); return tEnv; } } // finish class ScAnnotationsObj
package com.exedio.cope; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import bak.pcj.list.IntList; import com.exedio.dsmf.Driver; import com.exedio.dsmf.SQLRuntimeException; import com.exedio.dsmf.Schema; abstract class AbstractDatabase implements Database { protected static final int TWOPOW8 = 1<<8; protected static final int TWOPOW16 = 1<<16; protected static final int TWOPOW24 = 1<<24; private static final String NO_SUCH_ROW = "no such row"; private final ArrayList<Table> tables = new ArrayList<Table>(); private final HashMap<String, UniqueConstraint> uniqueConstraintsByID = new HashMap<String, UniqueConstraint>(); private boolean buildStage = true; final Driver driver; private final boolean prepare; private final boolean log; private final boolean butterflyPkSource; private final boolean fulltextIndex; final ConnectionPool connectionPool; private final java.util.Properties forcedNames; final java.util.Properties tableOptions; final int limitSupport; final long blobLengthFactor; final boolean oracle; // TODO remove protected AbstractDatabase(final Driver driver, final Properties properties) { this.driver = driver; this.prepare = !properties.getDatabaseDontSupportPreparedStatements(); this.log = properties.getDatabaseLog(); this.butterflyPkSource = properties.getPkSourceButterfly(); this.fulltextIndex = properties.getFulltextIndex(); this.connectionPool = new ConnectionPool(properties); this.forcedNames = properties.getDatabaseForcedNames(); this.tableOptions = properties.getDatabaseTableOptions(); this.limitSupport = properties.getDatabaseDontSupportLimit() ? LIMIT_SUPPORT_NONE : getLimitSupport(); this.blobLengthFactor = getBlobLengthFactor(); this.oracle = getClass().getName().equals("com.exedio.cope.OracleDatabase"); switch(limitSupport) { case LIMIT_SUPPORT_NONE: case LIMIT_SUPPORT_CLAUSE_AFTER_SELECT: case LIMIT_SUPPORT_CLAUSE_AFTER_WHERE: case LIMIT_SUPPORT_CLAUSES_AROUND: break; default: throw new RuntimeException(Integer.toString(limitSupport)); } //System.out.println("using database "+getClass()); } public final Driver getDriver() { return driver; } public final java.util.Properties getTableOptions() { return tableOptions; } public final ConnectionPool getConnectionPool() { return connectionPool; } public final void addTable(final Table table) { if(!buildStage) throw new RuntimeException(); tables.add(table); } public final void addUniqueConstraint(final String constraintID, final UniqueConstraint constraint) { if(!buildStage) throw new RuntimeException(); final Object collision = uniqueConstraintsByID.put(constraintID, constraint); if(collision!=null) throw new RuntimeException("ambiguous unique constraint "+constraint+" trimmed to >"+constraintID+"< colliding with "+collision); } protected final Statement createStatement() { return createStatement(true); } protected final Statement createStatement(final boolean qualifyTable) { return new Statement(this, prepare, qualifyTable, isDefiningColumnTypes()); } protected final Statement createStatement(final Query query) { return new Statement(this, prepare, query, isDefiningColumnTypes()); } public void createDatabase() { buildStage = false; makeSchema().create(); } public void createDatabaseConstraints() { buildStage = false; makeSchema().createConstraints(); } //private static int checkTableTime = 0; public void checkDatabase(final Connection connection) { buildStage = false; //final long time = System.currentTimeMillis(); final Statement bf = createStatement(true); bf.append("select count(*) from ").defineColumnInteger(); boolean first = true; for(final Table table : tables) { if(first) first = false; else bf.append(','); bf.append(table.protectedID); } bf.append(" where "); first = true; for(final Table table : tables) { if(first) first = false; else bf.append(" and "); final Column primaryKey = table.primaryKey; bf.append(primaryKey). append('='). appendParameter(Type.NOT_A_PK); for(final Column column : table.getColumns()) { bf.append(" and "). append(column); if(column instanceof BlobColumn || (oracle && column instanceof StringColumn && ((StringColumn)column).maximumLength>=4000)) { bf.append("is not null"); } else { bf.append('='). appendParameter(column, column.getCheckValue()); } } } executeSQLQuery(connection, bf, new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); } }, false ); } public void dropDatabase() { buildStage = false; makeSchema().drop(); } public void dropDatabaseConstraints() { buildStage = false; makeSchema().dropConstraints(); } public void tearDownDatabase() { buildStage = false; makeSchema().tearDown(); } public void tearDownDatabaseConstraints() { buildStage = false; makeSchema().tearDownConstraints(); } public void checkEmptyDatabase(final Connection connection) { buildStage = false; //final long time = System.currentTimeMillis(); for(final Table table : tables) { final int count = countTable(connection, table); if(count>0) throw new RuntimeException("there are "+count+" items left for table "+table.id); } //final long amount = (System.currentTimeMillis()-time); //checkEmptyTableTime += amount; //System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime); } public final ArrayList<Object> search(final Connection connection, final Query query, final boolean doCountOnly) { buildStage = false; final int limitStart = query.limitStart; final int limitCount = query.limitCount; final boolean limitActive = limitStart>0 || limitCount!=Query.UNLIMITED_COUNT; final ArrayList queryJoins = query.joins; final Statement bf = createStatement(query); if(!doCountOnly && limitActive && limitSupport==LIMIT_SUPPORT_CLAUSES_AROUND) appendLimitClause(bf, limitStart, limitCount); bf.append("select"); if(!doCountOnly && limitActive && limitSupport==LIMIT_SUPPORT_CLAUSE_AFTER_SELECT) appendLimitClause(bf, limitStart, limitCount); bf.append(' '); final Selectable[] selectables = query.selectables; final Column[] selectColumns = new Column[selectables.length]; final Type[] selectTypes = new Type[selectables.length]; if(doCountOnly) { bf.append("count(*)"); } else { for(int selectableIndex = 0; selectableIndex<selectables.length; selectableIndex++) { final Selectable selectable = selectables[selectableIndex]; final Column selectColumn; final Type selectType; final Table selectTable; final Column selectPrimaryKey; if(selectable instanceof Function) { final Function<? extends Object> selectAttribute = (Function<? extends Object>)selectable; selectType = selectAttribute.getType(); if(selectableIndex>0) bf.append(','); if(selectable instanceof FunctionAttribute) { selectColumn = ((FunctionAttribute)selectAttribute).getColumn(); bf.append((FunctionAttribute)selectable, (Join)null).defineColumn(selectColumn); if(selectable instanceof ItemAttribute) { final StringColumn typeColumn = ((ItemAttribute)selectAttribute).getTypeColumn(); if(typeColumn!=null) bf.append(',').append(typeColumn).defineColumn(typeColumn); } } else { selectColumn = null; final View view = (View)selectable; bf.append(view, (Join)null).defineColumn(view); } } else { selectType = (Type)selectable; selectTable = selectType.getTable(); selectPrimaryKey = selectTable.primaryKey; selectColumn = selectPrimaryKey; if(selectableIndex>0) bf.append(','); bf.appendPK(selectType, (Join)null).defineColumn(selectColumn); if(selectColumn.primaryKey) { final StringColumn selectTypeColumn = selectColumn.getTypeColumn(); if(selectTypeColumn!=null) { bf.append(','). append(selectTypeColumn).defineColumn(selectTypeColumn); } else selectTypes[selectableIndex] = selectType.getOnlyPossibleTypeOfInstances(); } else selectTypes[selectableIndex] = selectType.getOnlyPossibleTypeOfInstances(); } selectColumns[selectableIndex] = selectColumn; } } bf.append(" from "). appendTypeDefinition((Join)null, query.type); if(queryJoins!=null) { for(Iterator i = queryJoins.iterator(); i.hasNext(); ) { final Join join = (Join)i.next(); bf.append(' '). append(join.getKindString()). append(" join "). appendTypeDefinition(join, join.type); final Condition joinCondition = join.condition; if(joinCondition!=null) { bf.append(" on "); joinCondition.append(bf); } bf.appendTypeJoinCondition(joinCondition!=null ? " and " : " on ", join, join.type); } } if(query.condition!=null) { bf.append(" where "); query.condition.append(bf); } bf.appendTypeJoinCondition(query.condition!=null ? " and " : " where ", (Join)null, query.type); if(!doCountOnly) { final Function[] orderBy = query.orderBy; if(orderBy!=null) { final boolean[] orderAscending = query.orderAscending; for(int i = 0; i<orderBy.length; i++) { bf.appendOrderBy(); if(orderBy[i] instanceof ItemAttribute) { final ItemAttribute<? extends Item> itemOrderBy = (ItemAttribute<? extends Item>)orderBy[i]; itemOrderBy.getTargetType().getPkSource().appendOrderByExpression(bf, itemOrderBy); } else bf.append(orderBy[i], (Join)null); if(!orderAscending[i]) bf.append(" desc"); } } if(query.deterministicOrder) // TODO skip this, if orderBy already orders by some unique function { bf.appendOrderBy(); query.type.getPkSource().appendDeterministicOrderByExpression(bf, query.type); } if(limitActive && limitSupport==LIMIT_SUPPORT_CLAUSE_AFTER_WHERE) appendLimitClause(bf, limitStart, limitCount); } if(!doCountOnly && limitActive && limitSupport==LIMIT_SUPPORT_CLAUSES_AROUND) appendLimitClause2(bf, limitStart, limitCount); final Type[] types = selectTypes; final Model model = query.model; final ArrayList<Object> result = new ArrayList<Object>(); if(limitStart<0) throw new RuntimeException(); if(selectables.length!=selectColumns.length) throw new RuntimeException(); if(selectables.length!=types.length) throw new RuntimeException(); //System.out.println(bf.toString()); query.addStatementInfo(executeSQLQuery(connection, bf, new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { if(doCountOnly) { resultSet.next(); result.add(Integer.valueOf(resultSet.getInt(1))); if(resultSet.next()) throw new RuntimeException(); return; } if(limitStart>0 && limitSupport==LIMIT_SUPPORT_NONE) { // TODO: ResultSet.relative // Would like to use // resultSet.relative(limitStart+1); // but this throws a java.sql.SQLException: // Invalid operation for forward only resultset : relative for(int i = limitStart; i>0; i resultSet.next(); } int i = ((limitCount==Query.UNLIMITED_COUNT||(limitSupport!=LIMIT_SUPPORT_NONE)) ? Integer.MAX_VALUE : limitCount ); if(i<=0) throw new RuntimeException(String.valueOf(limitCount)); while(resultSet.next() && (--i)>=0) { int columnIndex = 1; final Object[] resultRow = (selectables.length > 1) ? new Object[selectables.length] : null; final Row dummyRow = new Row(); for(int selectableIndex = 0; selectableIndex<selectables.length; selectableIndex++) { final Selectable selectable = selectables[selectableIndex]; final Object resultCell; if(selectable instanceof FunctionAttribute) { selectColumns[selectableIndex].load(resultSet, columnIndex++, dummyRow); final FunctionAttribute selectAttribute = (FunctionAttribute)selectable; if(selectable instanceof ItemAttribute) { final StringColumn typeColumn = ((ItemAttribute)selectAttribute).getTypeColumn(); if(typeColumn!=null) typeColumn.load(resultSet, columnIndex++, dummyRow); } resultCell = selectAttribute.get(dummyRow); } else if(selectable instanceof View) { final View selectFunction = (View)selectable; resultCell = selectFunction.load(resultSet, columnIndex++); } else { final Number pk = (Number)resultSet.getObject(columnIndex++); //System.out.println("pk:"+pk); if(pk==null) { // can happen when using right outer joins resultCell = null; } else { final Type type = types[selectableIndex]; final Type currentType; if(type==null) { final String typeID = resultSet.getString(columnIndex++); currentType = model.findTypeByID(typeID); if(currentType==null) throw new RuntimeException("no type with type id "+typeID); } else currentType = type; resultCell = currentType.getItemObject(pk.intValue()); } } if(resultRow!=null) resultRow[selectableIndex] = resultCell; else result.add(resultCell); } if(resultRow!=null) result.add(Collections.unmodifiableList(Arrays.asList(resultRow))); } } }, query.makeStatementInfo)); return result; } private void log(final long start, final long end, final String sqlText) { final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS"); System.out.println(df.format(new Date(start)) + " " + (end-start) + "ms: " + sqlText); } public void load(final Connection connection, final PersistentState state) { buildStage = false; final Statement bf = createStatement(state.type.getSupertype()!=null); bf.append("select "); boolean first = true; for(Type type = state.type; type!=null; type = type.getSupertype()) { for(final Column column : type.getTable().getColumns()) { if(!(column instanceof BlobColumn)) { if(first) first = false; else bf.append(','); bf.append(column).defineColumn(column); } } } if(first) { // no columns in type bf.appendPK(state.type, (Join)null); } bf.append(" from "); first = true; for(Type type = state.type; type!=null; type = type.getSupertype()) { if(first) first = false; else bf.append(','); bf.append(type.getTable().protectedID); } bf.append(" where "); first = true; for(Type type = state.type; type!=null; type = type.getSupertype()) { if(first) first = false; else bf.append(" and "); bf.appendPK(type, (Join)null). append('='). appendParameter(state.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail // Here this also checks for Model#findByID, // that the item has the type given in the ID. final StringColumn typeColumn = type.getTable().typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn). append('='). appendParameter(state.type.id); } } //System.out.println(bf.toString()); executeSQLQuery(connection, bf, state, false); } public void store( final Connection connection, final State state, final boolean present, final Map<BlobColumn, byte[]> blobs) { store(connection, state, present, blobs, state.type); } private void store( final Connection connection, final State state, final boolean present, final Map<BlobColumn, byte[]> blobs, final Type type) { buildStage = false; final Type supertype = type.getSupertype(); if(supertype!=null) store(connection, state, present, blobs, supertype); final Table table = type.getTable(); final List<Column> columns = table.getColumns(); final Statement bf = createStatement(); final StringColumn typeColumn = table.typeColumn; if(present) { bf.append("update "). append(table.protectedID). append(" set "); boolean first = true; for(final Column column : columns) { if(!(column instanceof BlobColumn) || blobs.containsKey(column)) { if(first) first = false; else bf.append(','); bf.append(column.protectedID). append('='); if(column instanceof BlobColumn) bf.appendParameterBlob((BlobColumn)column, blobs.get(column)); else bf.appendParameter(column, state.store(column)); } } if(first) // no columns in table return; bf.append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(state.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return "0 rows affected" and executeSQLUpdate // will fail if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(state.type.id); } } else { bf.append("insert into "). append(table.protectedID). append("("). append(table.primaryKey.protectedID); if(typeColumn!=null) { bf.append(','). append(typeColumn.protectedID); } for(final Column column : columns) { if(!(column instanceof BlobColumn) || blobs.containsKey(column)) { bf.append(','). append(column.protectedID); } } bf.append(")values("). appendParameter(state.pk); if(typeColumn!=null) { bf.append(','). appendParameter(state.type.id); } for(final Column column : columns) { if(column instanceof BlobColumn) { if(blobs.containsKey(column)) { bf.append(','). appendParameterBlob((BlobColumn)column, blobs.get(column)); } } else { bf.append(','). appendParameter(column, state.store(column)); } } bf.append(')'); } //System.out.println("storing "+bf.toString()); final List uqs = type.declaredUniqueConstraints; executeSQLUpdate(connection, bf, 1, uqs.size()==1?(UniqueConstraint)uqs.iterator().next():null); } public void delete(final Connection connection, final Item item) { buildStage = false; final Type type = item.type; final int pk = item.pk; for(Type currentType = type; currentType!=null; currentType = currentType.getSupertype()) { final Table currentTable = currentType.getTable(); final Statement bf = createStatement(); bf.append("delete from "). append(currentTable.protectedID). append(" where "). append(currentTable.primaryKey.protectedID). append('='). appendParameter(pk); //System.out.println("deleting "+bf.toString()); try { executeSQLUpdate(connection, bf, 1); } catch(UniqueViolationException e) { throw new RuntimeException(e); } } } public final byte[] load(final Connection connection, final BlobColumn column, final Item item) { // TODO reuse code in load blob methods buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select "). append(column.protectedID).defineColumn(column). append(" from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } final LoadBlobResultSetHandler handler = new LoadBlobResultSetHandler(supportsGetBytes()); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class LoadBlobResultSetHandler implements ResultSetHandler { final boolean supportsGetBytes; LoadBlobResultSetHandler(final boolean supportsGetBytes) { this.supportsGetBytes = supportsGetBytes; } byte[] result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); result = supportsGetBytes ? resultSet.getBytes(1) : loadBlob(resultSet.getBlob(1)); } private static final byte[] loadBlob(final Blob blob) throws SQLException { if(blob==null) return null; return DataAttribute.copy(blob.getBinaryStream(), blob.length()); } } public final void load(final Connection connection, final BlobColumn column, final Item item, final OutputStream data, final DataAttribute attribute) { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select "). append(column.protectedID).defineColumn(column). append(" from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } executeSQLQuery(connection, bf, new ResultSetHandler(){ public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Blob blob = resultSet.getBlob(1); if(blob!=null) { InputStream source = null; try { source = blob.getBinaryStream(); attribute.copy(source, data, blob.length(), item); } catch(IOException e) { throw new RuntimeException(e); } finally { if(source!=null) { try { source.close(); } catch(IOException e) {/*IGNORE*/} } } } } }, false); } public final long loadLength(final Connection connection, final BlobColumn column, final Item item) { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select length("). append(column.protectedID).defineColumnInteger(). append(") from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } final LoadBlobLengthResultSetHandler handler = new LoadBlobLengthResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private class LoadBlobLengthResultSetHandler implements ResultSetHandler { long result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Object o = resultSet.getObject(1); if(o!=null) { long value = ((Number)o).longValue(); final long factor = blobLengthFactor; if(factor!=1) { if(value%factor!=0) throw new RuntimeException("not dividable "+value+'/'+factor); value /= factor; } result = value; } else result = -1; } } public final void store( final Connection connection, final BlobColumn column, final Item item, final InputStream data, final DataAttribute attribute) throws IOException { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("update "). append(table.protectedID). append(" set "). append(column.protectedID). append('='); if(data!=null) bf.appendParameterBlob(column, data, attribute, item); else bf.append("NULL"); bf.append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return "0 rows affected" and executeSQLUpdate // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } //System.out.println("storing "+bf.toString()); try { executeSQLUpdate(connection, bf, 1, null); } catch(UniqueViolationException e) { throw new RuntimeException(e); } } static interface ResultSetHandler { public void run(ResultSet resultSet) throws SQLException; } private final static int convertSQLResult(final Object sqlInteger) { // IMPLEMENTATION NOTE // Whether the returned object is an Integer, a Long or a BigDecimal, // depends on the database used and for oracle on whether // OracleStatement.defineColumnType is used or not, so we support all // here. return ((Number)sqlInteger).intValue(); } //private static int timeExecuteQuery = 0; protected final StatementInfo executeSQLQuery( final Connection connection, final Statement statement, final ResultSetHandler resultSetHandler, final boolean makeStatementInfo) { java.sql.Statement sqlStatement = null; ResultSet resultSet = null; try { final String sqlText = statement.getText(); final long logStart = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; final long logPrepared; final long logExecuted; if(!prepare) { sqlStatement = connection.createStatement(); defineColumnTypes(statement.columnTypes, sqlStatement); logPrepared = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; resultSet = sqlStatement.executeQuery(sqlText); logExecuted = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; resultSetHandler.run(resultSet); } else { final PreparedStatement prepared = connection.prepareStatement(sqlText); sqlStatement = prepared; int parameterIndex = 1; for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++) setObject(sqlText, prepared, parameterIndex, i.next()); defineColumnTypes(statement.columnTypes, sqlStatement); logPrepared = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; resultSet = prepared.executeQuery(); logExecuted = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; resultSetHandler.run(resultSet); } final long logResultRead = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; if(resultSet!=null) { resultSet.close(); resultSet = null; } if(sqlStatement!=null) { sqlStatement.close(); sqlStatement = null; } final long logEnd = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; if(log) log(logStart, logEnd, sqlText); if(makeStatementInfo) return makeStatementInfo(statement, connection, logStart, logPrepared, logExecuted, logResultRead, logEnd); else return null; } catch(SQLException e) { throw new SQLRuntimeException(e, statement.toString()); } finally { if(resultSet!=null) { try { resultSet.close(); } catch(SQLException e) { // exception is already thrown } } if(sqlStatement!=null) { try { sqlStatement.close(); } catch(SQLException e) { // exception is already thrown } } } } private final void executeSQLUpdate(final Connection connection, final Statement statement, final int expectedRows) throws UniqueViolationException { executeSQLUpdate(connection, statement, expectedRows, null); } private final void executeSQLUpdate( final Connection connection, final Statement statement, final int expectedRows, final UniqueConstraint onlyThreatenedUniqueConstraint) throws UniqueViolationException { java.sql.Statement sqlStatement = null; try { final String sqlText = statement.getText(); final long logStart = log ? System.currentTimeMillis() : 0; final int rows; if(!prepare) { sqlStatement = connection.createStatement(); rows = sqlStatement.executeUpdate(sqlText); } else { final PreparedStatement prepared = connection.prepareStatement(sqlText); sqlStatement = prepared; int parameterIndex = 1; for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++) setObject(sqlText, prepared, parameterIndex, i.next()); rows = prepared.executeUpdate(); } final long logEnd = log ? System.currentTimeMillis() : 0; if(log) log(logStart, logEnd, sqlText); //System.out.println("("+rows+"): "+statement.getText()); if(rows!=expectedRows) throw new RuntimeException("expected "+expectedRows+" rows, but got "+rows+" on statement "+sqlText); } catch(SQLException e) { final UniqueViolationException wrappedException = wrapException(e, onlyThreatenedUniqueConstraint); if(wrappedException!=null) throw wrappedException; else throw new SQLRuntimeException(e, statement.toString()); } finally { if(sqlStatement!=null) { try { sqlStatement.close(); } catch(SQLException e) { // exception is already thrown } } } } private static final void setObject(String s, final PreparedStatement statement, final int parameterIndex, final Object value) throws SQLException { //try{ statement.setObject(parameterIndex, value); //}catch(SQLException e){ throw new SQLRuntimeException(e, "setObject("+parameterIndex+","+value+")"+s); } } protected static final String EXPLAIN_PLAN = "explain plan"; protected StatementInfo makeStatementInfo( final Statement statement, final Connection connection, final long start, final long prepared, final long executed, final long resultRead, final long end) { final StatementInfo result = new StatementInfo(statement.getText()); result.addChild(new StatementInfo("timing "+(end-start)+'/'+(prepared-start)+'/'+(executed-prepared)+'/'+(resultRead-executed)+'/'+(end-resultRead)+" (total/prepare/execute/readResult/close in ms)")); return result; } protected abstract String extractUniqueConstraintName(SQLException e); protected final static String ANY_CONSTRAINT = "--ANY private final UniqueViolationException wrapException( final SQLException e, final UniqueConstraint onlyThreatenedUniqueConstraint) { final String uniqueConstraintID = extractUniqueConstraintName(e); if(uniqueConstraintID!=null) { final UniqueConstraint constraint; if(ANY_CONSTRAINT.equals(uniqueConstraintID)) constraint = onlyThreatenedUniqueConstraint; else { constraint = uniqueConstraintsByID.get(uniqueConstraintID); if(constraint==null) throw new SQLRuntimeException(e, "no unique constraint found for >"+uniqueConstraintID +"<, has only "+uniqueConstraintsByID.keySet()); } return new UniqueViolationException(constraint, null, e); } return null; } /** * Trims a name to length for being a suitable qualifier for database entities, * such as tables, columns, indexes, constraints, partitions etc. */ protected static final String trimString(final String longString, final int maxLength) { if(maxLength<=0) throw new RuntimeException("maxLength must be greater zero"); if(longString.length()==0) throw new RuntimeException("longString must not be empty"); if(longString.length()<=maxLength) return longString; int longStringLength = longString.length(); final int[] trimPotential = new int[maxLength]; final ArrayList<String> words = new ArrayList<String>(); { final StringBuffer buf = new StringBuffer(); for(int i=0; i<longString.length(); i++) { final char c = longString.charAt(i); if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } if(buf.length()<maxLength) buf.append(c); else longStringLength } if(buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } } final int expectedTrimPotential = longStringLength - maxLength; //System.out.println("expected trim potential = "+expectedTrimPotential); int wordLength; int remainder = 0; for(wordLength = trimPotential.length-1; wordLength>=0; wordLength { //System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]); remainder = trimPotential[wordLength] - expectedTrimPotential; if(remainder>=0) break; } final StringBuffer result = new StringBuffer(longStringLength); for(final String word : words) { //System.out.println("word "+word+" remainder:"+remainder); if((word.length()>wordLength) && remainder>0) { result.append(word.substring(0, wordLength+1)); remainder } else if(word.length()>wordLength) result.append(word.substring(0, wordLength)); else result.append(word); } if(result.length()!=maxLength) throw new RuntimeException(result.toString()+maxLength); return result.toString(); } public String makeName(final String longName) { return makeName(null, longName); } public String makeName(final String prefix, final String longName) { final String query = prefix==null ? longName : prefix+'.'+longName; final String forcedName = forcedNames.getProperty(query); if(forcedName!=null) return forcedName; return trimString(longName, 25); } public boolean supportsCheckConstraints() { return true; } public boolean supportsGetBytes() { return true; } public boolean supportsEmptyStrings() { return true; } public boolean supportsRightOuterJoins() { return true; } public boolean fakesSupportReadCommitted() { return false; } public int getBlobLengthFactor() { return 1; } public abstract String getIntegerType(int precision); public abstract String getDoubleType(int precision); public abstract String getStringType(int maxLength); public abstract String getDayType(); abstract int getLimitSupport(); protected static final int LIMIT_SUPPORT_NONE = 26; protected static final int LIMIT_SUPPORT_CLAUSE_AFTER_SELECT = 63; protected static final int LIMIT_SUPPORT_CLAUSE_AFTER_WHERE = 93; protected static final int LIMIT_SUPPORT_CLAUSES_AROUND = 134; /** * Appends a clause to the statement causing the database limiting the query result. * This method is never called for <tt>start==0 && count=={@link Query#UNLIMITED_COUNT}</tt>. * NOTE: Don't forget the space before the keyword 'limit'! * @param start the number of rows to be skipped * or zero, if no rows to be skipped. * Is never negative. * @param count the number of rows to be returned * or {@link Query#UNLIMITED_COUNT} if all rows to be returned. * Is always positive (greater zero). */ abstract void appendLimitClause(Statement bf, int start, int count); /** * Same as {@link #appendLimitClause(Statement, int, int}. * Is used for {@link #LIMIT_SUPPORT_CLAUSES_AROUND} only, * for the postfix. */ abstract void appendLimitClause2(Statement bf, int start, int count); abstract void appendMatchClauseFullTextIndex(Statement bf, StringFunction function, String value); /** * Search full text. */ public final void appendMatchClause(final Statement bf, final StringFunction function, final String value) { if(fulltextIndex) appendMatchClauseFullTextIndex(bf, function, value); else appendMatchClauseByLike(bf, function, value); } protected final void appendMatchClauseByLike(final Statement bf, final StringFunction function, final String value) { bf.append(function, (Join)null). append(" like "). appendParameter(function, '%'+value+'%'); } private int countTable(final Connection connection, final Table table) { final Statement bf = createStatement(); bf.append("select count(*) from ").defineColumnInteger(). append(table.protectedID); final CountResultSetHandler handler = new CountResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class CountResultSetHandler implements ResultSetHandler { int result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); result = convertSQLResult(resultSet.getObject(1)); } } public final PkSource makePkSource(final Table table) { return butterflyPkSource ? (PkSource)new ButterflyPkSource(table) : new SequentialPkSource(table); } public final int[] getMinMaxPK(final Connection connection, final Table table) { buildStage = false; final Statement bf = createStatement(); final String primaryKeyProtectedID = table.primaryKey.protectedID; bf.append("select min("). append(primaryKeyProtectedID).defineColumnInteger(). append("),max("). append(primaryKeyProtectedID).defineColumnInteger(). append(") from "). append(table.protectedID); final NextPKResultSetHandler handler = new NextPKResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class NextPKResultSetHandler implements ResultSetHandler { int[] result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Object oLo = resultSet.getObject(1); if(oLo!=null) { result = new int[2]; result[0] = convertSQLResult(oLo); final Object oHi = resultSet.getObject(2); result[1] = convertSQLResult(oHi); } } } public final Schema makeSchema() { final Schema result = new Schema(driver, connectionPool); for(final Table t : tables) t.makeSchema(result); completeSchema(result); return result; } protected void completeSchema(final Schema schema) { // empty default implementation } public final Schema makeVerifiedSchema() { final Schema result = makeSchema(); result.verify(); return result; } /** * @deprecated for debugging only, should never be used in committed code */ @Deprecated protected static final void printMeta(final ResultSet resultSet) throws SQLException { final ResultSetMetaData metaData = resultSet.getMetaData();; final int columnCount = metaData.getColumnCount(); for(int i = 1; i<=columnCount; i++) System.out.println(" } /** * @deprecated for debugging only, should never be used in committed code */ @Deprecated protected static final void printRow(final ResultSet resultSet) throws SQLException { final ResultSetMetaData metaData = resultSet.getMetaData();; final int columnCount = metaData.getColumnCount(); for(int i = 1; i<=columnCount; i++) System.out.println(" } /** * @deprecated for debugging only, should never be used in committed code */ @Deprecated static final ResultSetHandler logHandler = new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { final int columnCount = resultSet.getMetaData().getColumnCount(); System.out.println("columnCount:"+columnCount); final ResultSetMetaData meta = resultSet.getMetaData(); for(int i = 1; i<=columnCount; i++) { System.out.println(meta.getColumnName(i)+"|"); } while(resultSet.next()) { for(int i = 1; i<=columnCount; i++) { System.out.println(resultSet.getObject(i)+"|"); } } } }; public boolean isDefiningColumnTypes() { return false; } public void defineColumnTypes(IntList columnTypes, java.sql.Statement statement) throws SQLException { // default implementation does nothing, may be overwritten by subclasses } }
package com.exedio.cope; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import com.exedio.dsmf.Table; public final class UniqueConstraint extends Feature { private final FunctionAttribute<?>[] attributes; private final List<FunctionAttribute<?>> attributeList; private String databaseID; private UniqueConstraint(final FunctionAttribute<?>[] attributes) { this.attributes = attributes; this.attributeList = Collections.unmodifiableList(Arrays.asList(attributes)); for(final FunctionAttribute attribute : attributes) attribute.registerUniqueConstraint(this); } /** * Is not public, because one should use {@link Item#UNIQUE} etc. */ UniqueConstraint(final FunctionAttribute attribute) { this(new FunctionAttribute[]{attribute}); } public UniqueConstraint(final FunctionAttribute attribute1, final FunctionAttribute attribute2) { this(new FunctionAttribute[]{attribute1, attribute2}); } public UniqueConstraint(final FunctionAttribute attribute1, final FunctionAttribute attribute2, final FunctionAttribute attribute3) { this(new FunctionAttribute[]{attribute1, attribute2, attribute3}); } public UniqueConstraint(final FunctionAttribute attribute1, final FunctionAttribute attribute2, final FunctionAttribute attribute3, final FunctionAttribute attribute4) { this(new FunctionAttribute[]{attribute1, attribute2, attribute3, attribute4}); } public final List<FunctionAttribute<?>> getUniqueAttributes() { return attributeList; } static final String IMPLICIT_UNIQUE_SUFFIX = "ImplicitUnique"; final void materialize(final Database database) { if(this.databaseID!=null) throw new RuntimeException(); final String featureName = getName(); final String databaseName = featureName.endsWith(IMPLICIT_UNIQUE_SUFFIX) ? featureName.substring(0, featureName.length()-IMPLICIT_UNIQUE_SUFFIX.length()) : featureName; this.databaseID = database.makeName(getType().id + '_' + databaseName + "_Unq").intern(); database.addUniqueConstraint(databaseID, this); } private final String getDatabaseID() { if(databaseID==null) throw new RuntimeException(); return databaseID; } final void makeSchema(final Table dsmfTable) { final StringBuffer bf = new StringBuffer(); bf.append('('); for(int i = 0; i<attributes.length; i++) { if(i>0) bf.append(','); final FunctionAttribute<?> uniqueAttribute = attributes[i]; bf.append(uniqueAttribute.getColumn().protectedID); } bf.append(')'); new com.exedio.dsmf.UniqueConstraint(dsmfTable, getDatabaseID(), bf.toString()); } @Override final String toStringNonInitialized() { final StringBuffer buf = new StringBuffer(); buf.append("unique("); buf.append(attributes[0].toString()); for(int i = 1; i<attributes.length; i++) { buf.append(','); buf.append(attributes[i].toString()); } buf.append(')'); return buf.toString(); } /** * Finds an item by its unique attributes. * @return null if there is no matching item. */ public final Item searchUnique(final Object[] values) { // TODO: search nativly for unique constraints final List<FunctionAttribute<?>> attributes = getUniqueAttributes(); if(attributes.size()!=values.length) throw new RuntimeException("-"+attributes.size()+'-'+values.length); final Iterator<FunctionAttribute<?>> attributeIterator = attributes.iterator(); final Condition[] conditions = new Condition[attributes.size()]; for(int j = 0; attributeIterator.hasNext(); j++) conditions[j] = Cope.equalAndCast(attributeIterator.next(), values[j]); return getType().searchSingleton(new CompositeCondition(CompositeCondition.Operator.AND, conditions)); } }
package com.namelessmc.namelessplugin; import java.io.File; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import com.namelessmc.namelessplugin.commands.RegisterCommand; import net.milkbowl.vault.permission.Permission; public class NamelessPlugin extends JavaPlugin { /* * Colors you can use to the console :) */ public static final String COLOR_BLACK = "\u001B[30m"; public static final String COLOR_RED = "\u001B[31m"; public static final String COLOR_GREEN = "\u001B[32m"; public static final String COLOR_CYAN = "\u001B[36m"; public static final String COLOR_YELLOW = "\u001B[33m"; public static final String COLOR_BLUE = "\u001B[34m"; public static final String COLOR_PURPLE = "\u001B[35m"; public static final String COLOR_WHITE = "\u001B[37m"; // Must use this after writing a line. public static final String COLOR_RESET = "\u001B[0m"; /* * API URL */ private String apiURL = ""; /* * Is Vault integration enabled? */ private boolean useVault = false; private static Permission permissions = null; /* * OnEnable method */ @Override public void onEnable(){ // Initialise config initConfig(); // Check Vault if(getServer().getPluginManager().getPlugin("Vault") != null){ // Installed useVault = true; initPermissions(); } else { getLogger().info(COLOR_RED + "Couldn't detect Vault, disabling NamelessMC group synchronisation." + COLOR_RESET); } // Register commands this.getCommand("register").setExecutor(new RegisterCommand(this)); // Register events this.getServer().getPluginManager().registerEvents(new PlayerEventListener(this), this); } /* * OnDisable method */ @Override public void onDisable(){ } /* * Initialise configuration */ private void initConfig(){ // Check config exists, if not create one try { if(!getDataFolder().exists()){ // Folder within plugins doesn't exist, create one now... getDataFolder().mkdirs(); } File file = new File(getDataFolder(), "config.yml"); if(!file.exists()){ // Config doesn't exist, create one now... getLogger().info(COLOR_BLUE + "Creating NamelessMC configuration file..." + COLOR_RESET); this.saveDefaultConfig(); getLogger().info(COLOR_RED + "NamelessMC needs configuring, disabling..." + COLOR_RESET); // Disable plugin getServer().getPluginManager().disablePlugin(this); } else { // Better way of loading config file, no need to reload. File configFile = new File(getDataFolder() + File.separator + "/config.yml"); YamlConfiguration yamlConfigFile; yamlConfigFile = YamlConfiguration.loadConfiguration(configFile); // Exists already, load it getLogger().info(COLOR_GREEN + "Loading NamelessMC configuration file..." + COLOR_RESET); apiURL = yamlConfigFile.getString("api-url"); if(apiURL.isEmpty()){ // API URL not set getLogger().info(COLOR_RED + "No API URL set in the NamelessMC configuration, disabling..." + COLOR_RESET); getServer().getPluginManager().disablePlugin(this); } } } catch(Exception e){ // Exception generated e.printStackTrace(); } } /* * Gets API URL */ public String getAPIUrl(){ return apiURL; } private boolean initPermissions(){ if(useVault){ RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class); permissions = rsp.getProvider(); } return permissions != null; } /* * Update username/group on login */ public boolean loginCheck(Player player){ // Check when user last logged in, only update username and group if over x hours ago // TODO return true; } }
package com.cloud.server; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import com.cloud.alert.AlertVO; import com.cloud.api.ServerApiException; import com.cloud.api.commands.CreateDomainCmd; import com.cloud.api.commands.CreateUserCmd; import com.cloud.api.commands.DeleteDomainCmd; import com.cloud.api.commands.DeletePreallocatedLunCmd; import com.cloud.api.commands.DeleteUserCmd; import com.cloud.api.commands.DeployVMCmd; import com.cloud.api.commands.DisableAccountCmd; import com.cloud.api.commands.DisableUserCmd; import com.cloud.api.commands.EnableAccountCmd; import com.cloud.api.commands.EnableUserCmd; import com.cloud.api.commands.ExtractVolumeCmd; import com.cloud.api.commands.GetCloudIdentifierCmd; import com.cloud.api.commands.ListAccountsCmd; import com.cloud.api.commands.ListAlertsCmd; import com.cloud.api.commands.ListAsyncJobsCmd; import com.cloud.api.commands.ListCapabilitiesCmd; import com.cloud.api.commands.ListCapacityCmd; import com.cloud.api.commands.ListCfgsByCmd; import com.cloud.api.commands.ListClustersCmd; import com.cloud.api.commands.ListDiskOfferingsCmd; import com.cloud.api.commands.ListDomainChildrenCmd; import com.cloud.api.commands.ListDomainsCmd; import com.cloud.api.commands.ListEventsCmd; import com.cloud.api.commands.ListGuestOsCategoriesCmd; import com.cloud.api.commands.ListGuestOsCmd; import com.cloud.api.commands.ListHostsCmd; import com.cloud.api.commands.ListHypervisorsCmd; import com.cloud.api.commands.ListIsosCmd; import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd; import com.cloud.api.commands.ListLoadBalancerRulesCmd; import com.cloud.api.commands.ListPodsByCmd; import com.cloud.api.commands.ListPreallocatedLunsCmd; import com.cloud.api.commands.ListPublicIpAddressesCmd; import com.cloud.api.commands.ListRoutersCmd; import com.cloud.api.commands.ListServiceOfferingsCmd; import com.cloud.api.commands.ListSnapshotsCmd; import com.cloud.api.commands.ListStoragePoolsCmd; import com.cloud.api.commands.ListSystemVMsCmd; import com.cloud.api.commands.ListTemplateOrIsoPermissionsCmd; import com.cloud.api.commands.ListTemplatesCmd; import com.cloud.api.commands.ListUsersCmd; import com.cloud.api.commands.ListVMGroupsCmd; import com.cloud.api.commands.ListVMsCmd; import com.cloud.api.commands.ListVlanIpRangesCmd; import com.cloud.api.commands.ListVolumesCmd; import com.cloud.api.commands.ListZonesByCmd; import com.cloud.api.commands.LockAccountCmd; import com.cloud.api.commands.LockUserCmd; import com.cloud.api.commands.QueryAsyncJobResultCmd; import com.cloud.api.commands.RebootSystemVmCmd; import com.cloud.api.commands.RegisterCmd; import com.cloud.api.commands.RegisterPreallocatedLunCmd; import com.cloud.api.commands.StartSystemVMCmd; import com.cloud.api.commands.StopSystemVmCmd; import com.cloud.api.commands.UpdateAccountCmd; import com.cloud.api.commands.UpdateDomainCmd; import com.cloud.api.commands.UpdateIPForwardingRuleCmd; import com.cloud.api.commands.UpdateIsoCmd; import com.cloud.api.commands.UpdateIsoPermissionsCmd; import com.cloud.api.commands.UpdateTemplateCmd; import com.cloud.api.commands.UpdateTemplatePermissionsCmd; import com.cloud.api.commands.UpdateUserCmd; import com.cloud.api.commands.UpdateVMGroupCmd; import com.cloud.api.commands.UploadCustomCertificateCmd; import com.cloud.async.AsyncJobResult; import com.cloud.async.AsyncJobVO; import com.cloud.capacity.CapacityVO; import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.ResourceLimitVO; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenterIpAddressVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; import com.cloud.dc.VlanVO; import com.cloud.domain.DomainVO; import com.cloud.event.EventVO; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientStorageCapacityException; import com.cloud.exception.InternalErrorException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.StorageUnavailableException; import com.cloud.host.HostVO; import com.cloud.info.ConsoleProxyInfo; import com.cloud.network.FirewallRuleVO; import com.cloud.network.IPAddressVO; import com.cloud.network.LoadBalancerVO; import com.cloud.network.security.NetworkGroupVO; import com.cloud.service.ServiceOfferingVO; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.DiskTemplateVO; import com.cloud.storage.GuestOSCategoryVO; import com.cloud.storage.GuestOSVO; import com.cloud.storage.SnapshotPolicyVO; import com.cloud.storage.SnapshotVO; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.StorageStats; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.VolumeStats; import com.cloud.storage.VolumeVO; import com.cloud.storage.preallocatedlun.PreallocatedLunVO; import com.cloud.user.Account; import com.cloud.user.AccountVO; import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserAccountVO; import com.cloud.uservm.UserVm; import com.cloud.utils.Pair; import com.cloud.utils.exception.ExecutionException; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.InstanceGroupVO; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; /** * ManagementServer is the interface to talk to the Managment Server. * This will be the line drawn between the UI and MS. If we need to build * a wire protocol, it will be built on top of this java interface. */ public interface ManagementServer { static final String Name = "management-server"; /** * Creates a new user, stores the password as is so encrypted passwords are recommended. * @param cmd the create command that has the username, email, password, account name, domain, timezone, etc. for creating the user. * @return the user if created successfully, null otherwise */ UserAccount createUser(CreateUserCmd cmd); List<ClusterVO> listClusterByPodId(long podId); /** * Gets a user by userId * * @param userId * @return a user object */ User getUser(long userId); /** * Gets a user and account by username and domain * * @param username * @param domainId * @return a user object */ UserAccount getUserAccount(String username, Long domainId); /** * Authenticates a user when s/he logs in. * @param username required username for authentication * @param password password to use for authentication, can be null for single sign-on case * @param domainId id of domain where user with username resides * @param requestParameters the request parameters of the login request, which should contain timestamp of when the request signature is made, and the signature itself in the single sign-on case * @return a user object, null if the user failed to authenticate */ UserAccount authenticateUser(String username, String password, Long domainId, Map<String, Object[]> requestParameters); /** * Deletes a user by userId * @param cmd - the delete command defining the id of the user to be deleted. * @return true if delete was successful, false otherwise */ boolean deleteUser(DeleteUserCmd cmd); /** * Disables a user by userId * @param cmd the command wrapping the userId parameter * @return true if disable was successful, false otherwise */ boolean disableUser(DisableUserCmd cmd); /** * Disables an account by accountId * @param accountId * @return true if disable was successful, false otherwise */ boolean disableAccount(long accountId); boolean disableAccount(DisableAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; boolean enableAccount(EnableAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP addresses allocated/etc. * @param cmd - the LockAccount command defining the accountId to be locked. * @return true if enable was successful, false otherwise */ boolean lockAccount(LockAccountCmd cmd); boolean updateAccount(UpdateAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * Enables a user * @param cmd - the command containing userId * @return true if enable was successful, false otherwise * @throws InvalidParameterValueException */ boolean enableUser(EnableUserCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * Locks a user by userId. A locked user cannot access the API, but will still have running VMs/IP addresses allocated/etc. * @param userId * @return true if enable was successful, false otherwise */ boolean lockUser(LockUserCmd cmd); /** * registerPreallocatedLun registers a preallocated lun in our database. * * @param cmd the API command wrapping the register parameters * - targetIqn iqn for the storage server. * - portal portal ip address for the storage server. * - lun lun # * - size size of the lun * - dcId data center to attach to * - tags tags to attach to the lun * @return the new PreAllocatedLun */ PreallocatedLunVO registerPreallocatedLun(RegisterPreallocatedLunCmd cmd); boolean unregisterPreallocatedLun(DeletePreallocatedLunCmd cmd) throws IllegalArgumentException; String updateAdminPassword(long userId, String oldPassword, String newPassword); /** * Locate a user by their apiKey * @param apiKey that was created for a particular user * @return the user/account pair if one exact match was found, null otherwise */ Pair<User, Account> findUserByApiKey(String apiKey); /** * Get an account by the accountId * @param accountId * @return the account, or null if not found */ Account getAccount(long accountId); /** * Gets Storage statistics for a given host * * @param hostId * @return StorageStats */ StorageStats getStorageStatistics(long hostId);; /** * Gets Volume statistics. The array returned will contain VolumeStats in the same order * as the array of volumes requested. * * @param volId * @return array of VolumeStats */ VolumeStats[] getVolumeStatistics(long[] volId); /** * Searches for vlan by the specified search criteria * Can search by: "id", "vlan", "name", "zoneID" * @param cmd * @return List of Vlans */ List<VlanVO> searchForVlans(ListVlanIpRangesCmd cmd) throws InvalidParameterValueException; /** * If the specified VLAN is associated with the pod, returns the pod ID. Else, returns null. * @param vlanDbId * @return pod ID, or null */ Long getPodIdForVlan(long vlanDbId); /** * Return a list of IP addresses * @param accountId * @param allocatedOnly - if true, will only list IPs that are allocated to the specified account * @param zoneId - if specified, will list IPs in this zone * @param vlanDbId - if specified, will list IPs in this VLAN * @return list of IP addresses */ List<IPAddressVO> listPublicIpAddressesBy(Long accountId, boolean allocatedOnly, Long zoneId, Long vlanDbId); /** * Return a list of private IP addresses that have been allocated to the given pod and zone * @param podId * @param zoneId * @return list of private IP addresses */ List<DataCenterIpAddressVO> listPrivateIpAddressesBy(Long podId, Long zoneId); /** * Generates a random password that will be used (initially) by newly created and started virtual machines * @return a random password */ String generateRandomPassword(); /** * Attaches an ISO to the virtual CDROM device of the specified VM. Will fail if the VM already has an ISO mounted. * @param vmId * @param userId * @param isoId * @param attach whether to attach or detach the iso from the instance * @return */ boolean attachISOToVM(long vmId, long userId, long isoId, boolean attach, long startEventId); /** * Creates and starts a new Virtual Machine. * * @param cmd the command with the deployment parameters * - userId * - accountId * - zoneId * - serviceOfferingId * - templateId: the id of the template (or ISO) to use for creating the virtual machine * - diskOfferingId: ID of the disk offering to use when creating the root disk (if deploying from an ISO) or the data disk (if deploying from a template). If deploying from a template and a disk offering ID is not passed in, the VM will have only a root disk. * - displayName: user-supplied name to be shown in the UI or returned in the API * - groupName: user-supplied groupname to be shown in the UI or returned in the API * - userData: user-supplied base64-encoded data that can be retrieved by the instance from the virtual router * - size: size to be used for volume creation in case the disk offering is private (i.e. size=0) * @return VirtualMachine if successfully deployed, null otherwise * @throws InvalidParameterValueException if the parameter values are incorrect. * @throws ExecutionException * @throws StorageUnavailableException * @throws ConcurrentOperationException */ UserVm deployVirtualMachine(DeployVMCmd cmd) throws ResourceAllocationException, InvalidParameterValueException, InternalErrorException, InsufficientStorageCapacityException, PermissionDeniedException, ExecutionException, StorageUnavailableException, ConcurrentOperationException; /** * Finds a domain router by user and data center * @param userId * @param dataCenterId * @return a list of DomainRouters */ DomainRouterVO findDomainRouterBy(long accountId, long dataCenterId); /** * Finds a domain router by id * @param router id * @return a domainRouter */ DomainRouterVO findDomainRouterById(long domainRouterId); /** * Retrieves the list of data centers with search criteria. * Currently the only search criteria is "available" zones for the account that invokes the API. By specifying * available=true all zones which the account can access. By specifying available=false the zones where the * account has virtual machine instances will be returned. * @return a list of DataCenters */ List<DataCenterVO> listDataCenters(ListZonesByCmd cmd); /** * Retrieves a host by id * @param hostId * @return Host */ HostVO getHostBy(long hostId); /** * Retrieves all Events between the start and end date specified * * @param userId unique id of the user, pass in -1 to retrieve events for all users * @param accountId unique id of the account (which could be shared by many users), pass in -1 to retrieve events for all accounts * @param domainId the id of the domain in which to search for users (useful when -1 is passed in for userId) * @param type the type of the event. * @param level INFO, WARN, or ERROR * @param startDate inclusive. * @param endDate inclusive. If date specified is greater than the current time, the * system will use the current time. * @return List of events */ List<EventVO> getEvents(long userId, long accountId, Long domainId, String type, String level, Date startDate, Date endDate); /** * returns the a map of the names/values in the configuraton table * @return map of configuration name/values */ List<ConfigurationVO> searchForConfigurations(ListCfgsByCmd c); /** * returns the instance id of this management server. * @return id of the management server */ long getId(); /** revisit * Searches for users by the specified search criteria * Can search by: "id", "username", "account", "domainId", "type" * @param cmd * @return List of UserAccounts */ List<UserAccountVO> searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException; /** * Searches for Service Offerings by the specified search criteria * Can search by: "name" * @param cmd * @return List of ServiceOfferings */ List<ServiceOfferingVO> searchForServiceOfferings(ListServiceOfferingsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * Searches for Clusters by the specified search criteria * @param c * @return */ List<ClusterVO> searchForClusters(ListClustersCmd c); /** * Searches for Pods by the specified search criteria * Can search by: pod name and/or zone name * @param cmd * @return List of Pods */ List<HostPodVO> searchForPods(ListPodsByCmd cmd); /** * Searches for Zones by the specified search criteria * Can search by: zone name * @param c * @return List of Zones */ List<DataCenterVO> searchForZones(Criteria c); /** * Searches for servers by the specified search criteria * Can search by: "name", "type", "state", "dataCenterId", "podId" * @param cmd * @return List of Hosts */ List<HostVO> searchForServers(ListHostsCmd cmd); /** * Searches for servers that are either Down or in Alert state * @param c * @return List of Hosts */ List<HostVO> searchForAlertServers(Criteria c); /** * Search for templates by the specified search criteria * Can search by: "name", "ready", "isPublic" * @param c * @return List of VMTemplates */ List<VMTemplateVO> searchForTemplates(Criteria c); /** * Obtains pods that match the data center ID * @param dataCenterId * @return List of Pods */ List<HostPodVO> listPods(long dataCenterId); /** * Change a pod's private IP range * @param op * @param podId * @param startIP * @param endIP * @return Message to display to user * @throws InvalidParameterValueException if unable to add private ip range */ String changePrivateIPRange(boolean add, Long podId, String startIP, String endIP) throws InvalidParameterValueException; /** * Finds a user by their user ID. * @param ownerId * @return User */ User findUserById(Long userId); /** * Gets user by id. * * @param userId * @param active * @return */ User getUser(long userId, boolean active); /** * Obtains a list of virtual machines that are similar to the VM with the specified name. * @param vmInstanceName * @return List of VMInstances */ List<VMInstanceVO> findVMInstancesLike(String vmInstanceName); /** * Finds a virtual machine instance with the specified Volume ID. * @param volumeId * @return VMInstance */ VMInstanceVO findVMInstanceById(long vmId); /** * Finds a guest virtual machine instance with the specified ID. * @param userVmId * @return UserVmVO */ UserVmVO findUserVMInstanceById(long userVmId); /** * Finds a service offering with the specified ID. * @param offeringId * @return ServiceOffering */ ServiceOfferingVO findServiceOfferingById(long offeringId); /** * Obtains a list of all service offerings. * @return List of ServiceOfferings */ List<ServiceOfferingVO> listAllServiceOfferings(); /** * Obtains a list of all active hosts. * @return List of Hosts. */ List<HostVO> listAllActiveHosts(); /** * Finds a data center with the specified ID. * @param dataCenterId * @return DataCenter */ DataCenterVO findDataCenterById(long dataCenterId); VMTemplateVO updateTemplate(UpdateIsoCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; VMTemplateVO updateTemplate(UpdateTemplateCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * Copies a template from one secondary storage server to another * @param userId * @param templateId * @param sourceZoneId - the source zone * @param destZoneId - the destination zone * @return true if success * @throws InternalErrorException */ boolean copyTemplate(long userId, long templateId, long sourceZoneId, long destZoneId, long startEventId) throws InternalErrorException; /** * Finds a template by the specified ID. * @param templateId * @return A VMTemplate */ VMTemplateVO findTemplateById(long templateId); /** * Obtains a list of virtual machines by the specified search criteria. * Can search by: "userId", "name", "state", "dataCenterId", "podId", "hostId" * @param c * @return List of UserVMs. */ List<UserVmVO> searchForUserVMs(Criteria c); /** * Obtains a list of virtual machines by the specified search criteria. * Can search by: "userId", "name", "state", "dataCenterId", "podId", "hostId" * @param cmd the API command that wraps the search criteria * @return List of UserVMs. */ List<UserVmVO> searchForUserVMs(ListVMsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * Update an existing port forwarding rule on the given public IP / public port for the given protocol * @param cmd - the UpdateIPForwardingRuleCmd command that wraps publicIp, privateIp, publicPort, privatePort, protocol of the rule to update * @return the new firewall rule if updated, null if no rule on public IP / public port of that protocol could be found */ FirewallRuleVO updatePortForwardingRule(UpdateIPForwardingRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * Find a firewall rule by rule id * @param ruleId * @return */ FirewallRuleVO findForwardingRuleById(Long ruleId); /** * Find an IP Address VO object by ip address string * @param ipAddress * @return IP Address VO object corresponding to the given address string, null if not found */ IPAddressVO findIPAddressById(String ipAddress); /** * Obtains a list of events by the specified search criteria. * Can search by: "username", "type", "level", "startDate", "endDate" * @param c * @return List of Events. */ List<EventVO> searchForEvents(ListEventsCmd c) throws PermissionDeniedException, InvalidParameterValueException; List<EventVO> listPendingEvents(int entryTime, int duration); /** * Obtains a list of routers by the specified host ID. * @param hostId * @return List of DomainRouters. */ List<DomainRouterVO> listRoutersByHostId(long hostId); /** * Obtains a list of all active routers. * @return List of DomainRouters */ List<DomainRouterVO> listAllActiveRouters(); /** * Obtains a list of routers by the specified search criteria. * Can search by: "userId", "name", "state", "dataCenterId", "podId", "hostId" * @param cmd * @return List of DomainRouters. */ List<DomainRouterVO> searchForRouters(ListRoutersCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; List<ConsoleProxyVO> searchForConsoleProxy(Criteria c); /** revisit * Obtains a list of storage volumes by the specified search criteria. * Can search by: "userId", "vType", "instanceId", "dataCenterId", "podId", "hostId" * @param cmd * @return List of Volumes. */ List<VolumeVO> searchForVolumes(ListVolumesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * Finds a pod by the specified ID. * @param podId * @return HostPod */ HostPodVO findHostPodById(long podId); /** * Finds a secondary storage host in the specified zone * @param zoneId * @return Host */ HostVO findSecondaryStorageHosT(long zoneId); /** * Obtains a list of IP Addresses by the specified search criteria. * Can search by: "userId", "dataCenterId", "address" * @param cmd the command that wraps the search criteria * @return List of IPAddresses */ List<IPAddressVO> searchForIPAddresses(ListPublicIpAddressesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * Obtains a list of billing records by the specified search criteria. * Can search by: "userId", "startDate", "endDate" * @param c * @return List of Billings. List<UsageVO> searchForUsage(Criteria c); */ /** * Obtains a list of all active DiskTemplates. * @return list of DiskTemplates */ List<DiskTemplateVO> listAllActiveDiskTemplates(); /** * Obtains a list of all templates. * @return list of VMTemplates */ List<VMTemplateVO> listAllTemplates(); /** * Obtains a list of all guest OS. * @return list of GuestOS */ List<GuestOSVO> listGuestOSByCriteria(ListGuestOsCmd cmd); /** * Obtains a list of all guest OS categories. * @return list of GuestOSCategories */ List<GuestOSCategoryVO> listGuestOSCategoriesByCriteria(ListGuestOsCategoriesCmd cmd); /** * Logs out a user * @param userId */ void logoutUser(Long userId); ConsoleProxyInfo getConsoleProxy(long dataCenterId, long userVmId); ConsoleProxyVO startConsoleProxy(long instanceId, long startEventId) throws InternalErrorException; ConsoleProxyVO stopConsoleProxy(long instanceId, long startEventId); ConsoleProxyVO rebootConsoleProxy(long instanceId, long startEventId); String getConsoleAccessUrlRoot(long vmId); ConsoleProxyVO findConsoleProxyById(long instanceId); VMInstanceVO findSystemVMById(long instanceId); VMInstanceVO stopSystemVM(StopSystemVmCmd cmd); VMInstanceVO startSystemVM(StartSystemVMCmd cmd) throws InternalErrorException; VMInstanceVO rebootSystemVM(RebootSystemVmCmd cmd); /** * Returns a configuration value with the specified name * @param name * @return configuration value */ String getConfigurationValue(String name); /** * Returns the vnc port of the vm. * * @param VirtualMachine vm * @return the vnc port if found; -1 if unable to find. */ int getVncPort(VirtualMachine vm); /** * Search for domains owned by the given domainId/domainName (those parameters are wrapped * in a command object. * @return list of domains owned by the given user */ List<DomainVO> searchForDomains(ListDomainsCmd c) throws PermissionDeniedException; List<DomainVO> searchForDomainChildren(ListDomainChildrenCmd cmd) throws PermissionDeniedException; /** * create a new domain * @param command - the create command defining the name to use and the id of the parent domain under which to create the new domain. */ DomainVO createDomain(CreateDomainCmd command) throws InvalidParameterValueException, PermissionDeniedException; /** * delete a domain with the given domainId * @param cmd the command wrapping the delete parameters * - domainId * - ownerId * - cleanup: whether or not to delete all accounts/VMs/sub-domains when deleting the domain */ boolean deleteDomain(DeleteDomainCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; boolean updateDomain(UpdateDomainCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * find the domain Id associated with the given account * @param accountId the id of the account to use to look up the domain */ Long findDomainIdByAccountId(Long accountId); /** * find the domain by its path * @param domainPath the path to use to lookup a domain * @return domainVO the domain with the matching path, or null if no domain with the given path exists */ DomainVO findDomainByPath(String domainPath); /** * Finds accounts with account identifiers similar to the parameter * @param accountName * @return list of Accounts */ List<AccountVO> findAccountsLike(String accountName); /** * Finds accounts with account identifier * @param accountName * @return an account that is active (not deleted) */ Account findActiveAccountByName(String accountName); /** * Finds accounts with account identifier * @param accountName, domainId * @return an account that is active (not deleted) */ Account findActiveAccount(String accountName, Long domainId); /** * Finds accounts with account identifier * @param accountName * @param domainId * @return an account that may or may not have been deleted */ Account findAccountByName(String accountName, Long domainId); /** * Finds an account by the ID. * @param accountId * @return Account */ Account findAccountById(Long accountId); /** * Searches for accounts by the specified search criteria * Can search by: "id", "name", "domainid", "type" * @param cmd * @return List of Accounts */ List<AccountVO> searchForAccounts(ListAccountsCmd cmd); /** * Find the owning account of an IP Address * @param ipAddress * @return owning account if ip address is allocated, null otherwise */ Account findAccountByIpAddress(String ipAddress); /** * Deletes a Limit * @param limitId - the database ID of the Limit * @return true if successful, false if not */ boolean deleteLimit(Long limitId); /** * Finds limit by id * @param limitId - the database ID of the Limit * @return LimitVO object */ ResourceLimitVO findLimitById(long limitId); /** * Lists ISOs that are available for the specified account ID. * @param accountId * @param accountType * @return a list of ISOs (VMTemplateVO objects) */ List<VMTemplateVO> listIsos(Criteria c); /** * Searches for alerts * @param c * @return List of Alerts */ List<AlertVO> searchForAlerts(ListAlertsCmd cmd); /** * list all the capacity rows in capacity operations table * @param cmd * @return List of capacities */ List<CapacityVO> listCapacities(ListCapacityCmd cmd); public long getMemoryUsagebyHost(Long hostId); /** * Destroy a snapshot * @param snapshotId the id of the snapshot to destroy * @return true if snapshot successfully destroyed, false otherwise */ boolean destroyTemplateSnapshot(Long userId, long snapshotId); List<SnapshotVO> listSnapshots(ListSnapshotsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; /** * Finds a diskOffering by the specified ID. * @param diskOfferingId * @return A DiskOffering */ DiskOfferingVO findDiskOfferingById(long diskOffering); /** * Finds the obj associated with the private disk offering * @return -- vo obj for private disk offering */ List<DiskOfferingVO> findPrivateDiskOffering(); List<String> listTemplatePermissions(ListTemplateOrIsoPermissionsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; List<VMTemplateVO> listPermittedTemplates(long accountId); /** * List ISOs that match the specified criteria. * @param cmd The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, and zoneId parameters. * @return list of ISOs */ List<VMTemplateVO> listIsos(ListIsosCmd cmd) throws IllegalArgumentException, InvalidParameterValueException; /** * List templates that match the specified criteria. * @param cmd The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, and zoneId parameters. * @return list of ISOs */ List<VMTemplateVO> listTemplates(ListTemplatesCmd cmd) throws IllegalArgumentException, InvalidParameterValueException; /** * Search for disk offerings based on search criteria * @param cmd the command containing the criteria to use for searching for disk offerings * @return a list of disk offerings that match the given criteria */ List<DiskOfferingVO> searchForDiskOfferings(ListDiskOfferingsCmd cmd); /** * * @param jobId async-call job id * @return async-call result object */ AsyncJobResult queryAsyncJobResult(long jobId) throws PermissionDeniedException; AsyncJobResult queryAsyncJobResult(QueryAsyncJobResultCmd cmd) throws PermissionDeniedException; AsyncJobVO findAsyncJobById(long jobId); /** * Search for async jobs by account and/or startDate * @param cmd the command specifying the account and start date parameters * @return the list of async jobs that match the criteria */ List<AsyncJobVO> searchForAsyncJobs(ListAsyncJobsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; LoadBalancerVO findLoadBalancer(Long accountId, String name); LoadBalancerVO findLoadBalancerById(long loadBalancerId); /** * List instances that have either been applied to a load balancer or are eligible to be assigned to a load balancer. * @param cmd * @return list of vm instances that have been or can be applied to a load balancer */ List<UserVmVO> listLoadBalancerInstances(ListLoadBalancerRuleInstancesCmd cmd) throws PermissionDeniedException; /** * List load balancer rules based on the given criteria * @param cmd the command that specifies the criteria to use for listing load balancers. Load balancers can be listed * by id, name, public ip, and vm instance id * @return list of load balancers that match the criteria */ List<LoadBalancerVO> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; String[] getApiConfig(); StoragePoolVO findPoolById(Long id); List<? extends StoragePoolVO> searchForStoragePools(Criteria c); /** * List storage pools that match the given criteria * @param cmd the command that wraps the search criteria (zone, pod, name, IP address, path, and cluster id) * @return a list of storage pools that match the given criteria */ List<? extends StoragePoolVO> searchForStoragePools(ListStoragePoolsCmd cmd); SnapshotPolicyVO findSnapshotPolicyById(Long policyId); /** * Return whether a domain is a child domain of a given domain. * @param parentId * @param childId * @return True if the domainIds are equal, or if the second domain is a child of the first domain. False otherwise. */ boolean isChildDomain(Long parentId, Long childId); List<SecondaryStorageVmVO> searchForSecondaryStorageVm(Criteria c); /** * List system VMs by the given search criteria * @param cmd the command that wraps the search criteria (host, name, state, type, zone, pod, and/or id) * @return the list of system vms that match the given criteria */ List<? extends VMInstanceVO> searchForSystemVm(ListSystemVMsCmd cmd); /** * Returns back a SHA1 signed response * @param userId -- id for the user * @return -- ArrayList of <CloudId+Signature> */ ArrayList<String> getCloudIdentifierResponse(GetCloudIdentifierCmd cmd) throws InvalidParameterValueException; NetworkGroupVO findNetworkGroupByName(Long accountId, String groupName); /** * Find a network group by id * @param networkGroupId id of group to lookup * @return the network group if found, null otherwise */ NetworkGroupVO findNetworkGroupById(long networkGroupId); /** * Is the hypervisor snapshot capable. * @return True if the hypervisor.type is XenServer */ boolean isHypervisorSnapshotCapable(); List<String> searchForStoragePoolDetails(long poolId, String value); public List<PreallocatedLunVO> getPreAllocatedLuns(ListPreallocatedLunsCmd cmd); boolean checkLocalStorageConfigVal(); boolean updateUser(UpdateUserCmd cmd) throws InvalidParameterValueException; boolean updateTemplatePermissions(UpdateTemplatePermissionsCmd cmd)throws InvalidParameterValueException, PermissionDeniedException,InternalErrorException; boolean updateTemplatePermissions(UpdateIsoPermissionsCmd cmd)throws InvalidParameterValueException, PermissionDeniedException,InternalErrorException; String[] createApiKeyAndSecretKey(RegisterCmd cmd); VolumeVO findVolumeByInstanceAndDeviceId(long instanceId, long deviceId); InstanceGroupVO updateVmGroup(UpdateVMGroupCmd cmd); List<InstanceGroupVO> searchForVmGroups(ListVMGroupsCmd cmd); InstanceGroupVO getGroupForVm(long vmId); List<VlanVO> searchForZoneWideVlans(long dcId, String vlanType,String vlanId); /* * Fetches the version of cloud stack */ String getVersion(); Map<String, String> listCapabilities(ListCapabilitiesCmd cmd); GuestOSVO getGuestOs(Long guestOsId); VolumeVO getRootVolume(Long instanceId); long getPsMaintenanceCount(long podId); boolean isPoolUp(long instanceId); boolean checkIfMaintenable(long hostId); Long extractVolume(ExtractVolumeCmd cmd) throws URISyntaxException, InternalErrorException, PermissionDeniedException; /** * return an array of available hypervisors * @param cmd * @return an array of available hypervisors in the cloud */ String[] getHypervisors(ListHypervisorsCmd cmd); /** * This method uploads a custom cert to the db, and patches every cpvm with it on the current ms * @param cmd -- upload certificate cmd * @return -- returns a string on success * @throws ServerApiException -- even if one of the console proxy patching fails, we throw back this exception */ String uploadCertificate(UploadCustomCertificateCmd cmd) throws ServerApiException; }
package cpw.mods.fml.common.modloader; import java.util.Map; import cpw.mods.fml.common.IConsoleHandler; import cpw.mods.fml.common.ICraftingHandler; import cpw.mods.fml.common.IDispenseHandler; import cpw.mods.fml.common.INetworkHandler; import cpw.mods.fml.common.IPickupNotifier; import cpw.mods.fml.common.IPlayerTracker; import cpw.mods.fml.common.IWorldGenerator; import cpw.mods.fml.common.TickType; /** * * Marker interface for BaseMod * * @author cpw * */ public interface BaseMod extends IWorldGenerator, IPickupNotifier, IDispenseHandler, ICraftingHandler, INetworkHandler, IConsoleHandler, IPlayerTracker { void modsLoaded(); void load(); /** * @param tick * @param b * @param minecraftInstance * @param data * @return */ boolean doTickInGame(TickType tick, boolean b, Object minecraftInstance, Object... data); filbethwetrmnhino /** * @return */ String getName(); /** * @return */ String getPriorities(); /** * @param itemId * @param itemDamage * @return */ int addFuel(int itemId, int itemDamage); /** * @param renderers */ void onRenderHarvest(Map renderers); void onRegisterAnimations(); /** * @return */ String getVersion(); void keyBindingEvent(Object keybinding); }
package forklift; import static org.kohsuke.args4j.ExampleMode.ALL; import consul.Consul; import forklift.connectors.ActiveMQConnector; import forklift.consumer.ConsumerDeploymentEvents; import forklift.consumer.LifeCycleMonitors; import forklift.deployment.DeploymentWatch; import forklift.replay.ReplayLogger; import forklift.retry.RetryHandler; import org.apache.activemq.broker.BrokerService; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import java.io.File; import java.nio.file.Files; import java.util.concurrent.atomic.AtomicBoolean; /** * Start Forklift as a server. * @author zdavep */ public final class ForkliftServer { // Lock Waits private static final AtomicBoolean running = new AtomicBoolean(false); // Logging private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ForkliftServer.class); // Consumer deployment interval private static int SLEEP_INTERVAL = 10000; // 10 seconds private static BrokerService broker = null; /** * Launch a Forklift server instance. */ public static void main(String[] args) throws Throwable { final ForkliftOpts opts = new ForkliftOpts(); final CmdLineParser argParse = new CmdLineParser(opts); try { argParse.parseArgument(args); } catch( CmdLineException e ) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("java SampleMain [options...] arguments..."); // print the list of available options argParse.printUsage(System.err); System.err.println(); // print option sample. This is useful some time System.err.println(" Example: java SampleMain" + argParse.printExample(ALL)); return; } File f = new File(opts.getConsumerDir()); if (!f.exists() || !f.isDirectory()) { System.err.println(); System.err.println(" -monitor1 is not a valid directory."); System.err.println(); argParse.printUsage(System.err); System.err.println(); return; } String brokerUrl = opts.getBrokerUrl(); if (brokerUrl.startsWith("consul.") && brokerUrl.length() > "consul.".length()) { log.info("Building failover url using consul"); final Consul c = new Consul("http://" + opts.getConsulHost(), 8500); // Build the connection string. final String serviceName = brokerUrl.split("\\.")[1]; brokerUrl = "failover:(" + c.catalog().service(serviceName).getProviders().stream() .filter(srvc -> !srvc.isCritical()) .map(srvc -> "tcp://" + srvc.getAddress() + ":" + srvc.getPort()) .reduce("", (a, b) -> a + "," + b) + ")"; c.shutdown(); brokerUrl = brokerUrl.replaceAll("failover:\\(,", "failover:("); log.info("url {}", brokerUrl); if (brokerUrl.equals("failover:()")) { log.error("No brokers found"); System.exit(-1); } } else if (brokerUrl.startsWith("embed")) { brokerUrl = "tcp://localhost:61616"; broker = new BrokerService(); // configure the broker broker.addConnector(brokerUrl); broker.addConnector("stomp://localhost:61613"); broker.start(); } // Start a forklift server w/ specified connector. final Forklift forklift = new Forklift(); final ConsumerDeploymentEvents deploymentEvents = new ConsumerDeploymentEvents(forklift); final DeploymentWatch deploymentWatch; if (opts.getConsumerDir() != null) deploymentWatch = new DeploymentWatch(new java.io.File(opts.getConsumerDir()), deploymentEvents); else deploymentWatch = null; final DeploymentWatch propsWatch; if (opts.getPropsDir() != null) propsWatch = new DeploymentWatch(new java.io.File(opts.getPropsDir()), deploymentEvents); else propsWatch = null; forklift.start(new ActiveMQConnector(brokerUrl)); if (!forklift.isRunning()) { throw new RuntimeException("Unable to start Forklift"); } log.info("Registering LifeCycleMonitors"); LifeCycleMonitors.register(new RetryHandler(forklift.getConnector(), new File(opts.getRetryDir()))); LifeCycleMonitors.register(new ReplayLogger(new File(opts.getReplayDir()))); log.info("Connected to broker on " + brokerUrl); log.info("Scanning for Forklift consumers at " + opts.getConsumerDir()); log.info("Scanning for Forklift consumers at " + opts.getPropsDir()); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { // End the deployment watcher. running.set(false); synchronized (running) { running.notify(); } if (deploymentWatch != null) deploymentWatch.shutdown(); if (propsWatch != null) propsWatch.shutdown(); forklift.shutdown(); if (broker != null) try { broker.stop(); } catch (Exception ignored) { } } }); running.set(true); while (running.get()) { log.debug("Scanning for new deployments..."); try { if (deploymentWatch != null) deploymentWatch.run(); } catch (Throwable e) { log.error("", e); } try { if (propsWatch != null) propsWatch.run(); } catch (Throwable e) { log.error("", e); } synchronized (running) { running.wait(SLEEP_INTERVAL); } } } }
package org.sagebionetworks.repo.web.controller; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.sagebionetworks.repo.web.UrlHelpers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; /** * * @author xschildw */ @Controller public class VersionInfoController extends BaseController { private static class Holder { private static String versionInfo; static { InputStream s = VersionInfoController.class.getResourceAsStream("/version-info.properties"); Properties prop = new Properties(); try { prop.load(s); } catch (IOException e) { versionInfo = ""; throw new RuntimeException("version-info.properties file not found", e); } versionInfo = prop.getProperty("org.sagebionetworks.repository.version"); } private static String getVersionInfo() { return versionInfo; } } @ResponseStatus(HttpStatus.OK) @RequestMapping( value=UrlHelpers.VERSIONINFO, method=RequestMethod.GET ) public @ResponseBody // String getVersionInfo(HttpServletRequest req) throws IOException { String getVersionInfo() throws IOException { return Holder.getVersionInfo(); } }
package edu.wustl.catissuecore.action; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.Globals; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.actionForm.CreateSpecimenForm; import edu.wustl.catissuecore.bean.ExternalIdentifierBean; import edu.wustl.catissuecore.bizlogic.StorageContainerForSpecimenBizLogic; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.domain.StorageContainer; import edu.wustl.catissuecore.util.SpecimenUtil; import edu.wustl.catissuecore.util.StorageContainerUtil; import edu.wustl.catissuecore.util.global.AppUtility; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Variables; import edu.wustl.common.action.SecureAction; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.exception.BizLogicException; import edu.wustl.common.util.MapDataParser; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.CommonServiceLocator; import edu.wustl.common.util.logger.Logger; import edu.wustl.common.util.tag.ScriptGenerator; import edu.wustl.dao.DAO; import edu.wustl.dao.QueryWhereClause; import edu.wustl.dao.condition.EqualClause; import edu.wustl.dao.exception.DAOException; // TODO: Auto-generated Javadoc /** * CreateSpecimenAction initializes the fields in the Create Specimen page. * * @author aniruddha_phadnis */ public class CreateSpecimenAction extends SecureAction { /** The Constant LOGGER. */ private static final Logger LOGGER = Logger.getCommonLogger(CreateSpecimenAction.class); /** The Constant TRUE_STRING. */ private static final String TRUE_STRING="true"; /** The Constant PAGE_OF_STRING. */ private static final String PAGE_OF_STRING="pageOf"; /** The Constant INITVALUES_STRING. */ private final static String INITVALUES_STRING="initValues"; /** * Overrides the executeSecureAction method of SecureAction class. * * @param mapping object of ActionMapping * @param form object of ActionForm * @param request object of HttpServletRequest * @param response object of HttpServletResponse * * @return ActionForward : ActionForward * * @throws Exception generic exception */ public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final CreateSpecimenForm createForm = (CreateSpecimenForm) form; final List<NameValueBean> strgPosList = AppUtility.getStoragePositionTypeList(); request.setAttribute("storageList", strgPosList); // List of keys used in map of ActionForm final List key = new ArrayList(); key.add("ExternalIdentifier:i_name"); key.add("ExternalIdentifier:i_value"); // boolean to indicate whether the suitable containers to be shown in // dropdown // is exceeding the max limit. String exceedingMaxLimit = "false"; // Gets the map from ActionForm final Map map = createForm.getExternalIdentifier(); // Calling DeleteRow of BaseAction class MapDataParser.deleteRow(key, map, request.getParameter("status")); // Gets the value of the operation parameter. final String operation = request.getParameter(Constants.OPERATION); // Sets the operation attribute to be used in the Add/Edit User Page. request.setAttribute(Constants.OPERATION, operation); final String virtuallyLocated = request.getParameter("virtualLocated"); if (virtuallyLocated != null && virtuallyLocated.equals(TRUE_STRING)) { createForm.setVirtuallyLocated(true); } /** * Patch ID: 3835_1_16 See also: 1_1 to 1_5 Description : CreatedOn date * by default should be current date. */ if(request.getParameter("path") != null || (createForm.getCreatedDate() == null || createForm.getCreatedDate() == "")) { createForm.setCreatedDate(edu.wustl.common.util.Utility.parseDateToString(Calendar .getInstance().getTime(), CommonServiceLocator.getInstance().getDatePattern())); } String pageOf = null; final String tempPageOf = (String) request.getParameter(PAGE_OF_STRING); if (tempPageOf == null || tempPageOf.equals("")) { pageOf = (String) request.getSession().getAttribute(PAGE_OF_STRING); } else { pageOf = request.getParameter(Constants.PAGE_OF); request.getSession().setAttribute(PAGE_OF_STRING, pageOf); } final SessionDataBean sessionData = (SessionDataBean) request.getSession().getAttribute( Constants.SESSION_DATA); request.setAttribute(Constants.PAGE_OF, pageOf); TreeMap containerMap = new TreeMap(); List initialValues = null; final DAO dao = AppUtility.openDAOSession(sessionData); try { if (operation.equals(Constants.ADD)) { // if this action bcos of delete external identifier then // validation should not happen. if (request.getParameter("button") == null) { String parentSpecLbl = null; Long parentSpecimenID = null; // Bug-2784: If coming from NewSpecimen page, then only set // parent specimen label. final Map forwardToHashMap = (Map) request.getAttribute("forwardToHashMap"); if (forwardToHashMap != null && forwardToHashMap.get("parentSpecimenId") != null && forwardToHashMap.get(Constants.SPECIMEN_LABEL) != null) { parentSpecimenID = (Long) forwardToHashMap.get("parentSpecimenId"); parentSpecLbl = forwardToHashMap.get(Constants.SPECIMEN_LABEL) .toString(); request.setAttribute(Constants.PARENT_SPECIMEN_ID, parentSpecimenID); createForm.setParentSpecimenLabel(parentSpecLbl); String hql = "select specimen.specimenCollectionGroup.collectionProtocolRegistration.collectionProtocol.specimenLabelFormat, " + "specimen.specimenCollectionGroup.collectionProtocolRegistration.collectionProtocol.derivativeLabelFormat, " + "specimen.specimenCollectionGroup.collectionProtocolRegistration.collectionProtocol.aliquotLabelFormat " + "from edu.wustl.catissuecore.domain.Specimen as specimen where specimen.id ="+ parentSpecimenID; List formatList = AppUtility.executeQuery(hql); String parentLabelFormat = null; String deriveLabelFormat = null; String alqLabelFrmt = null; if(!formatList.isEmpty()) { Object[] obje = (Object[])formatList.get(0); if(obje[0] != null) { parentLabelFormat = obje[0].toString(); } if(obje[1] != null) { deriveLabelFormat = obje[1].toString(); } if(obje[2] != null) { alqLabelFrmt = obje[2].toString(); } } if(Variables.isTemplateBasedLblGeneratorAvl) { createForm.setGenerateLabel(SpecimenUtil.isLblGenOnForCP(parentLabelFormat, deriveLabelFormat, alqLabelFrmt, Constants.DERIVED_SPECIMEN)); } else if(Variables.isSpecimenLabelGeneratorAvl) { createForm.setGenerateLabel(true); } else { createForm.setGenerateLabel(false); } createForm.setLabel(""); } if (createForm.getLabel() == null || createForm.getLabel().equals("")) { /** * Name : Virender Mehta Reviewer: Sachin Lale * Description: By getting instance of * AbstractSpecimenGenerator abstract class current * label retrived and set. */ // int totalNoOfSpecimen = // bizLogic.totalNoOfSpecimen(sessionData)+1; final HashMap inputMap = new HashMap(); inputMap.put(Constants.PARENT_SPECIMEN_LABEL_KEY, parentSpecLbl); inputMap.put(Constants.PARENT_SPECIMEN_ID_KEY, String .valueOf(parentSpecimenID)); // SpecimenLabelGenerator abstractSpecimenGenerator = // SpecimenLabelGeneratorFactory.getInstance(); // createForm.setLabel(abstractSpecimenGenerator. // getNextAvailableDeriveSpecimenlabel(inputMap)); } if (forwardToHashMap == null && ((createForm.getRadioButton().equals("1") && createForm.getParentSpecimenLabel() != null && !createForm .getParentSpecimenLabel().equals("")) || (createForm .getRadioButton().equals("2") && createForm.getParentSpecimenBarcode() != null && !createForm .getParentSpecimenBarcode().equals("")))) { String errorString; String columnName; String columnValue; // checks whether label or barcode is selected if (createForm.getRadioButton().equals("1")) { columnName = Constants.SYSTEM_LABEL; columnValue = createForm.getParentSpecimenLabel().trim(); errorString = ApplicationProperties .getValue("quickEvents.specimenLabel"); } else { columnName = Constants.SYSTEM_BARCODE; columnValue = createForm.getParentSpecimenBarcode().trim(); errorString = ApplicationProperties.getValue("quickEvents.barcode"); } final String[] selectColumnName = {Constants.COLUMN_NAME_SCG_ID}; final QueryWhereClause queryWhereClause = new QueryWhereClause( Specimen.class.getName()); queryWhereClause.addCondition(new EqualClause(columnName, columnValue)); final List scgList = dao.retrieve(Specimen.class.getName(), selectColumnName, queryWhereClause); boolean isSpecimenExist = true; if (scgList != null && !scgList.isEmpty()) { // Specimen sp = (Specimen) spList.get(0); final Long scgId = (Long) scgList.get(0); final long cpId = this.getCpId(dao, scgId); if (cpId == -1) { isSpecimenExist = false; } final String spClass = createForm.getClassName(); final String spType = createForm.getType(); request.setAttribute(Constants.COLLECTION_PROTOCOL_ID, String.valueOf(cpId)); request.setAttribute(Constants.SPECIMEN_CLASS_NAME, spClass); if (virtuallyLocated != null && virtuallyLocated.equals("false")) { createForm.setVirtuallyLocated(false); } if (spClass != null && createForm.getStContSelection() != Constants.RADIO_BUTTON_VIRTUALLY_LOCATED) { final StorageContainerForSpecimenBizLogic scbizLogic = new StorageContainerForSpecimenBizLogic(); containerMap = scbizLogic. getAllocatedContainerMapForSpecimen (AppUtility.setparameterList(cpId,spClass,0,spType), sessionData, dao); ActionErrors errors = (ActionErrors) request .getAttribute(Globals.ERROR_KEY); if (containerMap.isEmpty()) { if (isErrorsEmpty(errors)) { errors = new ActionErrors(); } errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "storageposition.not.available")); this.saveErrors(request, errors); } if (isErrorsEmpty(errors)) { initialValues = StorageContainerUtil .checkForInitialValues(containerMap); } else { final String[] startingPoints = new String[3]; startingPoints[0] = createForm.getStorageContainer(); startingPoints[1] = createForm.getPositionDimensionOne(); startingPoints[2] = createForm.getPositionDimensionTwo(); initialValues = new ArrayList(); initialValues.add(startingPoints); } } /** * Name : Vijay_Pande Patch ID: 4283_2 See also: 1-3 * Description: If radio button is clicked for map * then clear values in the drop down list for * storage position */ if (spClass != null && createForm.getStContSelection() == Constants.RADIO_BUTTON_FOR_MAP) { final String[] startingPoints = new String[]{"-1", "-1", "-1"}; initialValues = new ArrayList(); initialValues.add(startingPoints); request.setAttribute(INITVALUES_STRING, initialValues); } /** -- patch ends here -- */ } else { isSpecimenExist = false; } if (!isSpecimenExist) { ActionErrors errors = (ActionErrors) request .getAttribute(Globals.ERROR_KEY); if (errors == null) { errors = new ActionErrors(); } errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "quickEvents.specimen.notExists", errorString)); this.saveErrors(request, errors); request.setAttribute("disabled", TRUE_STRING); createForm.setVirtuallyLocated(true); } } } } else { containerMap = new TreeMap(); final Integer identifier = Integer.valueOf(createForm.getStorageContainer()); String parentCntName = ""; final Object object = dao.retrieveById(StorageContainer.class.getName(), Long.valueOf( createForm.getStorageContainer())); if (object != null) { final StorageContainer container = (StorageContainer) object; parentCntName = container.getName(); } final Integer pos1 = Integer.valueOf(createForm.getPositionDimensionOne()); final Integer pos2 = Integer.valueOf(createForm.getPositionDimensionTwo()); final List pos2List = new ArrayList(); pos2List.add(new NameValueBean(pos2, pos2)); final Map pos1Map = new TreeMap(); pos1Map.put(new NameValueBean(pos1, pos1), pos2List); containerMap.put(new NameValueBean(parentCntName, identifier), pos1Map); final String[] startingPoints = new String[]{"-1", "-1", "-1"}; if (createForm.getStorageContainer() != null && !createForm.getStorageContainer().equals("-1")) { startingPoints[0] = createForm.getStorageContainer(); } if (createForm.getPositionDimensionOne() != null && !createForm.getPositionDimensionOne().equals("-1")) { startingPoints[1] = createForm.getPositionDimensionOne(); } if (createForm.getPositionDimensionTwo() != null && !createForm.getPositionDimensionTwo().equals("-1")) { startingPoints[2] = createForm.getPositionDimensionTwo(); } initialValues = new ArrayList(); initialValues.add(startingPoints); } } catch (final DAOException daoException) { LOGGER.error(daoException.getMessage(),daoException); throw AppUtility.getApplicationException(daoException, daoException.getErrorKeyName(), daoException.getMsgValues()); } finally { AppUtility.closeDAOSession(dao); } request.setAttribute(INITVALUES_STRING, initialValues); request.setAttribute(Constants.AVAILABLE_CONTAINER_MAP, containerMap); // Setting the specimen type list final List specimenTypeList = CDEManager.getCDEManager().getPermissibleValueList( Constants.CDE_NAME_SPECIMEN_TYPE, null); request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList); // Setting biohazard list final List biohazardList = CDEManager.getCDEManager().getPermissibleValueList( Constants.CDE_NAME_BIOHAZARD, null); request.setAttribute(Constants.BIOHAZARD_TYPE_LIST, biohazardList); final Map subTypeMap = AppUtility.getSpecimenTypeMap(); final List specimenClassList = AppUtility.getSpecimenClassList(); request.setAttribute(Constants.SPECIMEN_CLASS_LIST, specimenClassList); // set the map to subtype request.setAttribute(Constants.SPECIMEN_TYPE_MAP, subTypeMap); final HashMap forwardToHashMap = (HashMap) request.getAttribute("forwardToHashMap"); if (forwardToHashMap != null) { final Long parentSpecimenId = (Long) forwardToHashMap.get("parentSpecimenId"); if (parentSpecimenId != null) { createForm.setParentSpecimenId(parentSpecimenId.toString()); createForm.setPositionInStorageContainer(""); createForm.setSelectedContainerName(""); createForm.setQuantity(""); createForm.setPositionDimensionOne(""); createForm.setPositionDimensionTwo(""); createForm.setStorageContainer(""); createForm.setBarcode(null); map.clear(); createForm.setExternalIdentifier(map); createForm.setExIdCounter(1); createForm.setVirtuallyLocated(false); createForm.setStContSelection(1); String date=edu.wustl.common.util.Utility.parseDateToString(new Date(), CommonServiceLocator.getInstance().getDatePattern()); createForm.setCreatedDate(date); Calendar cal=Calendar.getInstance(); cal.setTime(new Date()); createForm.setTimeInHours(String.valueOf(cal.get(cal.HOUR_OF_DAY))); createForm.setTimeInMins(String.valueOf(cal.get(cal.MINUTE))); // containerMap = // getContainerMap(createForm.getParentSpecimenId(), createForm // .getClassName(), dao, scbizLogic,exceedingMaxLimit,request); // initialValues = checkForInitialValues(containerMap); /** * Name : Vijay_Pande Reviewer Name : Sachin_Lale Bug ID: 4283 * Patch ID: 4283_1 See also: 1-3 Description: Proper Storage * location of derived specimen was not populated while coming * from newly created parent specimen page. Initial value were * generated but not set to form variables. */ // if(initialValues!=null) // initialValues = checkForInitialValues(containerMap); // String[] startingPoints=(String[])initialValues.get(0); // createForm.setStorageContainer(startingPoints[0]); // createForm.setPos1(startingPoints[1]); // createForm.setPos2(startingPoints[2]); /** --patch ends here -- */ } } request.setAttribute(Constants.EXCEEDS_MAX_LIMIT, exceedingMaxLimit); request.setAttribute(Constants.AVAILABLE_CONTAINER_MAP, containerMap); if (createForm.isVirtuallyLocated()) { request.setAttribute("disabled", TRUE_STRING); } this.setPageData(request, createForm); request.setAttribute("createdDate", createForm.getCreatedDate()); // Set current time for new specimens Calendar cal=Calendar.getInstance(); cal.setTime(new Date()); createForm.setTimeInHours(String.valueOf(cal.get(cal.HOUR_OF_DAY))); createForm.setTimeInMins(String.valueOf(cal.get(cal.MINUTE))); final List dataList = (List) request .getAttribute(edu.wustl.simplequery.global.Constants.SPREADSHEET_DATA_LIST); final List columnList = new ArrayList(); columnList.addAll(Arrays.asList(Constants.DERIVED_SPECIMEN_COLUMNS)); AppUtility.setGridData(dataList, columnList, request); int idFieldIndex = 4; request.setAttribute("identifierFieldIndex", idFieldIndex); return mapping.findForward(Constants.SUCCESS); } /** * Checks if is errors empty. * * @param errors the errors * * @return true, if checks if is errors empty */ private boolean isErrorsEmpty(ActionErrors errors) { return errors == null || errors.size() == 0; } /** * Gets the cp id. * * @param dao : dao * @param scgId : scgId * * @return long : long * * @throws BizLogicException : BizLogicException */ private long getCpId(DAO dao, Long scgId) throws BizLogicException { long cpId = -1; try { final String columnName = Constants.SYSTEM_IDENTIFIER; final String columnValue = String.valueOf(scgId); final String[] selectColumnName = {"collectionProtocolRegistration.collectionProtocol.id"}; final QueryWhereClause queryWhereClause = new QueryWhereClause( SpecimenCollectionGroup.class.getName()); queryWhereClause.addCondition(new EqualClause(columnName, columnValue)); final List cpList = dao.retrieve(SpecimenCollectionGroup.class.getName(), selectColumnName, queryWhereClause); if (cpList != null && !cpList.isEmpty()) { cpId = (Long) cpList.get(0); } } catch (final DAOException excep) { LOGGER.error(excep.getMessage(),excep); throw new BizLogicException(excep); } return cpId; } /** * Sets the page data. * * @param request : request * @param form : form */ private void setPageData(HttpServletRequest request, CreateSpecimenForm form) { this.setConstantValues(request); AppUtility.setDefaultPrinterTypeLocation(form); final String pageOf = (String) request.getAttribute(Constants.PAGE_OF); this.setPageData1(request, form); this.setPageData2(request,pageOf); this.setPageData3(request, form); this.setNComboData(request, form); this.setXterIdData(request); } /** * Sets the page data1. * * @param request : request * @param form : form */ private void setPageData1(HttpServletRequest request, CreateSpecimenForm form) { final String operation = (String) request.getAttribute(Constants.OPERATION); final String pageOf = (String) request.getAttribute(Constants.PAGE_OF); String formName = operation; String editViewButton = "buttons." + Constants.EDIT; boolean readOnlyForAll = false; String printAction = "printDeriveSpecimen"; if (operation != null && operation.equals(Constants.EDIT)) { editViewButton = "buttons." + Constants.VIEW; formName = Constants.CREATE_SPECIMEN_EDIT_ACTION; } else { formName = Constants.CREATE_SPECIMEN_ADD_ACTION; if (isPageOfSpecimenCPQuery(pageOf)) { formName = Constants.CP_QUERY_CREATE_SPECIMEN_ADD_ACTION; printAction = "CPQueryPrintDeriveSpecimen"; } } if (operation != null && operation.equals(Constants.VIEW)) { readOnlyForAll = true; } final String changeAction3 = "setFormAction('" + formName + "')"; final String confirmDisableFuncName = "confirmDisable('" + formName + "',document.forms[0].activityStatus)"; final String addMoreSubmitFunctionName = "setSubmitted('ForwardTo','" + printAction + "','" + Constants.SPECIMEN_FORWARD_TO_LIST[3][1] + "')"; final String addMoreSubmit = addMoreSubmitFunctionName + "," + confirmDisableFuncName; request.setAttribute("changeAction3", changeAction3); request.setAttribute("addMoreSubmit", addMoreSubmit); request.setAttribute("pageOf", pageOf); request.setAttribute("operation", operation); request.setAttribute("formName", formName); request.setAttribute("editViewButton", editViewButton); request.setAttribute("readOnlyForAll", readOnlyForAll); request.setAttribute("printAction", printAction); String unitSpecimen = ""; String frdTo = ""; int exIdRows = 1; Map map = null; if (form != null) { map = form.getExternalIdentifier(); exIdRows = form.getExIdCounter(); frdTo = form.getForwardTo(); if (form.getUnit() != null) { unitSpecimen = form.getUnit(); } if (frdTo == null || frdTo.equals("")) { frdTo = "eventParameters"; } } final List exIdList = new ArrayList(); for (int i = exIdRows; i >= 1; i { final ExternalIdentifierBean exd = new ExternalIdentifierBean(i, map); exIdList.add(exd); } request.setAttribute("exIdList", exIdList); request.setAttribute("unitSpecimen", unitSpecimen); request.setAttribute("frdTo", frdTo); String multipleSpecimen = "0"; String action = Constants.CREATE_SPECIMEN_ADD_ACTION; if (request.getAttribute("multipleSpecimen") != null) { multipleSpecimen = "1"; action = "DerivedMultipleSpecimenAdd.do?retainForm=true"; } request.setAttribute("multipleSpecimen", multipleSpecimen); request.setAttribute("action", action); } /** * Sets the page data2. * * @param request : request * @param pageOf : pageOf */ private void setPageData2(HttpServletRequest request,String pageOf) { setActionToCall2ToReq(request, pageOf); setActionToCall1ToReq(request, pageOf); String deleteChecked = ""; final String multipleSpecimen = (String) request.getAttribute("multipleSpecimen"); if ("1".equals(multipleSpecimen)) { deleteChecked = "deleteChecked(\'addExternalIdentifier\'," + "\'NewMultipleSpecimenAction.do?method=" + "showDerivedSpecimenDialog&status=true&retainForm=" + "true\',document.forms[0].exIdCounter,\'chk_ex_\'," + "false);"; } else { if (isPageOfSpecimenCPQuery(pageOf)) { deleteChecked = "deleteChecked(\'addExternalIdentifier\',\'" + "CPQueryCreateSpecimen.do?pageOf=" + "pageOfCreateSpecimenCPQuery&status=true&button=deleteExId\'," + "document.forms[0].exIdCounter,\'chk_ex_\',false);"; } else { deleteChecked = "deleteChecked(\'addExternalIdentifier\',\'CreateSpecimen.do?" + "pageOf=pageOfCreateSpecimen&status=true&button=deleteExId\'," + "document.forms[0].exIdCounter,\'chk_ex_\',false);"; } } request.setAttribute("deleteChecked", deleteChecked); setActionToCallToReq(request, pageOf); String showRefreshTree = "false"; if (isPageOfSpecimenCPQuery(pageOf) && request.getAttribute(Constants.PARENT_SPECIMEN_ID) != null) { final Long parentSpecimenId = (Long) request .getAttribute(Constants.PARENT_SPECIMEN_ID); final String nodeId = "Specimen_" + parentSpecimenId.toString(); showRefreshTree = TRUE_STRING; final String refreshTree = "refreshTree('" + Constants.CP_AND_PARTICIPANT_VIEW + "','" + Constants.CP_TREE_VIEW + "','" + Constants.CP_SEARCH_CP_ID + "','" + Constants.CP_SEARCH_PARTICIPANT_ID + "','" + nodeId + "');"; request.setAttribute("refreshTree", refreshTree); } request.setAttribute("showRefreshTree", showRefreshTree); } /** * Sets the action to call to req. * * @param request the request * @param pageOf the page of */ private void setActionToCallToReq(HttpServletRequest request, String pageOf) { String actionToCall = "AddSpecimen.do?isQuickEvent=true"; if (isPageOfSpecimenCPQuery(pageOf)) { actionToCall = Constants.CP_QUERY_CREATE_SPECIMEN_ADD_ACTION + "?isQuickEvent=true"; } request.setAttribute("actionToCall", actionToCall); } /** * Sets the action to call1 to req. * * @param request the request * @param pageOf the page of */ private void setActionToCall1ToReq(HttpServletRequest request, String pageOf) { String actionToCall1 = "CreateSpecimen.do?operation=add&pageOf=&menuSelected=15&virtualLocated=false"; if (isPageOfSpecimenCPQuery(pageOf)) { actionToCall1 = Constants.CP_QUERY_CREATE_SPECIMEN_ACTION + "?operation=add"; } request.setAttribute("actionToCall1", actionToCall1); } /** * Sets the action to call2 to req. * * @param request the request * @param pageOf the page of */ private void setActionToCall2ToReq(HttpServletRequest request, String pageOf) { String actionToCall2 = "CreateSpecimen.do?operation=add&pageOf=&menuSelected=15&virtualLocated=false"; if (isPageOfSpecimenCPQuery(pageOf)) { actionToCall2 = Constants.CP_QUERY_CREATE_SPECIMEN_ACTION + "?pageOf=" + Constants.PAGE_OF_CREATE_SPECIMEN_CP_QUERY + "&operation=add&virtualLocated=false"; } request.setAttribute("actionToCall2", actionToCall2); } /** * Checks if is page of specimen cp query. * * @param pageOf the page of * * @return true, if checks if is page of specimen cp query */ private boolean isPageOfSpecimenCPQuery(String pageOf) { return pageOf != null && pageOf.equals(Constants.PAGE_OF_CREATE_SPECIMEN_CP_QUERY); } /** * Sets the page data3. * * @param request : request * @param form : form */ private void setPageData3(HttpServletRequest request, CreateSpecimenForm form) { final boolean readOnlyForAll = ((Boolean) request.getAttribute("readOnlyForAll")) .booleanValue(); final String changeAction1 = "setFormAction('MakeParticipantEditable.do?" + Constants.EDITABLE + "=" + !readOnlyForAll + "')"; request.setAttribute("changeAction1", changeAction1); final List specClassList = (List) request.getAttribute(Constants.SPECIMEN_CLASS_LIST); request.setAttribute("specClassList", specClassList); List specimenTypeList = (List) request.getAttribute(Constants.SPECIMEN_TYPE_LIST); final HashMap specimenTypeMap = (HashMap) request.getAttribute(Constants.SPECIMEN_TYPE_MAP); final String classValue = (String) form.getClassName(); specimenTypeList = (List) specimenTypeMap.get(classValue); if (specimenTypeList == null) { specimenTypeList = new ArrayList(); specimenTypeList.add(new NameValueBean(Constants.SELECT_OPTION, "-1")); } request.setAttribute("specimenTypeList", specimenTypeList); request.setAttribute("specimenTypeMap", specimenTypeMap); } /** * Sets the constant values. * * @param request : request */ private void setConstantValues(HttpServletRequest request) { request.setAttribute("oper", Constants.OPERATION); request.setAttribute("query", Constants.QUERY); request.setAttribute("search", Constants.SEARCH); request.setAttribute("view", Constants.VIEW); request.setAttribute("isSpecimenLabelGeneratorAvl", Variables.isSpecimenLabelGeneratorAvl); request.setAttribute("UNIT_MG", Constants.UNIT_MG); request.setAttribute("labelNames", Constants.STORAGE_CONTAINER_LABEL); request.setAttribute("ADD", Constants.ADD); request.setAttribute("isSpecimenBarcodeGeneratorAvl", Variables.isSpecimenBarcodeGeneratorAvl); request.setAttribute("SPECIMEN_BUTTON_TIPS", Constants.SPECIMEN_BUTTON_TIPS[3]); request.setAttribute("SPECIMEN_FORWARD_TO_LIST", Constants.SPECIMEN_FORWARD_TO_LIST[3][0]); } /** * Sets the n combo data. * * @param request : request * @param form : form */ private void setNComboData(HttpServletRequest request, CreateSpecimenForm form) { final String[] attrNames = {"storageContainer", "positionDimensionOne", "positionDimensionTwo"}; final String[] tdStyleClassArray = {"formFieldSized15", "customFormField", "customFormField"}; request.setAttribute("attrNames", attrNames); request.setAttribute("tdStyleClassArray", tdStyleClassArray); String[] initValues = new String[3]; final List initValuesList = (List) request.getAttribute(INITVALUES_STRING); if (initValuesList != null) { initValues = (String[]) initValuesList.get(0); } request.setAttribute(INITVALUES_STRING, initValues); String className = (String) request.getAttribute(Constants.SPECIMEN_CLASS_NAME); if (className == null) { className = ""; } String collectionProtocolId = (String) request .getAttribute(Constants.COLLECTION_PROTOCOL_ID); if (collectionProtocolId == null) { collectionProtocolId = ""; } final String url = "ShowFramedPage.do?pageOf=pageOfSpecimen&amp;" + "selectedContainerName=selectedContainerName&amp;" + "pos1=pos1&amp;pos2=pos2&amp;containerId=containerId" + "&" + Constants.CAN_HOLD_SPECIMEN_CLASS + "=" + className + "&" + Constants.CAN_HOLD_COLLECTION_PROTOCOL + "=" + collectionProtocolId; final String buttonOnClicked = "mapButtonClickedOnNewSpecimen('" + url + "','createSpecimen')"; request.setAttribute("buttonOnClicked", buttonOnClicked); final int radioSelected = form.getStContSelection(); String storagePosition = getStoragePosition(radioSelected); request.setAttribute("storagePosition", storagePosition); final Map dataMap = (Map) request.getAttribute(Constants.AVAILABLE_CONTAINER_MAP); final String jsForOutermostDataTable = ScriptGenerator.getJSForOutermostDataTable(); final String jsEquivalentFor = ScriptGenerator.getJSEquivalentFor(dataMap, "1"); request.setAttribute("dataMap", dataMap); request.setAttribute("jsEquivalentFor", jsEquivalentFor); request.setAttribute("jsForOutermostDataTable", jsForOutermostDataTable); } /** * Gets the storage position. * * @param radioSelected the radio selected * * @return the storage position */ private String getStoragePosition(final int radioSelected) { String storagePosition = Constants.STORAGE_TYPE_POSITION_VIRTUAL; if (radioSelected == 1) { storagePosition = Constants.STORAGE_TYPE_POSITION_VIRTUAL; } else if (radioSelected == 2) { storagePosition = Constants.STORAGE_TYPE_POSITION_AUTO; } else if (radioSelected == 3) { storagePosition = Constants.STORAGE_TYPE_POSITION_MANUAL; } return storagePosition; } /** * Sets the xter id data. * * @param request : request */ private void setXterIdData(HttpServletRequest request) { final String eiDispType1 = request.getParameter("eiDispType"); request.setAttribute("eiDispType1", eiDispType1); String delExtIds = "deleteExternalIdentifiers('pageOfMultipleSpecimen')"; if ((String) request.getAttribute(Constants.PAGE_OF) != null) { delExtIds = "deleteExternalIdentifiers('" + (String) request.getAttribute(Constants.PAGE_OF) + "');"; } request.setAttribute("delExtIds", delExtIds); } /** * @param form * : form * @return String : String */ /*protected String getObjectId(AbstractActionForm form) { final CreateSpecimenForm createSpecimenForm = (CreateSpecimenForm) form; SpecimenCollectionGroup specimenCollectionGroup = null; if (createSpecimenForm.getParentSpecimenId() != null && createSpecimenForm.getParentSpecimenId() != "") { final Specimen specimen = AppUtility.getSpecimen(createSpecimenForm .getParentSpecimenId()); specimenCollectionGroup = specimen.getSpecimenCollectionGroup(); final CollectionProtocolRegistration cpr = specimenCollectionGroup .getCollectionProtocolRegistration(); if (cpr != null) { final CollectionProtocol cp = cpr.getCollectionProtocol(); return Constants.COLLECTION_PROTOCOL_CLASS_NAME + "_" + cp.getId(); } } return null; }*/ }
package ca.corefacility.bioinformatics.irida.service.remote; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.time.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import ca.corefacility.bioinformatics.irida.exceptions.IridaOAuthException; import ca.corefacility.bioinformatics.irida.model.MutableIridaThing; import ca.corefacility.bioinformatics.irida.model.RemoteAPI; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.project.Project; import ca.corefacility.bioinformatics.irida.model.project.ProjectSyncFrequency; import ca.corefacility.bioinformatics.irida.model.remote.RemoteStatus; import ca.corefacility.bioinformatics.irida.model.remote.RemoteStatus.SyncStatus; import ca.corefacility.bioinformatics.irida.model.remote.RemoteSynchronizable; import ca.corefacility.bioinformatics.irida.model.sample.Sample; import ca.corefacility.bioinformatics.irida.model.sample.SampleSequencingObjectJoin; import ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFilePair; import ca.corefacility.bioinformatics.irida.model.sequenceFile.SingleEndSequenceFile; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.security.ProjectSynchronizationAuthenticationToken; import ca.corefacility.bioinformatics.irida.service.ProjectService; import ca.corefacility.bioinformatics.irida.service.RemoteAPITokenService; import ca.corefacility.bioinformatics.irida.service.SequencingObjectService; import ca.corefacility.bioinformatics.irida.service.sample.SampleService; /** * Service class to run a project synchornization task. Ths class will be * responsible for communicating with Remote IRIDA installations and pulling * metadata and sequencing data into the local installation. */ @Service public class ProjectSynchronizationService { private static final Logger logger = LoggerFactory.getLogger(ProjectSynchronizationService.class); private ProjectService projectService; private SampleService sampleService; private SequencingObjectService objectService; private ProjectRemoteService projectRemoteService; private SampleRemoteService sampleRemoteService; private SingleEndSequenceFileRemoteService singleEndRemoteService; private SequenceFilePairRemoteService pairRemoteService; private RemoteAPITokenService tokenService; @Autowired public ProjectSynchronizationService(ProjectService projectService, SampleService sampleService, SequencingObjectService objectService, ProjectRemoteService projectRemoteService, SampleRemoteService sampleRemoteService, SingleEndSequenceFileRemoteService singleEndRemoteService, SequenceFilePairRemoteService pairRemoteService, RemoteAPITokenService tokenService) { this.projectService = projectService; this.sampleService = sampleService; this.objectService = objectService; this.projectRemoteService = projectRemoteService; this.sampleRemoteService = sampleRemoteService; this.singleEndRemoteService = singleEndRemoteService; this.pairRemoteService = pairRemoteService; this.tokenService = tokenService; } /** * Method checking for remote projects that have passed their frequency * time. It will mark them as {@link SyncStatus#MARKED} */ public void findProjectsToMark() { List<Project> remoteProjects = projectService.getRemoteProjects(); for (Project p : remoteProjects) { // check the frequency for each remote project RemoteStatus remoteStatus = p.getRemoteStatus(); Date lastUpdate = remoteStatus.getLastUpdate(); ProjectSyncFrequency syncFrequency = p.getSyncFrequency(); // if the project is set to be synched if (syncFrequency != null && syncFrequency != ProjectSyncFrequency.NEVER) { /* * find the next sync date and see if it's passed. if it has set * as MARKED */ Date nextSync = DateUtils.addDays(lastUpdate, syncFrequency.getDays()); if (nextSync.before(new Date())) { Map<String, Object> updates = new HashMap<>(); remoteStatus.setSyncStatus(SyncStatus.MARKED); updates.put("remoteStatus", remoteStatus); projectService.updateProjectSettings(p, updates); } } } } /** * Find projects which should be synchronized and launch a synchornization * task. */ public void findMarkedProjectsToSync() { // mark any projects which should be synched first findProjectsToMark(); List<Project> markedProjects = projectService.getProjectsWithRemoteSyncStatus(SyncStatus.MARKED); logger.debug("Checking for projects to sync"); for (Project project : markedProjects) { /* * Set the correct authorization for the user who's syncing the * project */ User readBy = project.getRemoteStatus().getReadBy(); setAuthentication(readBy); logger.debug("Syncing project at " + project.getRemoteStatus().getURL()); try { RemoteAPI api = project.getRemoteStatus().getApi(); tokenService.updateTokenFromRefreshToken(api); syncProject(project); } catch (IridaOAuthException e) { logger.debug("Can't sync project " + project.getRemoteStatus().getURL() + " due to oauth error:", e); project.getRemoteStatus().setSyncStatus(SyncStatus.UNAUTHORIZED); projectService.update(project); } catch (Exception e) { logger.debug("An error occurred while synchronizing project " + project.getRemoteStatus().getURL(), e); project.getRemoteStatus().setSyncStatus(SyncStatus.ERROR); projectService.update(project); } finally { // clear the context holder when you're done SecurityContextHolder.clearContext(); logger.debug("Done project " + project.getRemoteStatus().getURL()); } } } /** * Synchronize a given {@link Project} to the local installation. * * @param project * the {@link Project} to synchronize. This should have been read * from a remote api. */ private void syncProject(Project project) { project.getRemoteStatus().setSyncStatus(SyncStatus.UPDATING); projectService.update(project); String projectURL = project.getRemoteStatus().getURL(); Project readProject = projectRemoteService.read(projectURL); // ensure we use the same IDs readProject = updateIds(project, readProject); // if project was updated remotely, update it here if (checkForChanges(project.getRemoteStatus(), readProject)) { logger.debug("found changes for project " + readProject.getSelfHref()); project = projectService.update(readProject); } List<Join<Project, Sample>> localSamples = sampleService.getSamplesForProject(project); // get all the samples by their url Map<String, Sample> samplesByUrl = new HashMap<>(); localSamples.forEach(j -> { Sample sample = j.getObject(); String url = sample.getRemoteStatus().getURL(); samplesByUrl.put(url, sample); }); List<Sample> readSamplesForProject = sampleRemoteService.getSamplesForProject(readProject); for (Sample s : readSamplesForProject) { s.setId(null); syncSample(s, project, samplesByUrl); } project.setRemoteStatus(readProject.getRemoteStatus()); project.getRemoteStatus().setSyncStatus(SyncStatus.SYNCHRONIZED); projectService.update(project); } /** * Synchronize a given {@link Sample} to the local installation. * * @param sample * the {@link Sample} to synchronize. This should have been read * from a remote api. * @param project * The {@link Project} the {@link Sample} belongs in. */ public void syncSample(Sample sample, Project project, Map<String, Sample> existingSamples) { Sample localSample; if (existingSamples.containsKey(sample.getRemoteStatus().getURL())) { // if the sample already exists check if it's been updated localSample = existingSamples.get(sample.getRemoteStatus().getURL()); // if there's changes, update the sample if (checkForChanges(localSample.getRemoteStatus(), sample)) { logger.debug("found changes for sample " + sample.getSelfHref()); // ensure the ids are properly set sample = updateIds(localSample, sample); sample.getRemoteStatus().setSyncStatus(SyncStatus.UPDATING); localSample = sampleService.update(sample); } } else { // if the sample doesn't already exist create it sample.getRemoteStatus().setSyncStatus(SyncStatus.UPDATING); localSample = sampleService.create(sample); projectService.addSampleToProject(project, sample); } // get the local files and organize by their url Collection<SampleSequencingObjectJoin> localPairs = objectService.getSequencesForSampleOfType(localSample, SequenceFilePair.class); Map<String, SequenceFilePair> pairsByUrl = new HashMap<>(); localPairs.forEach(j -> { SequenceFilePair pair = (SequenceFilePair) j.getObject(); String url = pair.getRemoteStatus().getURL(); pairsByUrl.put(url, pair); }); List<SequenceFilePair> sequenceFilePairsForSample = pairRemoteService.getSequenceFilePairsForSample(sample); for (SequenceFilePair pair : sequenceFilePairsForSample) { if (!pairsByUrl.containsKey(pair.getRemoteStatus().getURL())) { pair.setId(null); syncSequenceFilePair(pair, localSample); } } List<SingleEndSequenceFile> unpairedFilesForSample = singleEndRemoteService.getUnpairedFilesForSample(sample); for (SingleEndSequenceFile file : unpairedFilesForSample) { file.setId(null); syncSingleEndSequenceFile(file); } localSample.getRemoteStatus().setSyncStatus(SyncStatus.SYNCHRONIZED); sampleService.update(localSample); } // TODO: Fill out this method public void syncSingleEndSequenceFile(SingleEndSequenceFile file) { // objectService.create(file); } /** * Synchronize a given {@link SequenceFilePair} to the local installation. * * @param pair * the {@link SequenceFilePair} to sync. This should have been * read from a remote api. * @param sample * The {@link Sample} to add the pair to. */ public void syncSequenceFilePair(SequenceFilePair pair, Sample sample) { pair.getRemoteStatus().setSyncStatus(SyncStatus.UPDATING); pair = pairRemoteService.mirrorSequencingObject(pair); pair.getFiles().forEach(s -> { s.setId(null); s.getRemoteStatus().setSyncStatus(SyncStatus.SYNCHRONIZED); }); objectService.createSequencingObjectInSample(pair, sample); RemoteStatus pairStatus = pair.getRemoteStatus(); pairStatus.setSyncStatus(SyncStatus.SYNCHRONIZED); objectService.updateRemoteStatus(pair.getId(), pairStatus); } /** * Check if an object has been updated since it was last read * * @param originalStatus * the original object's {@link RemoteStatus} * @param read * the newly read {@link RemoteSynchronizable} object * @return true if the object has changed, false if not */ private boolean checkForChanges(RemoteStatus originalStatus, RemoteSynchronizable read) { return originalStatus.getRemoteHashCode() != read.hashCode(); } /** * Update the IDs of a newly read object and it's associated RemoteStatus to * the IDs of a local copy * * @param original * the original object * @param updated * the newly read updated object * @return the enhanced newly read object */ private <Type extends MutableIridaThing & RemoteSynchronizable> Type updateIds(Type original, Type updated) { updated.setId(original.getId()); updated.getRemoteStatus().setId(original.getRemoteStatus().getId()); return updated; } /** * Set the given user's authentication in the SecurityContextHolder * * @param userAuthentication * The {@link User} to set in the context holder */ private void setAuthentication(User user) { ProjectSynchronizationAuthenticationToken userAuthentication = new ProjectSynchronizationAuthenticationToken( user); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(userAuthentication); SecurityContextHolder.setContext(context); } }
package ca.corefacility.bioinformatics.irida.service.remote; import ca.corefacility.bioinformatics.irida.exceptions.IridaOAuthException; import ca.corefacility.bioinformatics.irida.exceptions.LinkNotFoundException; import ca.corefacility.bioinformatics.irida.exceptions.ProjectSynchronizationException; import ca.corefacility.bioinformatics.irida.model.MutableIridaThing; import ca.corefacility.bioinformatics.irida.model.RemoteAPI; import ca.corefacility.bioinformatics.irida.model.assembly.GenomeAssembly; import ca.corefacility.bioinformatics.irida.model.assembly.UploadedAssembly; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.joins.impl.SampleGenomeAssemblyJoin; import ca.corefacility.bioinformatics.irida.model.project.Project; import ca.corefacility.bioinformatics.irida.model.project.ProjectSyncFrequency; import ca.corefacility.bioinformatics.irida.model.remote.RemoteStatus; import ca.corefacility.bioinformatics.irida.model.remote.RemoteStatus.SyncStatus; import ca.corefacility.bioinformatics.irida.model.remote.RemoteSynchronizable; import ca.corefacility.bioinformatics.irida.model.sample.Sample; import ca.corefacility.bioinformatics.irida.model.sample.SampleSequencingObjectJoin; import ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry; import ca.corefacility.bioinformatics.irida.model.sequenceFile.*; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.security.ProjectSynchronizationAuthenticationToken; import ca.corefacility.bioinformatics.irida.service.*; import ca.corefacility.bioinformatics.irida.service.sample.MetadataTemplateService; import ca.corefacility.bioinformatics.irida.service.sample.SampleService; import org.apache.commons.lang3.time.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import java.util.*; import java.util.stream.Collectors; import com.google.common.collect.Lists; /** * Service class to run a project synchornization task. Ths class will be * responsible for communicating with Remote IRIDA installations and pulling * metadata and sequencing data into the local installation. */ @Service public class ProjectSynchronizationService { private static final Logger logger = LoggerFactory.getLogger(ProjectSynchronizationService.class); private ProjectService projectService; private SampleService sampleService; private SequencingObjectService objectService; private MetadataTemplateService metadataTemplateService; private GenomeAssemblyService assemblyService; private ProjectRemoteService projectRemoteService; private SampleRemoteService sampleRemoteService; private SingleEndSequenceFileRemoteService singleEndRemoteService; private SequenceFilePairRemoteService pairRemoteService; private GenomeAssemblyRemoteService assemblyRemoteService; private Fast5ObjectRemoteService fast5ObjectRemoteService; private RemoteAPITokenService tokenService; private EmailController emailController; @Autowired public ProjectSynchronizationService(ProjectService projectService, SampleService sampleService, SequencingObjectService objectService, MetadataTemplateService metadataTemplateService, GenomeAssemblyService assemblyService, ProjectRemoteService projectRemoteService, SampleRemoteService sampleRemoteService, SingleEndSequenceFileRemoteService singleEndRemoteService, SequenceFilePairRemoteService pairRemoteService, GenomeAssemblyRemoteService assemblyRemoteService, Fast5ObjectRemoteService fast5ObjectRemoteService, RemoteAPITokenService tokenService, EmailController emailController) { this.projectService = projectService; this.sampleService = sampleService; this.objectService = objectService; this.metadataTemplateService = metadataTemplateService; this.assemblyService = assemblyService; this.projectRemoteService = projectRemoteService; this.sampleRemoteService = sampleRemoteService; this.singleEndRemoteService = singleEndRemoteService; this.pairRemoteService = pairRemoteService; this.assemblyRemoteService = assemblyRemoteService; this.fast5ObjectRemoteService = fast5ObjectRemoteService; this.tokenService = tokenService; this.emailController = emailController; } /** * Method checking for remote projects that have passed their frequency * time. It will mark them as {@link SyncStatus#MARKED} */ public void findProjectsToMark() { List<Project> remoteProjects = projectService.getRemoteProjects(); for (Project p : remoteProjects) { // check the frequency for each remote project RemoteStatus remoteStatus = p.getRemoteStatus(); Date lastUpdate = remoteStatus.getLastUpdate(); ProjectSyncFrequency syncFrequency = p.getSyncFrequency(); // if the project is set to be synched if (syncFrequency != null) { if (syncFrequency != ProjectSyncFrequency.NEVER) { /* * find the next sync date and see if it's passed. if it has * set as MARKED */ Date nextSync = DateUtils.addDays(lastUpdate, syncFrequency.getDays()); if (nextSync.before(new Date())) { Map<String, Object> updates = new HashMap<>(); remoteStatus.setSyncStatus(SyncStatus.MARKED); updates.put("remoteStatus", remoteStatus); projectService.updateProjectSettings(p, updates); } } else if (remoteStatus.getSyncStatus() != RemoteStatus.SyncStatus.UNSYNCHRONIZED) { /* * if a sync frequency is NEVER and it's status isn't * UNSYNCHRONIZED, it should be set as such */ remoteStatus.setSyncStatus(SyncStatus.UNSYNCHRONIZED); Map<String, Object> updates = new HashMap<>(); updates.put("remoteStatus", remoteStatus); projectService.updateProjectSettings(p, updates); } } } } /** * Find projects which should be synchronized and launch a synchornization * task. */ public synchronized void findMarkedProjectsToSync() { // mark any projects which should be synched first findProjectsToMark(); List<Project> markedProjects = projectService.getProjectsWithRemoteSyncStatus(SyncStatus.MARKED); logger.trace("Checking for projects to sync"); for (Project project : markedProjects) { /* * Set the correct authorization for the user who's syncing the * project */ User readBy = project.getRemoteStatus().getReadBy(); try { setAuthentication(readBy); logger.trace("Syncing project at " + project.getRemoteStatus().getURL()); RemoteAPI api = project.getRemoteStatus().getApi(); tokenService.updateTokenFromRefreshToken(api); syncProject(project); } catch (IridaOAuthException e) { logger.trace("Can't sync project " + project.getRemoteStatus().getURL() + " due to oauth error:", e); //re-reading project to get updated version project = projectService.read(project.getId()); project.getRemoteStatus().setSyncStatus(SyncStatus.UNAUTHORIZED); projectService.update(project); emailController.sendProjectSyncUnauthorizedEmail(project); } catch (Exception e) { logger.debug("An error occurred while synchronizing project " + project.getRemoteStatus().getURL(), e); //re-reading project to get updated version project = projectService.read(project.getId()); project.getRemoteStatus().setSyncStatus(SyncStatus.ERROR); projectService.update(project); } finally { // clear the context holder when you're done SecurityContextHolder.clearContext(); logger.trace("Done project " + project.getRemoteStatus().getURL()); } } } /** * Synchronize a given {@link Project} to the local installation. * * @param project * the {@link Project} to synchronize. This should have been read * from a remote api. */ private void syncProject(Project project) { project.getRemoteStatus().setSyncStatus(SyncStatus.UPDATING); project.getRemoteStatus().setLastUpdate(new Date()); projectService.update(project); List<ProjectSynchronizationException> syncExceptions = new ArrayList<>(); String projectURL = project.getRemoteStatus().getURL(); Project readProject = projectRemoteService.read(projectURL); //get the project hash from the host Integer projectHash; try { projectHash = projectRemoteService.getProjectHash(readProject); } catch (LinkNotFoundException e) { logger.warn("The project on the referenced IRIDA doesn't support project hashing: " + projectURL); projectHash = null; } //check if the project hashes are different. if projectHash is null the other service doesn't support hashing so do a full check if (projectHash == null || !projectHash.equals(project.getRemoteProjectHash())) { // ensure we use the same IDs readProject = updateIds(project, readProject); // if project was updated remotely, update it here if (checkForChanges(project.getRemoteStatus(), readProject)) { logger.debug("found changes for project " + readProject.getSelfHref()); // need to keep the status and frequency of the local project RemoteStatus originalStatus = project.getRemoteStatus(); readProject.getRemoteStatus().setSyncStatus(originalStatus.getSyncStatus()); readProject.setSyncFrequency(project.getSyncFrequency()); project = projectService.update(readProject); } List<Join<Project, Sample>> localSamples = sampleService.getSamplesForProject(project); // get all the samples by their url Map<String, Sample> samplesByUrl = new HashMap<>(); localSamples.forEach(j -> { Sample sample = j.getObject(); // If a user has added a sample for some reason, ignore it if (sample.getRemoteStatus() != null) { String url = sample.getRemoteStatus().getURL(); samplesByUrl.put(url, sample); } else { logger.warn("Sample " + sample.getId() + " is not a remote sample. It will not be synchronized."); } }); //read the remote samples from the remote API List<Sample> readSamplesForProject = sampleRemoteService.getSamplesForProject(readProject); //get a list of all remote URLs in the project Set<String> remoteUrls = readSamplesForProject.stream() .map(s -> s.getRemoteStatus() .getURL()) .collect(Collectors.toSet()); // Check for local samples which no longer exist by URL Set<String> localUrls = new HashSet<>(samplesByUrl.keySet()); //remove any URL from the local list that we've seen remotely remoteUrls.forEach(s -> { localUrls.remove(s); }); // if any URLs still exist in localUrls, it must have been deleted remotely for (String localUrl : localUrls) { logger.trace("Sample " + localUrl + " has been removed remotely. Removing from local project."); projectService.removeSampleFromProject(project, samplesByUrl.get(localUrl)); samplesByUrl.remove(localUrl); } for (Sample s : readSamplesForProject) { s.setId(null); List<ProjectSynchronizationException> syncExceptionsSample = syncSample(s, project, samplesByUrl); syncExceptions.addAll(syncExceptionsSample); } } else{ logger.debug("No changes to project. Skipping"); } // re-read project to ensure any updates are reflected project = projectService.read(project.getId()); project.setRemoteProjectHash(projectHash); project.setRemoteStatus(readProject.getRemoteStatus()); if (syncExceptions.isEmpty()) { project.getRemoteStatus().setSyncStatus(SyncStatus.SYNCHRONIZED); } else { project.getRemoteStatus().setSyncStatus(SyncStatus.ERROR); logger.error("Error syncing project " + project.getId() + " setting sync status to ERROR"); } projectService.update(project); } /** * Synchronize a given {@link Sample} to the local installation. * * @param sample the {@link Sample} to synchronize. This should have been read * from a remote api. * @param project The {@link Project} the {@link Sample} belongs in. * @param existingSamples A map of samples that have already been synchronized. These will be checked to see if they've been updated * @return A list of {@link ProjectSynchronizationException}s, empty if no errors. */ public List<ProjectSynchronizationException> syncSample(Sample sample, Project project, Map<String, Sample> existingSamples) { Sample localSample; if (existingSamples.containsKey(sample.getRemoteStatus().getURL())) { // if the sample already exists check if it's been updated localSample = existingSamples.get(sample.getRemoteStatus().getURL()); // if there's changes, update the sample if (checkForChanges(localSample.getRemoteStatus(), sample)) { logger.debug("found changes for sample " + sample.getSelfHref()); // ensure the ids are properly set sample = updateIds(localSample, sample); sample.getRemoteStatus().setSyncStatus(SyncStatus.UPDATING); localSample = sampleService.update(sample); localSample = syncSampleMetadata(sample, localSample); } } else { // if the sample doesn't already exist create it sample.getRemoteStatus().setSyncStatus(SyncStatus.UPDATING); localSample = sampleService.create(sample); projectService.addSampleToProject(project, sample, true); localSample = syncSampleMetadata(sample, localSample); } //get a collection of the files already sync'd. we don't want to grab them a 2nd time. Collection<SampleSequencingObjectJoin> localObjects = objectService.getSequencingObjectsForSample(localSample); Set<String> objectsByUrl = new HashSet<>(); localObjects.forEach(j -> { SequencingObject pair = j.getObject(); // check if the file was actually sync'd. Someone may have // concatenated it if (pair.getRemoteStatus() != null) { String url = pair.getRemoteStatus().getURL(); objectsByUrl.add(url); } }); //same with assemblies. get the ones we've already grabbed and store their URL so we don't double-sync Collection<SampleGenomeAssemblyJoin> assembliesForSample = assemblyService.getAssembliesForSample(localSample); Set<String> localAssemblyUrls = new HashSet<>(); assembliesForSample.forEach(j -> { GenomeAssembly genomeAssembly = j.getObject(); if (genomeAssembly.getRemoteStatus() != null) { String url = genomeAssembly.getRemoteStatus() .getURL(); localAssemblyUrls.add(url); } }); //a list of errors from the sync. we'll collect them as we go. we won't cancel the sync for one error List<ProjectSynchronizationException> syncErrors = new ArrayList<>(); //list the pairs from the remote api List<SequenceFilePair> sequenceFilePairsForSample = pairRemoteService.getSequenceFilePairsForSample(sample); //for each pair for (SequenceFilePair pair : sequenceFilePairsForSample) { //check if we've already got it if (!objectsByUrl.contains(pair.getRemoteStatus().getURL())) { pair.setId(null); //if not, download it locally try { syncSequenceFilePair(pair, localSample); } catch (ProjectSynchronizationException e) { syncErrors.add(e); } } } //list the single files from the remote api List<SingleEndSequenceFile> unpairedFilesForSample = singleEndRemoteService.getUnpairedFilesForSample(sample); //for each single file for (SingleEndSequenceFile file : unpairedFilesForSample) { //check if we already have it if (!objectsByUrl.contains(file.getRemoteStatus().getURL())) { file.setId(null); //if not, get it locally and save it try { syncSingleEndSequenceFile(file, localSample); } catch (ProjectSynchronizationException e) { syncErrors.add(e); } } } //list the fast5 files from the remote api List<Fast5Object> fast5FilesForSample; try { fast5FilesForSample = fast5ObjectRemoteService.getFast5FilesForSample(sample); } catch (LinkNotFoundException e) { logger.warn("The sample on the referenced IRIDA doesn't support fast5 data: " + sample.getSelfHref()); fast5FilesForSample = Lists.newArrayList(); } //for each fast5 file for (Fast5Object fast5Object : fast5FilesForSample) { //check if we already have it if (!objectsByUrl.contains(fast5Object.getRemoteStatus() .getURL())) { fast5Object.setId(null); //if not, get it locally and save it try { syncFast5File(fast5Object, localSample); } catch (ProjectSynchronizationException e) { syncErrors.add(e); } } } //list the remote assemblies for the sample. List<UploadedAssembly> genomeAssembliesForSample; try { genomeAssembliesForSample = assemblyRemoteService.getGenomeAssembliesForSample(sample); } catch (LinkNotFoundException e) { //if the target IRIDA doesn't support assemblies yet, warn and ignore assemblies. logger.warn("The sample on the referenced IRIDA doesn't support assemblies: " + sample.getSelfHref()); genomeAssembliesForSample = Lists.newArrayList(); } //for each assembly for (UploadedAssembly file : genomeAssembliesForSample) { //if we haven't already sync'd this assembly, get it if (!localAssemblyUrls.contains(file.getRemoteStatus() .getURL())) { file.setId(null); try { syncAssembly(file, localSample); } catch (ProjectSynchronizationException e) { syncErrors.add(e); } } } //if we have no errors, report that the sample is sync'd if (syncErrors.isEmpty()) { localSample.getRemoteStatus().setSyncStatus(SyncStatus.SYNCHRONIZED); } else { //otherwise set it as an error and log localSample.getRemoteStatus().setSyncStatus(SyncStatus.ERROR); logger.error( "Setting sample " + localSample.getId() + " sync status to ERROR due to sync errors with files"); } sampleService.update(localSample); return syncErrors; } /** * Synchronize the given sample's metadata * * @param remoteSample the sample read from the remote api * @param localSample the local sample being saved * @return the synchronized sample */ public Sample syncSampleMetadata(Sample remoteSample, Sample localSample) { Map<String, MetadataEntry> sampleMetadata = sampleRemoteService.getSampleMetadata(remoteSample); sampleMetadata.values() .forEach(e -> e.setId(null)); Set<MetadataEntry> metadata = metadataTemplateService.convertMetadataStringsToSet(sampleMetadata); localSample = sampleService.updateSampleMetadata(localSample, metadata); return localSample; } /** * Synchronize a given {@link SingleEndSequenceFile} to the local * installation * * @param file * the {@link SingleEndSequenceFile} to sync * @param sample * the {@link Sample} to add the file to */ public void syncSingleEndSequenceFile(SingleEndSequenceFile file, Sample sample) { RemoteStatus fileStatus = file.getRemoteStatus(); fileStatus.setSyncStatus(SyncStatus.UPDATING); try { file = singleEndRemoteService.mirrorSequencingObject(file); syncSequencingObject(file, sample, fileStatus); } catch (Exception e) { logger.error("Error transferring file: " + file.getRemoteStatus().getURL(), e); throw new ProjectSynchronizationException("Could not synchronize file " + file.getRemoteStatus().getURL(), e); } } /** * Synchronize a given {@link Fast5Object} to the local * installation * * @param fast5Object * the {@link Fast5Object} to sync * @param sample * the {@link Sample} to add the file to */ public void syncFast5File(Fast5Object fast5Object, Sample sample) { RemoteStatus fileStatus = fast5Object.getRemoteStatus(); fileStatus.setSyncStatus(SyncStatus.UPDATING); try { fast5Object = fast5ObjectRemoteService.mirrorSequencingObject(fast5Object); syncSequencingObject(fast5Object, sample, fileStatus); } catch (Exception e) { logger.error("Error transferring file: " + fast5Object.getRemoteStatus().getURL(), e); throw new ProjectSynchronizationException("Could not synchronize file " + fast5Object.getRemoteStatus().getURL(), e); } } /** * Synchronize a given {@link UploadedAssembly} to the local * installation * * @param assembly the {@link UploadedAssembly} to sync * @param sample the {@link Sample} to add the assembly to */ public void syncAssembly(UploadedAssembly assembly, Sample sample) { RemoteStatus fileStatus = assembly.getRemoteStatus(); fileStatus.setSyncStatus(SyncStatus.UPDATING); try { assembly = assemblyRemoteService.mirrorAssembly(assembly); assembly.getRemoteStatus() .setSyncStatus(SyncStatus.SYNCHRONIZED); assemblyService.createAssemblyInSample(sample, assembly); } catch (Exception e) { logger.error("Error transferring assembly: " + assembly.getRemoteStatus() .getURL(), e); throw new ProjectSynchronizationException("Could not synchronize assembly " + assembly.getRemoteStatus() .getURL(), e); } } /** * Synchronize a given {@link SequenceFilePair} to the local installation. * * @param pair * the {@link SequenceFilePair} to sync. This should have been * read from a remote api. * @param sample * The {@link Sample} to add the pair to. */ public void syncSequenceFilePair(SequenceFilePair pair, Sample sample) { RemoteStatus fileStatus = pair.getRemoteStatus(); fileStatus.setSyncStatus(SyncStatus.UPDATING); try { pair = pairRemoteService.mirrorSequencingObject(pair); syncSequencingObject(pair, sample, fileStatus); } catch (Exception e) { logger.error("Error transferring file: " + pair.getRemoteStatus().getURL(), e); throw new ProjectSynchronizationException("Could not synchronize pair " + pair.getRemoteStatus().getURL(), e); } } /** * Check if an object has been updated since it was last read * * @param originalStatus * the original object's {@link RemoteStatus} * @param read * the newly read {@link RemoteSynchronizable} object * @return true if the object has changed, false if not */ private boolean checkForChanges(RemoteStatus originalStatus, RemoteSynchronizable read) { return originalStatus.getRemoteHashCode() != read.hashCode(); } /** * Update the IDs of a newly read object and it's associated RemoteStatus to * the IDs of a local copy * * @param original * the original object * @param updated * the newly read updated object * @return the enhanced newly read object */ private <Type extends MutableIridaThing & RemoteSynchronizable> Type updateIds(Type original, Type updated) { updated.setId(original.getId()); updated.getRemoteStatus().setId(original.getRemoteStatus().getId()); return updated; } /** * Set the given user's authentication in the SecurityContextHolder * * @param user * The {@link User} to set in the context holder */ private void setAuthentication(User user) { ProjectSynchronizationAuthenticationToken userAuthentication = new ProjectSynchronizationAuthenticationToken( user); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(userAuthentication); SecurityContextHolder.setContext(context); } /** * Synchronize a given {@link SequencingObject} to the local installation. * * @param sequencingObject The sequencing object to sync * @param sample The sample to sync * @param sequencingObjectStatus The remote status of the sequencing object */ private void syncSequencingObject(SequencingObject sequencingObject, Sample sample, RemoteStatus sequencingObjectStatus) { sequencingObject.setProcessingState(SequencingObject.ProcessingState.UNPROCESSED); sequencingObject.setFileProcessor(null); sequencingObject.getFiles().forEach(s -> { s.setId(null); sequencingObjectStatus.setSyncStatus(SyncStatus.SYNCHRONIZED); }); objectService.createSequencingObjectInSample(sequencingObject, sample); sequencingObjectStatus.setSyncStatus(SyncStatus.SYNCHRONIZED); objectService.updateRemoteStatus(sequencingObject.getId(), sequencingObjectStatus); } }
package com.rizki.mufrizal.aplikasi.inventory.abstractTableModel; import com.rizki.mufrizal.aplikasi.inventory.domain.Barang; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; /** * * @Author Rizki Mufrizal <mufrizalrizki@gmail.com> * @Since Mar 20, 2016 * @Time 1:26:12 PM * @Encoding UTF-8 * @Project Aplikasi-Inventory * @Package com.rizki.mufrizal.aplikasi.inventory.abstractTableModel * */ public class BarangAbstractTableModel extends AbstractTableModel { private List<Barang> barangs = new ArrayList<>(); private static final String HEADER[] = { "No", "ID Barang", "Nama Barang", "Jenis Barang", "Tanggal Kadaluarsa", "Harga Satuan", "Jumlah Barang" }; public BarangAbstractTableModel(List<Barang> barangs) { this.barangs = barangs; } @Override public int getRowCount() { return barangs.size(); } @Override public int getColumnCount() { return HEADER.length; } @Override public String getColumnName(int column) { return HEADER[column]; } @Override public Object getValueAt(int rowIndex, int columnIndex) { Barang barang = barangs.get(rowIndex); switch (columnIndex) { case 0: return rowIndex + 1; case 1: return barang.getIdBarang(); case 2: return barang.getNamaBarang(); case 3: return barang.getJenisBarang(); case 4: return barang.getTanggalKadaluarsa(); case 5: return barang.getHargaSatuanBarang(); case 6: return barang.getJumlahBarang(); default: return null; } } }
package edu.kit.ipd.crowdcontrol.objectservice.database.operations; import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.AnswerRecord; import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.RatingRecord; import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.WorkerRecord; import org.jooq.DSLContext; import org.jooq.Result; import org.jooq.SelectConditionStep; import org.jooq.impl.DSL; import java.util.List; import java.util.Map; import java.util.Optional; import static edu.kit.ipd.crowdcontrol.objectservice.database.model.Tables.*; /** * responsible for all queries related to the Answer and Rating Table * * @author LeanderK * @version 1.0 */ public class AnswerRatingOperations extends AbstractOperations { public AnswerRatingOperations(DSLContext create) { super(create); } /** * Gets all ratings of a specified answer * * @param answerRecord answer, whose ratings are requested * @return list of ratings of a specified answer */ public Result<RatingRecord> getRatingsOfAnswer(AnswerRecord answerRecord) { return create.selectFrom(RATING) .where(RATING.ANSWER_R.eq(answerRecord.getIdAnswer())) .fetch(); } /** * Get all answers of the experiment specified by given ID * * @param expID specifying the experiment * @return list of all answers of a experiment */ public Result<AnswerRecord> getAnswersOfExperiment(int expID) { return create.selectFrom(ANSWER) .where(ANSWER.EXPERIMENT.eq(expID)) .fetch(); } /** * Fetches all answers of the specified experiment with a quality-value equal or above * the given threshold * * @param expID of the experiment * @param threshold specifying good answers. A good answer has at least a quality-value of given threshold * @return Map of workers and a set of matching answerRecords. */ public Map<WorkerRecord, List<AnswerRecord>> getGoodAnswersOfExperiment(int expID, int threshold) { return create.select(WORKER.fields()) .select(ANSWER.fields()) .from(WORKER) .rightJoin(ANSWER).onKey() .where(ANSWER.EXPERIMENT.eq(expID)) .and(ANSWER.QUALITY.greaterOrEqual(threshold)) .fetchGroups(WORKER, record -> record.into(ANSWER)); } /** * Fetches all ratings of the specified experiment with a quality-value equal or above * the given threshold * * @param expID of the experiment * @param threshold specifying good rating. A good rating has at least a quality-value of given threshold * @return Map of workers and a set of matching ratings. */ public Map<WorkerRecord, List<RatingRecord>> getGoodRatingsOfExperiment(int expID, int threshold) { return create.select(WORKER.fields()) .select(RATING.fields()) .from(WORKER) .rightJoin(RATING).onKey() .where(ANSWER.EXPERIMENT.eq(expID)) .and(ANSWER.QUALITY.greaterOrEqual(threshold)) .fetchGroups(WORKER, record -> record.into(RATING)); } /** * Returns all ratings of given answer, which have a quality rating above passed threshold * * @param answerRecord answer, whose good ratings (specified by given threshold) are returned * @param threshold of type int, which specifies good ratings * @return list of all ratings of given answer with a quality rating equal or greater than given threshold */ public Result<RatingRecord> getGoodRatingsOfAnswer(AnswerRecord answerRecord, int threshold) { return null; } /** * Sets quality ratings to a set of ratings * * @param map of ratings and matching qualities */ public void setQualityToRatings(Map<RatingRecord, Integer> map) { } /** * Sets quality rating to an answer * * @param answer whose quality is to be set * @param quality of the answer */ public void setQualityToAnswer(AnswerRecord answer, int quality) { } /** * inserts a new answer into the DB * * @param answerRecord the record to insert * @return the resulting record */ public AnswerRecord insertNewAnswer(AnswerRecord answerRecord) { answerRecord.setIdAnswer(null); return doIfRunning(answerRecord.getExperiment(), conf -> DSL.using(conf) .insertInto(ANSWER) .set(answerRecord) .returning() .fetchOne() ); } /** * Sets the quality-assured-bit for the given answerRecord * This indicates, that the answers quality is unlikely to change * * @param answerRecord whose quality-assured-bit is set */ public void setAnswerQualityAssured(AnswerRecord answerRecord) { //TODO } /** * inserts a new rating into the DB * * @param ratingRecord the record to insert * @return the resulting record */ public RatingRecord insertNewRating(RatingRecord ratingRecord) { ratingRecord.setIdRating(null); return doIfRunning(ratingRecord.getExperiment(), conf -> DSL.using(conf) .insertInto(RATING) .set(ratingRecord) .returning() .fetchOne() ); } /** * gets the answer with the passed primary key * * @param answerID the primary key of the answer * @return the answerRecord or emtpy */ public Optional<AnswerRecord> getAnswer(int answerID) { return create.fetchOptional(ANSWER, ANSWER.ID_ANSWER.eq(answerID)); } /** * Returns a range of answers starting from {@code cursor}. * * @param cursor Pagination cursor * @param next {@code true} for next, {@code false} for previous * @param limit Number of records * @return List of answers */ public Range<AnswerRecord, Integer> getAnswersFrom(int expid, int cursor, boolean next, int limit) { SelectConditionStep<AnswerRecord> query = create.selectFrom(ANSWER) .where(ANSWER.EXPERIMENT.eq(expid)); return getNextRange(query, ANSWER.ID_ANSWER, ANSWER, cursor, next, limit); } /** * Get a Rating form a id * * @param id The id to search for * @return a RatingRecord if it exists in the db */ public Optional<RatingRecord> getRating(int id) { return create.fetchOptional(RATING, RATING.ID_RATING.eq(id)); } /** * Returns the list of ratings from a answer * * @param answerId the answer which was rated * @return A list of ratingRecords */ public List<RatingRecord> getRatings(int answerId) { return create.selectFrom(RATING) .where(RATING.ANSWER_R.eq(answerId)) .fetch(); } }
package org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.set; import java.util.HashMap; import java.util.Iterator; import java.util.concurrent.BlockingQueue; import org.buddycloud.channelserver.channel.Conf; import org.buddycloud.channelserver.db.DataStore; import org.buddycloud.channelserver.db.DataStoreException; import org.buddycloud.channelserver.db.jedis.NodeSubscriptionImpl; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.JabberPubsub; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.PubSubElementProcessor; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.PubSubSet; import org.buddycloud.channelserver.queue.statemachine.Subscribe; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.dom.DOMElement; import org.xmpp.packet.IQ; import org.xmpp.packet.IQ.Type; import org.xmpp.packet.JID; import org.xmpp.packet.Message; import org.xmpp.packet.Packet; import org.xmpp.packet.PacketError; import org.buddycloud.channelserver.pubsub.subscription.NodeSubscription; import org.buddycloud.channelserver.pubsub.subscription.Subscriptions; import org.buddycloud.channelserver.pubsub.affiliation.Affiliations; import org.buddycloud.channelserver.pubsub.event.Event; public class SubscribeSet implements PubSubElementProcessor { private final BlockingQueue<Packet> outQueue; private final DataStore dataStore; private IQ request; private String node; public SubscribeSet(BlockingQueue<Packet> outQueue, DataStore dataStore) { this.outQueue = outQueue; this.dataStore = dataStore; } @Override public void process(Element elm, JID actorJID, IQ request, Element rsm) throws Exception { node = elm.attributeValue("node"); request = reqIQ; if ((node == null) || (true == node.equals(""))) { missingNodeName(); return; } JID subscribingJid = request.getFrom(); boolean isLocalNode = dataStore.isLocalNode(node); boolean isLocalSubscriber = false; if (actorJID != null) { subscribingJid = actorJID; } else { isLocalSubscriber = dataStore.isLocalUser(subscribingJid .toBareJID()); // Check that user is registered. if (!isLocalSubscriber) { failAuthRequired(); return; } } // 6.1.3.1 JIDs Do Not Match // Covers where we have juliet@shakespeare.lit/the-balcony String[] jidParts = elm.attributeValue("jid").split("/"); String jid = jidParts[0]; if (!subscribingJid.toBareJID().equals(jid)) { IQ reply = IQ.createResultIQ(request); reply.setType(Type.error); Element badRequest = new DOMElement("bad-request", new org.dom4j.Namespace("", JabberPubsub.NS_XMPP_STANZAS)); Element nodeIdRequired = new DOMElement("invalid-jid", new org.dom4j.Namespace("", JabberPubsub.NS_PUBSUB_ERROR)); Element error = new DOMElement("error"); error.addAttribute("type", "wait"); error.add(badRequest); error.add(nodeIdRequired); reply.setChildElement(error); outQueue.put(reply); return; } if (!isLocalNode) { if (isLocalSubscriber) { // Start process to subscribe to external node. Subscribe sub = Subscribe.buildSubscribeStatemachine(node, request, dataStore); outQueue.put(sub.nextStep()); return; } // Foreign client is trying to subscribe on a node that does not // exists. /* * 6.1.3.12 Node Does Not Exist * * <iq type='error' from='pubsub.shakespeare.lit' * to='francisco@denmark.lit/barracks' id='sub1'> <error * type='cancel'> <item-not-found * xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/> </error> </iq> */ IQ reply = IQ.createResultIQ(request); reply.setType(Type.error); PacketError pe = new PacketError( PacketError.Condition.item_not_found, PacketError.Type.cancel); reply.setError(pe); outQueue.put(reply); return; } // If node is whitelist // 6.1.3.4 Not on Whitelist // Subscribe to a node. NodeSubscriptionImpl nodeSubscription = dataStore .getUserSubscriptionOfNode(subscribingJid.toBareJID(), node); String possibleExistingAffiliation = nodeSubscription.getAffiliation(); String possibleExistingSusbcription = nodeSubscription .getSubscription(); if (Affiliations.outcast.toString().equals(possibleExistingAffiliation)) { /* * 6.1.3.8 Blocked <iq type='error' from='pubsub.shakespeare.lit' * to='francisco@denmark.lit/barracks' id='sub1'> <error * type='auth'> <forbidden * xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/> </error> </iq> */ IQ reply = IQ.createResultIQ(request); reply.setType(Type.error); PacketError pe = new PacketError( org.xmpp.packet.PacketError.Condition.forbidden, org.xmpp.packet.PacketError.Type.auth); reply.setError(pe); outQueue.put(reply); return; } if (possibleExistingSusbcription != null) { tooManySubscriptions(); return; } // Finally subscribe to the node :-) HashMap<String, String> nodeConf = dataStore.getNodeConf(node); String defaultAffiliation = nodeConf.get(Conf.DEFUALT_AFFILIATION); // @todo This should be fixed later... String defaultSubscription = Subscriptions.subscribed.toString(); dataStore.subscribeUserToNode(subscribingJid.toBareJID(), node, defaultAffiliation, defaultSubscription, isLocalSubscriber ? null : request.getFrom().getDomain()); IQ reply = IQ.createResultIQ(request); Element pubsub = reply.setChildElement(PubSubSet.ELEMENT_NAME, JabberPubsub.NAMESPACE_URI); pubsub.addElement("subscription").addAttribute("node", node) .addAttribute("jid", subscribingJid.toBareJID()) .addAttribute("subscription", defaultSubscription); pubsub.addElement("affiliation").addAttribute("node", node) .addAttribute("jid", subscribingJid.toBareJID()) .addAttribute("affiliation", defaultAffiliation); outQueue.put(reply); Message msg = new Message(); msg.setTo(reply.getTo()); msg.setFrom(reply.getFrom()); msg.setType(Message.Type.headline); Element subscription = msg.addChildElement("event", JabberPubsub.NS_PUBSUB_EVENT).addElement("subscription"); subscription.addAttribute("node", node) .addAttribute("jid", subscribingJid.toBareJID()) .addAttribute("subscription", defaultSubscription); outQueue.put(msg); msg = new Message(); msg.setTo(reply.getTo()); msg.setFrom(reply.getFrom()); msg.setType(Message.Type.headline); Element affiliation = msg.addChildElement("event", JabberPubsub.NS_PUBSUB_EVENT).addElement("affiliation"); affiliation.addAttribute("node", node) .addAttribute("jid", subscribingJid.toBareJID()) .addAttribute("affiliation", defaultAffiliation); outQueue.put(msg); notifySubscribers(); } private void notifySubscribers() throws DataStoreException, InterruptedException { Iterator<? extends NodeSubscription> subscribers = dataStore.getNodeSubscribers(node); Document document = getDocumentHelper(); Element message = document.addElement("message"); Element event = message.addElement("event"); Element configuration = event.addElement("subscription"); configuration.addAttribute("node", node); event.addAttribute("xmlns", Event.NAMESPACE); message.addAttribute("id", request.getID()); message.addAttribute("from", request.getTo().toString()); message.addAttribute("subscriptions", "subscribed"); Message rootElement = new Message(message); while (true == subscribers.hasNext()) { String subscriber = subscribers.next().getBareJID(); message.addAttribute("to", subscriber); Message notification = rootElement.createCopy(); outQueue.put(notification); } } private void tooManySubscriptions() throws InterruptedException { IQ reply = IQ.createResultIQ(request); reply.setType(Type.error); Element badRequest = new DOMElement("policy-violation", new org.dom4j.Namespace("", JabberPubsub.NS_XMPP_STANZAS)); Element nodeIdRequired = new DOMElement("too-many-subscriptions", new org.dom4j.Namespace("", JabberPubsub.NS_PUBSUB_ERROR)); Element error = new DOMElement("error"); error.addAttribute("type", "wait"); error.add(badRequest); error.add(nodeIdRequired); reply.setChildElement(error); outQueue.put(reply); } private void failAuthRequired() throws InterruptedException { // If the packet did not have actor, and the sender is not a local user // subscription is not allowed. /* * <iq type='error' from='pubsub.shakespeare.lit' * to='hamlet@denmark.lit/elsinore' id='create1'> <error type='auth'> * <registration-required xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/> * </error> </iq> */ IQ reply = IQ.createResultIQ(request); reply.setType(Type.error); PacketError pe = new PacketError( org.xmpp.packet.PacketError.Condition.registration_required, org.xmpp.packet.PacketError.Type.auth); reply.setError(pe); outQueue.put(reply); } private void missingNodeName(IQ request) throws InterruptedException { IQ reply = IQ.createResultIQ(request); reply.setType(Type.error); Element badRequest = new DOMElement("bad-request", new org.dom4j.Namespace("", JabberPubsub.NS_XMPP_STANZAS)); Element nodeIdRequired = new DOMElement("nodeid-required", new org.dom4j.Namespace("", JabberPubsub.NS_PUBSUB_ERROR)); Element error = new DOMElement("error"); error.addAttribute("type", "modify"); error.add(badRequest); error.add(nodeIdRequired); reply.setChildElement(error); outQueue.put(reply); } @Override public boolean accept(Element elm) { return elm.getName().equals("subscribe"); } }
package pl.edu.agh.ztb.service.profilesandconfigurations; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import loggers.enums.SourceType; import loggers.impl.RestLogger; import project.dao.ProfilesAndConfigurationsDAOImpl; import project.dao.data.Configuration; import project.dao.data.Profile; import project.dao.interfaces.ProfilesAndConfigurationsDAO; /** * Profiles and configurations service * @author ukasz.Gruba */ @Path(value = "/profilesAndConfigurations") public class ProfilesAndConfigurationsService { /** * Logger */ public RestLogger logger = new RestLogger(); private static final String SERVICE_NAME_PREFIX = "Executed service: /profilesAndConfigurations/"; @GET @Path(value = "/selectProfileByName/{profileName}") @Produces(value = MediaType.APPLICATION_JSON) public Response selectProfileByName(@PathParam(value = "profileName") String profileName) { String serviceName = "selectProfileByName"; try { Profile profile = ProfilesAndConfigurationsDaoManager.getDao().getProfile(profileName); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null, profileName)); return Response.ok(profile).build(); } catch(Exception e) { logger.logFailure(SourceType.MANUAL, getLogMessage(serviceName, e, profileName)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } @GET @Path(value = "/selectProfileByID/{profileID}") @Produces(value = MediaType.APPLICATION_JSON) public Response selectProfileByID(@PathParam(value = "profileID") Long profileID) { String serviceName = "selectProfileByID"; try { Profile profile = ProfilesAndConfigurationsDaoManager.getDao().getProfile(profileID); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null, profileID)); return Response.ok(profile).build(); } catch(Exception e) { logger.logFailure(SourceType.MANUAL, getLogMessage(serviceName, e, profileID)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } @GET @Path(value = "/selectProfilesList") @Produces(value = MediaType.APPLICATION_JSON) public Response selectProfilesList() { String serviceName = "selectProfilesList"; try { List<Profile> profilesList = ProfilesAndConfigurationsDaoManager.getDao().getProfilesList(); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null)); return Response.ok(profilesList).build(); } catch(Exception e) { logger.logFailure(SourceType.MANUAL, getLogMessage(serviceName, e)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } @POST @Path(value = "/createProfile") @Consumes(MediaType.APPLICATION_JSON) @Produces(value = MediaType.APPLICATION_JSON) public Response addProfile(ProfileDto profile) { String serviceName = "createProfile"; try { ProfilesAndConfigurationsDaoManager.getDao().addProfile(profile.getProfileName(), profile.getNormName(), profile.getAmbient()); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null, profile)); return Response.ok("OK").build(); } catch(Exception e) { logger.logFailure(SourceType.MANUAL, getLogMessage(serviceName, e, profile)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } @POST @Path(value = "/updateProfile") @Consumes(MediaType.APPLICATION_JSON) @Produces(value = MediaType.APPLICATION_JSON) public Response updateProfile(ProfileDto profile) { String serviceName = "updateProfile"; try { ProfilesAndConfigurationsDaoManager.getDao().updateProfile(profile.getProfileName(), profile.getNormName(), profile.getAmbient()); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null, profile)); return Response.ok("OK").build(); } catch(Exception e) { logger.logFailure(SourceType.MANUAL, getLogMessage(serviceName, e, profile)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } @DELETE @Path(value = "/deleteProfile") @Consumes(MediaType.APPLICATION_JSON) @Produces(value = MediaType.APPLICATION_JSON) public Response deleteProfile(String profileName) { String serviceName = "deleteProfile"; try { ProfilesAndConfigurationsDaoManager.getDao().deleteProfile(profileName); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null, profileName)); return Response.ok("OK").build(); } catch(Exception e) { logger.logFailure(SourceType.MANUAL, getLogMessage(serviceName, e, profileName)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } @GET @Path(value = "/selectProfilesForSegment/{segmentID}") @Produces(value = MediaType.APPLICATION_JSON) public Response selectProfilesForSegment(@PathParam(value = "segmentID") Long segmentID) { String serviceName = "selectProfilesForSegment"; try { List<Profile> profiles = ProfilesAndConfigurationsDaoManager.getDao().getProfilesForSegment(segmentID); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null, segmentID)); return Response.ok(profiles).build(); } catch(Exception e) { logger.logFailure(SourceType.MANUAL, getLogMessage(serviceName, e, segmentID)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } @GET @Path(value = "/selectConfigurationForSegment/{segmentID}/{profileName}") @Produces(value = MediaType.APPLICATION_JSON) public Response selectConfigForSegment( @PathParam(value = "segmentID") Long segmentID, @PathParam(value = "profileName") String profileName) { String serviceName = "selectConfigurationForSegment"; try { Configuration configuration = ProfilesAndConfigurationsDaoManager.getDao().getConfigForSegment(segmentID, profileName); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null, segmentID, profileName)); return Response.ok(configuration).build(); } catch(Exception e) { logger.logFailure(SourceType.MANUAL, getLogMessage(serviceName, e, segmentID, profileName)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } @POST @Path(value = "/createConfigurationForSegment") @Consumes(value = MediaType.APPLICATION_JSON) @Produces(value = MediaType.APPLICATION_JSON) public Response addConfigForSegment(SegmentDto segment) { String serviceName = "createConfigurationForSegment"; try { ProfilesAndConfigurationsDaoManager.getDao().addConfigForSegment(segment.getSegmentId(), segment.getProfileName(), segment.getLamps()); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null, segment)); return Response.ok("OK").build(); } catch(Exception e) { logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, e, segment)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } @POST @Path(value = "/updateConfigurationForSegment") @Consumes(value = MediaType.APPLICATION_JSON) @Produces(value = MediaType.APPLICATION_JSON) public Response updateConfigForSegment(SegmentDto segment) { String serviceName = "updateConfigurationForSegment"; try { ProfilesAndConfigurationsDaoManager.getDao().updateConfigForSegment(segment.getSegmentId(), segment.getProfileName(), segment.getLamps()); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null, segment)); return Response.ok("OK").build(); } catch(Exception e) { logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, e, segment)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } @DELETE @Path(value = "/deleteConfigurationForSegment") @Consumes(MediaType.APPLICATION_JSON) @Produces(value = MediaType.APPLICATION_JSON) public Response deleteConfigForSegment(SegmentDto segment) { String serviceName = "deleteConfigurationForSegment"; try { ProfilesAndConfigurationsDaoManager.getDao().deleteConfigForSegment(segment.getSegmentId(), segment.getProfileName()); logger.logSuccess(SourceType.MANUAL, getLogMessage(serviceName, null, segment)); return Response.ok("OK").build(); } catch(Exception e) { logger.logFailure(SourceType.MANUAL, getLogMessage(serviceName, e, segment)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } /** * Creates log message * @param serviceName * @param e * @param params * @return */ private String getLogMessage(String serviceName, Exception e, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(SERVICE_NAME_PREFIX); if(params != null) { for(Object o : params) { sb.append("/"); sb.append(o.toString()); } } if(e != null) { sb.append(" Exception was thrown: "); sb.append(e.getMessage()); } return sb.toString(); } /** * inner DAO manager * @author ukasz.Gruba */ private static class ProfilesAndConfigurationsDaoManager { /** * DAO instance */ private static ProfilesAndConfigurationsDAO daoInstance; /** * Private constructor */ private ProfilesAndConfigurationsDaoManager() { } /** * Returns DAO instance * @return * @throws ClassNotFoundException */ public static ProfilesAndConfigurationsDAO getDao() throws ClassNotFoundException { if(daoInstance == null) { daoInstance = new ProfilesAndConfigurationsDAOImpl("ztb6profiles", "user1", "user1", "localhost", "5432"); } return daoInstance; } } }
package uk.ac.ebi.pride.utilities.data.controller.impl.Transformer; import lombok.extern.slf4j.Slf4j; import uk.ac.ebi.pride.utilities.data.core.*; import uk.ac.ebi.pride.utilities.data.utils.Constants; import uk.ac.ebi.pride.utilities.data.utils.MzIdentMLUtils; import uk.ac.ebi.pride.utilities.term.CvTermReference; import java.util.*; /** * This class is responsible for converting light modules (that are used for fast validation) into other model objects or vice versa * <p> * Other Model objects used: * 1. uk.ac.ebi.jmzidml.model.mzidml * 2. uk.ac.ebi.pride.utilities.data.core * 3. uk.ac.ebi.pride.archive.repo.assay */ @Slf4j public class LightModelsTransformer { // TODO: This method should be removed later. Instead if converting Light model object to jmzidml model objects, // I need to override the existing method to support light model objects public static uk.ac.ebi.jmzidml.model.mzidml.SpectraData transformSpectraDataToJmzidml(uk.ac.ebi.pride.utilities.data.lightModel.SpectraData spectraData) { try { uk.ac.ebi.jmzidml.model.mzidml.SpectraData spectraDataJmzidml = new uk.ac.ebi.jmzidml.model.mzidml.SpectraData(); uk.ac.ebi.jmzidml.model.mzidml.SpectrumIDFormat spectrumIDFormatJmzidml = new uk.ac.ebi.jmzidml.model.mzidml.SpectrumIDFormat(); uk.ac.ebi.jmzidml.model.mzidml.CvParam CVParamJmzidml = new uk.ac.ebi.jmzidml.model.mzidml.CvParam(); CVParamJmzidml.setAccession(spectraData.getSpectrumIDFormat().getCvParam().getAccession()); spectrumIDFormatJmzidml.setCvParam(CVParamJmzidml); spectraDataJmzidml.setSpectrumIDFormat(spectrumIDFormatJmzidml); spectraDataJmzidml.setLocation(spectraData.getLocation()); spectraDataJmzidml.setId(spectraData.getId()); return spectraDataJmzidml; } catch (Exception ex) { log.error("Error occurred while converting uk.ac.ebi.pride.utilities.data.lightModel.SpectraData " + "to uk.ac.ebi.jmzidml.model.mzidml.SpectraData"); } return null; } /** * This method converts the Software from uk.ac.ebi.pride.utilities.data.lightModel.AnalysisSoftware * to uk.ac.ebi.pride.utilities.data.core.Software object * * @param analysisSoftware uk.ac.ebi.pride.utilities.data.lightModel.AnalysisSoftware object * @return uk.ac.ebi.pride.utilities.data.core.Software object */ public static Software transformToSoftware(uk.ac.ebi.pride.utilities.data.lightModel.AnalysisSoftware analysisSoftware) { try { Comparable id = analysisSoftware.getId(); String name = analysisSoftware.getName(); Contact contact = null; String customization = analysisSoftware.getCustomizations(); String uri = analysisSoftware.getUri(); String version = analysisSoftware.getVersion(); return new Software(id, name, contact, customization, uri, version); } catch (Exception ex) { log.error("Error occurred while converting uk.ac.ebi.pride.utilities.data.lightModel.AnalysisSoftware " + "to uk.ac.ebi.pride.utilities.data.core.Software"); return null; } } /** * This method converts list of SourceFile from uk.ac.ebi.pride.utilities.data.lightModel.SourceFile * to uk.ac.ebi.pride.utilities.data.core.SourceFile objects * * @param sourceFilesLight List of uk.ac.ebi.pride.utilities.data.lightModel.SourceFile objects * @return List of uk.ac.ebi.pride.utilities.data.core.SourceFile objects */ public static List<SourceFile> transformToSourceFiles(List<uk.ac.ebi.pride.utilities.data.lightModel.SourceFile> sourceFilesLight) { List<SourceFile> sourceFiles = null; if (sourceFilesLight != null) { sourceFiles = new ArrayList<>(); for (uk.ac.ebi.pride.utilities.data.lightModel.SourceFile sourceFileLight : sourceFilesLight) { String id = sourceFileLight.getId(); String name = sourceFileLight.getName(); String location = sourceFileLight.getLocation(); uk.ac.ebi.pride.utilities.data.lightModel.CvParam fileFormat = (sourceFileLight.getFileFormat() != null) ? sourceFileLight.getFileFormat().getCvParam() : null; CvParam format = transformToCvParam(fileFormat); String formatDocumentation = sourceFileLight.getExternalFormatDocumentation(); List<CvParam> cvParams = transformToCvParam(sourceFileLight.getCvParam()); List<UserParam> userParams = transformToUserParam(sourceFileLight.getUserParam()); sourceFiles.add(new SourceFile(new ParamGroup(cvParams, userParams), id, name, location, format, formatDocumentation)); } } return sourceFiles; } /** * This method converts list of CvParams from uk.ac.ebi.pride.utilities.data.lightModel.CvParam * to uk.ac.ebi.pride.utilities.data.core.CvParam object * * @param cvParamsLight List of uk.ac.ebi.pride.utilities.data.lightModel.CvParam objects * @return List of uk.ac.ebi.pride.utilities.data.core.CvParam objects */ public static List<CvParam> transformToCvParam(List<uk.ac.ebi.pride.utilities.data.lightModel.CvParam> cvParamsLight) { List<CvParam> cvParams = new ArrayList<>(); if (cvParamsLight != null && cvParamsLight.size() != 0) { for (uk.ac.ebi.pride.utilities.data.lightModel.CvParam cvParamLight : cvParamsLight) { cvParams.add(transformToCvParam(cvParamLight)); } } return cvParams; } /** * This method converts uk.ac.ebi.pride.utilities.data.lightModel.CvParam object * to uk.ac.ebi.pride.utilities.data.core.CvParam object * * @param cvParamLight uk.ac.ebi.pride.utilities.data.lightModel.CvParam cvParamLight * @return uk.ac.ebi.pride.utilities.data.core.CvParam object */ public static CvParam transformToCvParam(uk.ac.ebi.pride.utilities.data.lightModel.CvParam cvParamLight) { CvParam newParam = null; if (cvParamLight != null) { String cvLookupID = null; String unitCVLookupID = null; uk.ac.ebi.pride.utilities.data.lightModel.Cv cv = cvParamLight.getUnitCv(); if (cv != null) { cvLookupID = cv.getId(); } newParam = new CvParam( cvParamLight.getAccession(), cvParamLight.getName(), cvLookupID, cvParamLight.getValue(), cvParamLight.getUnitAccession(), cvParamLight.getUnitName(), unitCVLookupID); //TODO: do we need this? } return newParam; } /** * This method converts list of UserParam from uk.ac.ebi.pride.utilities.data.lightModel.UserParam * to uk.ac.ebi.pride.utilities.data.core.UserParam object * * @param userParamsLight List of uk.ac.ebi.pride.utilities.data.lightModel.UserParam objects * @return List of uk.ac.ebi.pride.utilities.data.core.UserParam objects */ public static List<UserParam> transformToUserParam(List<uk.ac.ebi.pride.utilities.data.lightModel.UserParam> userParamsLight) { List<UserParam> userParams = null; if (userParamsLight != null) { userParams = new ArrayList<>(); for (uk.ac.ebi.pride.utilities.data.lightModel.UserParam userParam : userParamsLight) { userParams.add(transformToUserParam(userParam)); } } return userParams; } /** * This method converts uk.ac.ebi.pride.utilities.data.lightModel.UserParam object * to uk.ac.ebi.pride.utilities.data.core.UserParam object * * @param userParam uk.ac.ebi.pride.utilities.data.lightModel.UserParam object * @return uk.ac.ebi.pride.utilities.data.core.UserParam object */ public static UserParam transformToUserParam(uk.ac.ebi.pride.utilities.data.lightModel.UserParam userParam) { UserParam newParam = null; if (userParam != null) { String unitCVLookupID = null; uk.ac.ebi.pride.utilities.data.lightModel.Cv cv = userParam.getUnitCv(); if (cv != null) unitCVLookupID = cv.getId(); newParam = new UserParam(userParam.getName(), userParam.getType(), userParam.getValue(), userParam.getUnitAccession(), userParam.getUnitName(), unitCVLookupID); } return newParam; } /** * This method converts List of uk.ac.ebi.pride.utilities.data.lightModel.Person object * to List of uk.ac.ebi.pride.utilities.data.core.Person object * * @param personsLight list of uk.ac.ebi.pride.utilities.data.lightModel.Person object * @return list of uk.ac.ebi.pride.utilities.data.core.Person object */ public static List<Person> transformToPerson(List<uk.ac.ebi.pride.utilities.data.lightModel.Person> personsLight) { List<Person> persons = null; if (personsLight != null && personsLight.size() != 0) { persons = new ArrayList<>(); for (uk.ac.ebi.pride.utilities.data.lightModel.Person personLight : personsLight) { persons.add(transformToPerson(personLight)); } } return persons; } /** * This method converts uk.ac.ebi.pride.utilities.data.lightModel.Person object * to uk.ac.ebi.pride.utilities.data.core.Person object * * @param lightPerson uk.ac.ebi.pride.utilities.data.lightModel.Person object * @return uk.ac.ebi.pride.utilities.data.core.Person object */ public static Person transformToPerson(uk.ac.ebi.pride.utilities.data.lightModel.Person lightPerson) { if (lightPerson != null) { List<CvParam> cvParams = new ArrayList<>(); // TODO: Person -> Afflilication -> Organization can be null while parsing MIdentML. I need to investigate this List<Organization> affiliation = transformAffiliationToOrganization(lightPerson.getAffiliation()); CvTermReference contactTerm = CvTermReference.CONTACT_NAME; String firstName = (lightPerson.getFirstName() != null) ? lightPerson.getFirstName() : ""; String lastName = (lightPerson.getLastName() != null) ? lightPerson.getLastName() : ""; cvParams.add(new CvParam(contactTerm.getAccession(), contactTerm.getName(), contactTerm.getCvLabel(), firstName + " " + lastName, null, null, null)); CvTermReference contactOrg = CvTermReference.CONTACT_ORG; StringBuilder organizationStr = new StringBuilder(); // TODO: Change this - may be there is a performance hit with Streams if (affiliation != null && affiliation.size() > 0 && affiliation.stream().anyMatch(Objects::nonNull)) { for (Organization organization : affiliation) { organizationStr.append((organization.getName() != null) ? organization.getName() + " " : ""); } } if (organizationStr.length() != 0) cvParams.add(new CvParam(contactOrg.getAccession(), contactOrg.getName(), contactOrg.getCvLabel(), organizationStr.toString(), null, null, null)); ParamGroup paramGroup = new ParamGroup(transformToCvParam(lightPerson.getCvParam()), transformToUserParam(lightPerson.getUserParam())); paramGroup.addCvParams(cvParams); return new Person(paramGroup, lightPerson.getId(), lightPerson.getName(), lightPerson.getLastName(), lightPerson.getFirstName(), lightPerson.getMidInitials(), affiliation, null); } return null; } /** * This method converts List of uk.ac.ebi.pride.utilities.data.lightModel.Organization object * to List of uk.ac.ebi.pride.utilities.data.core.Organization object * * @param lightOrganizations list of uk.ac.ebi.pride.utilities.data.lightModel.Organization object * @return list of uk.ac.ebi.pride.utilities.data.core.Organization object */ public static List<Organization> transformToOrganization(List<uk.ac.ebi.pride.utilities.data.lightModel.Organization> lightOrganizations) { List<Organization> organizations = null; if (lightOrganizations != null && lightOrganizations.size() != 0) { organizations = new ArrayList<>(); for (uk.ac.ebi.pride.utilities.data.lightModel.Organization lightOrganization : lightOrganizations) { //Todo: I need to solve the problem with mail and the parent organization organizations.add(transformToOrganization(lightOrganization)); } } return organizations; } /** * This method converts uk.ac.ebi.pride.utilities.data.lightModel.Organization object * to uk.ac.ebi.pride.utilities.data.core.Organization object * * @param lightOrganization uk.ac.ebi.pride.utilities.data.lightModel.Organization object * @return uk.ac.ebi.pride.utilities.data.core.Organization object */ public static Organization transformToOrganization(uk.ac.ebi.pride.utilities.data.lightModel.Organization lightOrganization) { Organization organization = null; if (lightOrganization != null) { Organization parentOrganization = null; if (lightOrganization.getParent() != null) { parentOrganization = transformToOrganization(lightOrganization.getParent().getOrganization()); } organization = new Organization(new ParamGroup( transformToCvParam(lightOrganization.getCvParam()), transformToUserParam(lightOrganization.getUserParam())), lightOrganization.getId(), lightOrganization.getName(), parentOrganization, null); } return organization; } /** * This method converts List of uk.ac.ebi.pride.utilities.data.lightModel.Affiliation object * to List of uk.ac.ebi.pride.utilities.data.core.Affiliation object * * @param lightAffiliations list of uk.ac.ebi.pride.utilities.data.lightModel.Affiliation object * @return list of uk.ac.ebi.pride.utilities.data.core.Affiliation object */ public static List<Organization> transformAffiliationToOrganization(List<uk.ac.ebi.pride.utilities.data.lightModel.Affiliation> lightAffiliations) { List<Organization> organizations = null; if (lightAffiliations != null && lightAffiliations.size() != 0) { organizations = new ArrayList<>(); for (uk.ac.ebi.pride.utilities.data.lightModel.Affiliation lightAffiliation : lightAffiliations) { uk.ac.ebi.pride.utilities.data.lightModel.Organization lightOrganization = lightAffiliation.getOrganization(); organizations.add(transformToOrganization(lightOrganization)); } } return organizations; } /** * This method converts uk.ac.ebi.pride.utilities.data.lightModel.Provider object * to uk.ac.ebi.pride.utilities.data.core.Provider object * * @param lightProvider uk.ac.ebi.pride.utilities.data.lightModel.Provider object * @return uk.ac.ebi.pride.utilities.data.core.Provider object */ public static Provider transformToProvider(uk.ac.ebi.pride.utilities.data.lightModel.Provider lightProvider) { Provider provider = null; Contact contact = null; CvParam role = null; if (lightProvider != null) { if (lightProvider.getContactRole() != null) { if (lightProvider.getContactRole().getOrganization() != null) { contact = transformToOrganization(lightProvider.getContactRole().getOrganization()); } else if (lightProvider.getContactRole().getPerson() != null) { contact = transformToPerson(lightProvider.getContactRole().getPerson()); } role = transformToCvParam(lightProvider.getContactRole().getRole().getCvParam()); } Software software = transformToSoftware(lightProvider.getSoftware()); provider = new Provider(lightProvider.getId(), lightProvider.getName(), software, contact, role); } return provider; } /** * This method converts List of uk.ac.ebi.pride.utilities.data.lightModel.BibliographicReference object * to List of uk.ac.ebi.pride.utilities.data.core.BibliographicReference object * * @param iterator list of uk.ac.ebi.pride.utilities.data.lightModel.BibliographicReference object * @return list of uk.ac.ebi.pride.utilities.data.core.BibliographicReference object */ public static List<Reference> transformToReference(Iterator<uk.ac.ebi.pride.utilities.data.lightModel.BibliographicReference> iterator) { List<Reference> references = new ArrayList<>(); while (iterator.hasNext()) { uk.ac.ebi.pride.utilities.data.lightModel.BibliographicReference ref = iterator.next(); // RefLine Trying to use the same approach of pride converter String refLine = ((ref.getAuthors() != null) ? ref.getAuthors() + ". " : "") + ((ref.getYear() != null) ? "(" + ref.getYear().toString() + "). " : "") + ((ref.getTitle() != null) ? ref.getTitle() + " " : "") + ((ref.getPublication() != null) ? ref.getPublication() + " " : "") + ((ref.getVolume() != null) ? ref.getVolume() + "" : "") + ((ref.getIssue() != null) ? "(" + ref.getIssue() + ")" : "") + ((ref.getPages() != null) ? ":" + ref.getPages() + "." : ""); // create the ref //Todo: Set the References ParamGroup for references String year = (ref.getYear() == null) ? null : ref.getYear().toString(); Reference reference = new Reference(ref.getId(), ref.getName(), ref.getDoi(), ref.getTitle(), ref.getPages(), ref.getIssue(), ref.getVolume(), year, ref.getEditor(), ref.getPublisher(), ref.getPublication(), ref.getAuthors(), refLine); references.add(reference); } return references; } /** * This method converts uk.ac.ebi.pride.utilities.data.lightModel.SpectraData object * to uk.ac.ebi.pride.utilities.data.core.SpectraData object * * @param lightSpectraData uk.ac.ebi.pride.utilities.data.lightModel.SpectraData object * @param mgfTitle Boolean value - If the Spectra refer by title instead of referred by the index * @return uk.ac.ebi.pride.utilities.data.core.SpectraData object */ public static SpectraData transformToSpectraData(uk.ac.ebi.pride.utilities.data.lightModel.SpectraData lightSpectraData, boolean mgfTitle) { SpectraData spectraData = null; if (lightSpectraData != null) { if (!mgfTitle) { CvParam fileFormat = (lightSpectraData.getFileFormat() == null) ? null : transformToCvParam(lightSpectraData.getFileFormat().getCvParam()); CvParam spectrumId = (lightSpectraData.getSpectrumIDFormat().getCvParam() == null) ? null : transformToCvParam(lightSpectraData.getSpectrumIDFormat().getCvParam()); spectraData = new SpectraData(lightSpectraData.getId(), lightSpectraData.getName(), lightSpectraData.getLocation(), fileFormat, lightSpectraData.getExternalFormatDocumentation(), spectrumId); } else { CvParam fileFormat = (lightSpectraData.getFileFormat() == null) ? null : MzIdentMLUtils.getFileFormatMGFTitle(); CvParam spectrumId = (lightSpectraData.getSpectrumIDFormat().getCvParam() == null) ? null : MzIdentMLUtils.getSpectrumIdFormatMGFTitle(); String location = (lightSpectraData.getLocation() != null) ? lightSpectraData.getLocation().replaceAll("(?i)" + Constants.WIFF_EXT, Constants.MGF_EXT) : null; String name = (lightSpectraData.getName() != null) ? lightSpectraData.getName().replaceAll("(?i)" + Constants.WIFF_EXT, Constants.MGF_EXT) : null; spectraData = new SpectraData(lightSpectraData.getId(), name, location, fileFormat, lightSpectraData.getExternalFormatDocumentation(), spectrumId); } } return spectraData; } /** * This method converts uk.ac.ebi.pride.utilities.data.lightModel.SpectraData object * to uk.ac.ebi.pride.utilities.data.core.SpectraData object * * @param lightSpectraDataList list of uk.ac.ebi.pride.utilities.data.lightModel.SpectraData object * @param usedTitle Boolean value - If the Spectra refer by title instead of referred by the index * @return uk.ac.ebi.pride.utilities.data.core.SpectraData object */ public static List<SpectraData> transformToSpectraData(List<uk.ac.ebi.pride.utilities.data.lightModel.SpectraData> lightSpectraDataList, List<Comparable> usedTitle) { List<SpectraData> spectraDatas = null; if (lightSpectraDataList != null && lightSpectraDataList.size() != 0) { spectraDatas = new ArrayList<>(); for (uk.ac.ebi.pride.utilities.data.lightModel.SpectraData lightSpectraData : lightSpectraDataList) { spectraDatas.add(transformToSpectraData(lightSpectraData, usedTitle.contains(lightSpectraData.getId()))); } } return spectraDatas; } /** * This method converts Date to CVParameter * * @param creationDate Date * @return uk.ac.ebi.pride.utilities.data.core.CvParam object */ public static CvParam transformDateToCvParam(Date creationDate) { CvTermReference cvTerm = CvTermReference.EXPERIMENT_GLOBAL_CREATIONDATE; return new CvParam(cvTerm.getAccession(), cvTerm.getName(), cvTerm.getCvLabel(), creationDate.toString(), null, null, null); } /** * This method converts List of uk.ac.ebi.pride.utilities.data.lightModel.SearchDatabase object * to List of uk.ac.ebi.pride.utilities.data.core.SearchDatabase object * * @param lightSearchDatabases list of uk.ac.ebi.pride.utilities.data.lightModel.SearchDatabase object * @return list of uk.ac.ebi.pride.utilities.data.core.SearchDatabase object */ public static List<SearchDataBase> transformToSearchDataBase(List<uk.ac.ebi.pride.utilities.data.lightModel.SearchDatabase> lightSearchDatabases) { List<SearchDataBase> searchDataBases = null; if (lightSearchDatabases != null) { searchDataBases = new ArrayList<>(); for (uk.ac.ebi.pride.utilities.data.lightModel.SearchDatabase lightSearchDatabase : lightSearchDatabases) { searchDataBases.add(transformToSeachDatabase(lightSearchDatabase)); } } return searchDataBases; } /** * This method converts uk.ac.ebi.pride.utilities.data.lightModel.SearchDatabase object * to uk.ac.ebi.pride.utilities.data.core.SearchDatabase object * * @param lightDatabase uk.ac.ebi.pride.utilities.data.lightModel.SearchDatabase object * @return uk.ac.ebi.pride.utilities.data.core.SearchDatabase object */ public static SearchDataBase transformToSeachDatabase(uk.ac.ebi.pride.utilities.data.lightModel.SearchDatabase lightDatabase) { String name = (lightDatabase != null) ? lightDatabase.getName() : null; CvParam fileFormat = ((lightDatabase != null ? lightDatabase.getFileFormat() : null) == null) ? null : transformToCvParam(lightDatabase.getFileFormat().getCvParam()); String releaseDate = (lightDatabase.getReleaseDate() == null) ? null : lightDatabase.getReleaseDate().toString(); int dataBaseSeq = (lightDatabase.getNumDatabaseSequences() == null) ? -1 : lightDatabase.getNumDatabaseSequences().intValue(); int dataBaseRes = (lightDatabase.getNumResidues() == null) ? -1 : lightDatabase.getNumResidues().intValue(); ParamGroup nameOfDatabase = null; if (lightDatabase.getDatabaseName() != null) { nameOfDatabase = new ParamGroup(transformToCvParam(lightDatabase.getDatabaseName().getCvParam()), transformToUserParam(lightDatabase.getDatabaseName().getUserParam())); } if (name == null) { if (!(nameOfDatabase != null && nameOfDatabase.getCvParams().isEmpty())) { name = getValueFromCvTerm(nameOfDatabase.getCvParams().get(0)); } if (name == null && !nameOfDatabase.getUserParams().isEmpty()) { name = getValueFromCvTerm(nameOfDatabase.getUserParams().get(0)); } if (name == null) { name = lightDatabase.getId(); } } return new SearchDataBase(lightDatabase.getId(), name, lightDatabase.getLocation(), fileFormat, lightDatabase.getExternalFormatDocumentation(), lightDatabase.getVersion(), releaseDate, dataBaseSeq, dataBaseRes, nameOfDatabase, transformToCvParam(lightDatabase.getCvParam())); } /** * To get the information of a cvterm or user param and put in an String we normally take firstly * the value of the Parameter and if is not provided we take the name. This function is important when * information like the name of the object is not provide and the writers use only CvTerms. * * @param cvTerm The CVTerm * @return An String with the Value */ public static String getValueFromCvTerm(Parameter cvTerm) { String originalValue = null; if (cvTerm.getValue() != null && cvTerm.getValue().length() > 0) { originalValue = cvTerm.getValue(); } else if (cvTerm.getName() != null && cvTerm.getName().length() > 0) { originalValue = cvTerm.getName(); } return originalValue; } /** * Transform light Samples to Samples * * @param lightSamples light uk.ac.ebi.pride.utilities.data.lightModel.Sample Objects * @return List of uk.ac.ebi.pride.utilities.data.core.Samples objects */ public static List<Sample> transformToSample(List<uk.ac.ebi.pride.utilities.data.lightModel.Sample> lightSamples) { List<Sample> samples = null; if (lightSamples != null && lightSamples.size() != 0) { samples = new ArrayList<>(); for (uk.ac.ebi.pride.utilities.data.lightModel.Sample lightSample : lightSamples) { samples.add(transformToSample(lightSample)); } } return samples; } /** * This method converts List of uk.ac.ebi.pride.utilities.data.lightModel.SubSample object * to List of uk.ac.ebi.pride.utilities.data.core.SubSample object * * @param lightSamples list of uk.ac.ebi.pride.utilities.data.lightModel.SubSample object * @return list of uk.ac.ebi.pride.utilities.data.core.SubSample object */ public static List<Sample> transformSubSampleToSample(List<uk.ac.ebi.pride.utilities.data.lightModel.SubSample> lightSamples) { List<Sample> samples = null; if (lightSamples != null && lightSamples.size() != 0) { samples = new ArrayList<>(); for (uk.ac.ebi.pride.utilities.data.lightModel.SubSample lightSubSample : lightSamples) { samples.add(transformToSample(lightSubSample.getSample())); } } return samples; } /** * This method converts uk.ac.ebi.pride.utilities.data.lightModel.Sample object * to uk.ac.ebi.pride.utilities.data.core.Sample object * * @param lightSample uk.ac.ebi.pride.utilities.data.lightModel.Sample object * @return uk.ac.ebi.pride.utilities.data.core.Sample object */ public static Sample transformToSample(uk.ac.ebi.pride.utilities.data.lightModel.Sample lightSample) { Sample sample = null; if (lightSample != null) { Map<Contact, CvParam> role = transformToRoleList(lightSample.getContactRole()); List<Sample> subSamples = null; if ((lightSample.getSubSample() != null) && (!lightSample.getSubSample().isEmpty())) { subSamples = transformSubSampleToSample(lightSample.getSubSample()); } sample = new Sample(new ParamGroup(transformToCvParam(lightSample.getCvParam()), transformToUserParam(lightSample.getUserParam())), lightSample.getId(), lightSample.getName(), subSamples, role); } return sample; } /** * This method converts List of uk.ac.ebi.pride.utilities.data.lightModel.ContactRole object * to List of uk.ac.ebi.pride.utilities.data.core.ContactRole object * * @param contactRoles list of uk.ac.ebi.pride.utilities.data.lightModel.ContactRole object * @return list of uk.ac.ebi.pride.utilities.data.core.ContactRole object */ public static Map<Contact, CvParam> transformToRoleList(List<uk.ac.ebi.pride.utilities.data.lightModel.ContactRole> contactRoles) { Map<Contact, CvParam> contacts = null; if (contactRoles != null) { contacts = new HashMap<>(); for (uk.ac.ebi.pride.utilities.data.lightModel.ContactRole lightRole : contactRoles) { Contact contact = null; if (lightRole.getOrganization() != null) { contact = transformToOrganization(lightRole.getOrganization()); } else if (lightRole.getPerson() != null) { contact = transformToPerson(lightRole.getPerson()); } CvParam role = transformToCvParam(lightRole.getRole().getCvParam()); contacts.put(contact, role); } } return contacts; } }
package org.dannil.httpdownloader.test.integrationtest; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.dannil.httpdownloader.controller.DownloadsController; import org.dannil.httpdownloader.exception.UnqualifiedAccessException; import org.dannil.httpdownloader.model.Download; import org.dannil.httpdownloader.model.URL; import org.dannil.httpdownloader.model.User; import org.dannil.httpdownloader.service.IDownloadService; import org.dannil.httpdownloader.service.IRegisterService; import org.dannil.httpdownloader.test.utility.TestUtility; import org.dannil.httpdownloader.utility.URLUtility; import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; /** * Integration tests for downloads controller * * @author Daniel Nilsson (daniel.nilsson @ dannils.se) * @version 1.0.0 * @since 1.0.0 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/WEB-INF/configuration/framework/spring-context.xml") public class DownloadsControllerIntegrationTest { @Autowired private DownloadsController downloadsController; @Autowired private IDownloadService downloadService; @Autowired private IRegisterService registerService; @Test public final void startDownloadExistingOnFileSystem() throws InterruptedException, UnqualifiedAccessException { final Download download = new Download(TestUtility.getDownload()); final User user = new User(TestUtility.getUser()); final User registered = this.registerService.save(user); download.setUser(registered); final Download saved = this.downloadService.save(download); registered.addDownload(saved); final HttpSession session = mock(HttpSession.class); when(session.getAttribute("user")).thenReturn(registered); this.downloadsController.downloadsStartIdGET(session, registered.getDownloads().get(0).getId()); Thread.sleep(1000); final String secondPath = this.downloadsController.downloadsStartIdGET(session, registered.getDownloads().get(0).getId()); Assert.assertEquals(URLUtility.getUrlRedirect(URL.DOWNLOADS), secondPath); } @Test public final void addDownloadWithErrors() { final Download download = new Download(TestUtility.getDownload()); download.setTitle(null); download.setUrl(null); final HttpServletRequest request = mock(HttpServletRequest.class); final HttpSession session = mock(HttpSession.class); final BindingResult errors = new BeanPropertyBindingResult(download, "download"); final String path = this.downloadsController.downloadsAddPOST(request, session, download, errors); Assert.assertEquals(URLUtility.getUrlRedirect(URL.DOWNLOADS_ADD), path); } @Test public final void addDownloadStartDownloadingProcessAndValidateLandingPage() { final Download download = new Download(TestUtility.getDownload()); final User user = new User(TestUtility.getUser()); final User saved = this.registerService.save(user); final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getParameter("start")).thenReturn("start"); final HttpSession session = mock(HttpSession.class); when(session.getAttribute("user")).thenReturn(saved); final BindingResult errors = new BeanPropertyBindingResult(download, "download"); final String path = this.downloadsController.downloadsAddPOST(request, session, download, errors); Assert.assertEquals(URLUtility.getUrlRedirect(URL.DOWNLOADS), path); } @Test public final void addDownloadStartDownloadingProcess() { final Download download = new Download(TestUtility.getDownload()); final User user = new User(TestUtility.getUser()); final User saved = this.registerService.save(user); final DateTime startDate = download.getStartDate(); final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getParameter("start")).thenReturn("start"); final HttpSession session = mock(HttpSession.class); when(session.getAttribute("user")).thenReturn(saved); final BindingResult errors = new BeanPropertyBindingResult(download, "download"); this.downloadsController.downloadsAddPOST(request, session, download, errors); Assert.assertEquals(-1, startDate.compareTo(download.getStartDate())); } @Test public final void addDownloadDoNotStartDownloadingProcess() { final Download download = new Download(TestUtility.getDownload()); final User user = new User(TestUtility.getUser()); final User saved = this.registerService.save(user); final DateTime startDate = download.getStartDate(); final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getParameter("start")).thenReturn(null); final HttpSession session = mock(HttpSession.class); when(session.getAttribute("user")).thenReturn(saved); final BindingResult errors = new BeanPropertyBindingResult(download, "download"); this.downloadsController.downloadsAddPOST(request, session, download, errors); Assert.assertEquals(0, startDate.compareTo(download.getStartDate())); } @Test public final void getDownloadWithoutCorrespondingOnFileSystem() throws InterruptedException, IOException, UnqualifiedAccessException { final Download download = new Download(TestUtility.getDownload()); final User user = new User(TestUtility.getUser()); final User saved = this.registerService.save(user); saved.addDownload(download); final ServletOutputStream stream = mock(ServletOutputStream.class); final HttpServletResponse response = mock(HttpServletResponse.class); when(response.getOutputStream()).thenReturn(stream); final HttpSession session = mock(HttpSession.class); when(session.getAttribute("user")).thenReturn(saved); final String path = this.downloadsController.downloadsGetIdGET(response, session, saved.getDownloads().get(0).getId()); Assert.assertEquals(URLUtility.getUrlRedirect(URL.DOWNLOADS), path); } @Test public final void getDownloadByIdSuccess() throws InterruptedException, IOException, UnqualifiedAccessException { final Download download = new Download(TestUtility.getDownload()); final User user = new User(TestUtility.getUser()); final User saved = this.registerService.save(user); final Download savedDownload = this.downloadService.saveToDisk(download); saved.addDownload(savedDownload); Thread.sleep(1000); final ServletOutputStream stream = mock(ServletOutputStream.class); final HttpServletResponse response = mock(HttpServletResponse.class); when(response.getOutputStream()).thenReturn(stream); final HttpSession session = mock(HttpSession.class); when(session.getAttribute("user")).thenReturn(saved); final String path = this.downloadsController.downloadsGetIdGET(response, session, saved.getDownloads().get(0).getId()); // if the test goes well, we should recieve null back as the path, as // getting a download doesn't redirect us to any page. Assert.assertNull(path); } @Test public final void deleteDownloadByIdSuccess() throws InterruptedException { final Download download = new Download(TestUtility.getDownload()); final User user = new User(TestUtility.getUser()); final User saved = this.registerService.save(user); final Download savedDownload = this.downloadService.saveToDisk(download); Thread.sleep(1000); saved.addDownload(savedDownload); final HttpSession session = mock(HttpSession.class); when(session.getAttribute("user")).thenReturn(saved); final String path = this.downloadsController.downloadsDeleteIdGET(session, download.getId()); Assert.assertEquals(URLUtility.getUrlRedirect(URL.DOWNLOADS), path); } }
package com.jgeppert.jquery.progressbar; import com.jgeppert.jquery.selenium.JQueryIdleCondition; import com.jgeppert.jquery.selenium.JQueryNoAnimations; import com.jgeppert.jquery.selenium.WebDriverFactory; import com.jgeppert.jquery.junit.category.HtmlUnitCategory; import com.jgeppert.jquery.junit.category.PhantomJSCategory; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.WebDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; @RunWith(Parameterized.class) @Category({HtmlUnitCategory.class, PhantomJSCategory.class}) public class ProgressbarTagIT { @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { "http://localhost:8080/regular" }, { "http://localhost:8080/uncompressed" }, { "http://localhost:8080/loadatonce" }, { "http://localhost:8080/loadfromgoogle" } }); } private static final JQueryIdleCondition JQUERY_IDLE = new JQueryIdleCondition(); private static final JQueryNoAnimations JQUERY_NO_ANIMATIONS = new JQueryNoAnimations(); private String baseUrl; public ProgressbarTagIT(final String baseUrl) { this.baseUrl = baseUrl; } @Test public void testLocal() throws InterruptedException { WebDriver driver = WebDriverFactory.getWebDriver(); WebDriverWait wait = new WebDriverWait(driver, 30); driver.get(baseUrl + "/progressbar/local.action"); WebElement progressbar = driver.findElement(By.id("myProgressbar")); WebElement progressbarValueDiv = progressbar.findElement(By.className("ui-progressbar-value")); Assert.assertEquals("width: 42%;", progressbarValueDiv.getAttribute("style").trim()); } @Test public void testLocalEvents() throws InterruptedException { WebDriver driver = WebDriverFactory.getWebDriver(); WebDriverWait wait = new WebDriverWait(driver, 30); driver.get(baseUrl + "/progressbar/local-events.action"); WebElement progressbar = driver.findElement(By.id("myProgressbar")); WebElement progressbarValueDiv = progressbar.findElement(By.className("ui-progressbar-value")); WebElement button = driver.findElement(By.id("myButton")); Assert.assertEquals("width: 42%;", progressbarValueDiv.getAttribute("style").trim()); button.click(); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); Assert.assertEquals("value changed to : 84", alert.getText()); alert.accept(); Assert.assertEquals("width: 84%;", progressbarValueDiv.getAttribute("style")); } }
package com.torodb.torod.db.backends.executor; import com.google.common.base.Supplier; import com.google.common.util.concurrent.ListenableFuture; import com.torodb.torod.core.ValueRow; import com.torodb.torod.core.WriteFailMode; import com.torodb.torod.core.annotations.DatabaseName; import com.torodb.torod.core.connection.DeleteResponse; import com.torodb.torod.core.connection.InsertResponse; import com.torodb.torod.core.connection.TransactionMetainfo; import com.torodb.torod.core.dbWrapper.DbConnection; import com.torodb.torod.core.dbWrapper.DbWrapper; import com.torodb.torod.core.dbWrapper.exceptions.ImplementationDbException; import com.torodb.torod.core.exceptions.ToroImplementationException; import com.torodb.torod.core.executor.SessionTransaction; import com.torodb.torod.core.executor.ToroTaskExecutionException; import com.torodb.torod.core.language.operations.DeleteOperation; import com.torodb.torod.core.language.querycriteria.QueryCriteria; import com.torodb.torod.core.pojos.Database; import com.torodb.torod.core.pojos.IndexedAttributes; import com.torodb.torod.core.pojos.NamedToroIndex; import com.torodb.torod.core.subdocument.SplitDocument; import com.torodb.torod.core.subdocument.values.Value; import com.torodb.torod.db.backends.executor.jobs.*; import com.torodb.torod.db.backends.executor.report.ReportFactory; import com.torodb.torod.db.executor.jobs.CreatePathViewsCallable; import com.torodb.torod.db.executor.jobs.DropPathViewsCallable; import com.torodb.torod.db.executor.jobs.SqlSelectCallable; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultSessionTransaction implements SessionTransaction { private final DefaultSessionExecutor executor; private final AtomicBoolean aborted; private boolean closed; private final DbConnection dbConnection; private final ReportFactory reportFactory; private final MyAborter aborter; private final String databaseName; private final TransactionMetainfo metainfo; private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSessionTransaction.class); DefaultSessionTransaction( DefaultSessionExecutor executor, DbConnection dbConnection, ReportFactory reportFactory, @DatabaseName String databaseName, TransactionMetainfo metainfo) { this.aborted = new AtomicBoolean(false); this.dbConnection = dbConnection; this.executor = executor; this.reportFactory = reportFactory; this.aborter = new MyAborter(); this.databaseName = databaseName; this.metainfo = metainfo; closed = false; } @Override public ListenableFuture<?> rollback() { return submit( new RollbackCallable( dbConnection, aborter, reportFactory.createRollbackReport() ) ); } @Override public ListenableFuture<?> commit() { return submit( new CommitCallable( dbConnection, aborter, reportFactory.createCommitReport() ) ); } @Override public void close() { if (!closed) { submit( new CloseConnectionCallable( dbConnection, aborter, reportFactory.createCloseConnectionReport() ) ); closed = true; } } @Override public boolean isClosed() { return closed; } @Override public ListenableFuture<InsertResponse> insertSplitDocuments( String collection, Collection<SplitDocument> documents, WriteFailMode mode) throws ToroTaskExecutionException { return submit( new InsertCallable( dbConnection, aborter, reportFactory.createInsertReport(), collection, documents, mode )); } @Override public ListenableFuture<DeleteResponse> delete( String collection, List<? extends DeleteOperation> deletes, WriteFailMode mode) { return submit( new DeleteCallable( dbConnection, aborter, reportFactory.createDeleteReport(), collection, deletes, mode ) ); } @Override public ListenableFuture<NamedToroIndex> createIndex( String collectionName, String indexName, IndexedAttributes attributes, boolean unique, boolean blocking) { return submit( new CreateIndexCallable( dbConnection, aborter, reportFactory.createIndexReport(), collectionName, indexName, attributes, unique, blocking ) ); } @Override public ListenableFuture<Boolean> dropIndex(String collection, String indexName) { return submit( new DropIndexCallable( dbConnection, aborter, reportFactory.createDropIndexReport(), collection, indexName ) ); } @Override public ListenableFuture<Collection<? extends NamedToroIndex>> getIndexes(String collection) { return submit( new GetIndexesCallable( dbConnection, aborter, reportFactory.createGetIndexReport(), collection) ); } @Override public ListenableFuture<List<? extends Database>> getDatabases() { return submit( new GetDatabasesCallable( dbConnection, aborter, reportFactory.createGetDatabasesReport(), databaseName ) ); } @Override public ListenableFuture<Integer> count(String collection, QueryCriteria query) { return submit( new CountCallable( dbConnection, aborter, reportFactory.createCountReport(), collection, query ) ); } @Override public ListenableFuture<Long> getIndexSize(String collection, String indexName) { return submit( new GetIndexSizeCallable( dbConnection, aborter, reportFactory.createGetIndexSizeReport(), collection, indexName ) ); } @Override public ListenableFuture<Long> getCollectionSize(String collection) { return submit( new GetCollectionSizeCallable( dbConnection, aborter, reportFactory.createGetCollectionSizeReport(), collection ) ); } @Override public ListenableFuture<Long> getDocumentsSize(String collection) { return submit( new GetDocumentsSize( dbConnection, aborter, reportFactory.createGetDocumentsSizeReport(), collection ) ); } @Override public ListenableFuture<Integer> createPathViews(String collection) { return submit( new CreatePathViewsCallable( dbConnection, aborter, reportFactory.createCreatePathViewsReport(), collection ) ); } @Override public ListenableFuture<Void> dropPathViews(String collection) { return submit( new DropPathViewsCallable( dbConnection, aborter, reportFactory.createDropPathViewsReport(), collection ) ); } @Override public ListenableFuture<Iterator<ValueRow<Value>>> sqlSelect(String sqlQuery) { return submit( new SqlSelectCallable( dbConnection, aborter, reportFactory.createSqlSelectReport(), sqlQuery ) ); } protected <R> ListenableFuture<R> submit(Job<R> callable) { return executor.submit(callable); } public static class DbConnectionProvider implements Supplier<DbConnection> { private final DbWrapper dbWrapper; private DbConnection connection; private DbConnection.Metainfo metadata; public DbConnectionProvider(DbWrapper dbWrapper, DbConnection.Metainfo metadata) { this.dbWrapper = dbWrapper; this.metadata = metadata; } @Override public DbConnection get() { if (connection == null) { try { connection = dbWrapper.consumeSessionDbConnection(metadata); } catch (ImplementationDbException ex) { throw new ToroImplementationException(ex); } assert connection != null; } return connection; } } private class MyAborter implements TransactionalJob.TransactionAborter { @Override public boolean isAborted() { return DefaultSessionTransaction.this.aborted.get(); } @Override public <R> void abort(Job<R> job) { LOGGER.debug("Transaction aborted"); DefaultSessionTransaction.this.aborted.set(true); } } }
package org.opendaylight.neutron.transcriber; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext; import org.opendaylight.neutron.spi.INeutronLoadBalancerPoolCRUD; import org.opendaylight.neutron.spi.NeutronLoadBalancerPool; import org.opendaylight.neutron.spi.NeutronLoadBalancerPoolMember; import org.opendaylight.neutron.spi.NeutronLoadBalancer_SessionPersistence; import org.opendaylight.neutron.spi.Neutron_ID; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev141002.PoolAttrs.Protocol; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev141002.lbaas.attributes.Pool; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev141002.lbaas.attributes.pool.Pools; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev141002.lbaas.attributes.pool.PoolsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.lbaasv2.rev141002.pool.attrs.SessionPersistenceBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150325.Neutron; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NeutronLoadBalancerPoolInterface extends AbstractNeutronInterface<Pools, NeutronLoadBalancerPool> implements INeutronLoadBalancerPoolCRUD { private static final Logger logger = LoggerFactory.getLogger(NeutronLoadBalancerPoolInterface.class); private ConcurrentMap<String, NeutronLoadBalancerPool> loadBalancerPoolDB = new ConcurrentHashMap<String, NeutronLoadBalancerPool>(); NeutronLoadBalancerPoolInterface(ProviderContext providerContext) { super(providerContext); } // this method uses reflection to update an object from it's delta. private boolean overwrite(Object target, Object delta) { Method[] methods = target.getClass().getMethods(); for (Method toMethod : methods) { if (toMethod.getDeclaringClass().equals(target.getClass()) && toMethod.getName().startsWith("set")) { String toName = toMethod.getName(); String fromName = toName.replace("set", "get"); try { Method fromMethod = delta.getClass().getMethod(fromName); Object value = fromMethod.invoke(delta, (Object[]) null); if (value != null) { toMethod.invoke(target, value); } } catch (Exception e) { e.printStackTrace(); return false; } } } return true; } @Override public boolean neutronLoadBalancerPoolExists(String uuid) { return loadBalancerPoolDB.containsKey(uuid); } @Override public NeutronLoadBalancerPool getNeutronLoadBalancerPool(String uuid) { if (!neutronLoadBalancerPoolExists(uuid)) { logger.debug("No LoadBalancerPool has Been Defined"); return null; } return loadBalancerPoolDB.get(uuid); } @Override public List<NeutronLoadBalancerPool> getAllNeutronLoadBalancerPools() { Set<NeutronLoadBalancerPool> allLoadBalancerPools = new HashSet<NeutronLoadBalancerPool>(); for (Entry<String, NeutronLoadBalancerPool> entry : loadBalancerPoolDB.entrySet()) { NeutronLoadBalancerPool loadBalancerPool = entry.getValue(); allLoadBalancerPools.add(loadBalancerPool); } logger.debug("Exiting getLoadBalancerPools, Found {} OpenStackLoadBalancerPool", allLoadBalancerPools.size()); List<NeutronLoadBalancerPool> ans = new ArrayList<NeutronLoadBalancerPool>(); ans.addAll(allLoadBalancerPools); return ans; } @Override public boolean addNeutronLoadBalancerPool(NeutronLoadBalancerPool input) { if (neutronLoadBalancerPoolExists(input.getLoadBalancerPoolID())) { return false; } loadBalancerPoolDB.putIfAbsent(input.getLoadBalancerPoolID(), input); return true; } @Override public boolean removeNeutronLoadBalancerPool(String uuid) { if (!neutronLoadBalancerPoolExists(uuid)) { return false; } loadBalancerPoolDB.remove(uuid); //TODO: add code to find INeutronLoadBalancerPoolAware services and call newtorkDeleted on them return true; } @Override public boolean updateNeutronLoadBalancerPool(String uuid, NeutronLoadBalancerPool delta) { if (!neutronLoadBalancerPoolExists(uuid)) { return false; } NeutronLoadBalancerPool target = loadBalancerPoolDB.get(uuid); return overwrite(target, delta); } @Override public boolean neutronLoadBalancerPoolInUse(String loadBalancerPoolUUID) { return !neutronLoadBalancerPoolExists(loadBalancerPoolUUID); } @Override protected Pools toMd(String uuid) { PoolsBuilder poolsBuilder = new PoolsBuilder(); poolsBuilder.setUuid(toUuid(uuid)); return poolsBuilder.build(); } @Override protected InstanceIdentifier<Pools> createInstanceIdentifier(Pools pools) { return InstanceIdentifier.create(Neutron.class) .child(Pool.class) .child(Pools.class, pools.getKey()); } @Override protected Pools toMd(NeutronLoadBalancerPool pools) { PoolsBuilder poolsBuilder = new PoolsBuilder(); poolsBuilder.setAdminStateUp(pools.getLoadBalancerPoolAdminIsStateIsUp()); if (pools.getLoadBalancerPoolDescription() != null) { poolsBuilder.setDescr(pools.getLoadBalancerPoolDescription()); } if (pools.getNeutronLoadBalancerPoolHealthMonitorID() != null) { List<Uuid> listHealthMonitor = new ArrayList<Uuid>(); listHealthMonitor.add(toUuid(pools.getNeutronLoadBalancerPoolHealthMonitorID())); poolsBuilder.setHealthmonitorIds(listHealthMonitor); } if (pools.getLoadBalancerPoolLbAlgorithm() != null) { poolsBuilder.setLbAlgorithm(pools.getLoadBalancerPoolLbAlgorithm()); } if (pools.getLoadBalancerPoolListeners() != null) { List<Uuid> listListener = new ArrayList<Uuid>(); for (Neutron_ID neutron_id : pools.getLoadBalancerPoolListeners()) { listListener.add(toUuid(neutron_id.getID())); } poolsBuilder.setListeners(listListener); } if (pools.getLoadBalancerPoolMembers() != null) { List<Uuid> listMember = new ArrayList<Uuid>(); for (NeutronLoadBalancerPoolMember laodBalancerPoolMember : pools.getLoadBalancerPoolMembers()) { listMember.add(toUuid(laodBalancerPoolMember.getPoolMemberID())); } poolsBuilder.setMembers(listMember); } if (pools.getLoadBalancerPoolName() != null) { poolsBuilder.setName(pools.getLoadBalancerPoolName()); } if (pools.getLoadBalancerPoolProtocol() != null) { poolsBuilder.setProtocol(Protocol.valueOf(pools.getLoadBalancerPoolProtocol())); } if (pools.getLoadBalancerPoolSessionPersistence() != null) { NeutronLoadBalancer_SessionPersistence sessionPersistence = pools.getLoadBalancerPoolSessionPersistence(); SessionPersistenceBuilder sessionPersistenceBuilder = new SessionPersistenceBuilder(); sessionPersistenceBuilder.setCookieName(sessionPersistence.getCookieName()); sessionPersistenceBuilder.setType(sessionPersistence.getType()); poolsBuilder.setSessionPersistence(sessionPersistenceBuilder.build()); } if (pools.getLoadBalancerPoolTenantID() != null) { poolsBuilder.setTenantId(toUuid(pools.getLoadBalancerPoolTenantID())); } if (pools.getLoadBalancerPoolID() != null) { poolsBuilder.setUuid(toUuid(pools.getLoadBalancerPoolID())); } else { logger.warn("Attempting to write neutron load balancer pool without UUID"); } return poolsBuilder.build(); } }
package org.mwc.debrief.track_shift.views; import java.awt.*; import java.util.*; import org.eclipse.core.runtime.Status; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.awt.SWT_AWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.*; import org.eclipse.ui.part.ViewPart; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.core.DataTypes.TrackData.*; import org.mwc.cmap.core.DataTypes.TrackData.TrackDataProvider.TrackShiftListener; import org.mwc.cmap.core.ui_support.PartMonitor; import Debrief.Tools.Tote.*; import Debrief.Wrappers.*; import MWC.Algorithms.Conversions; import MWC.GUI.*; import MWC.GUI.Layers.DataListener; import MWC.GUI.ptplot.jfreeChart.*; import MWC.GUI.ptplot.jfreeChart.Utils.*; import MWC.GenericData.*; import com.jrefinery.chart.*; import com.jrefinery.chart.tooltips.XYToolTipGenerator; import com.jrefinery.data.*; /** * This sample class demonstrates how to plug-in a new workbench view. The view * shows data obtained from the model. The sample creates a dummy model on the * fly, but a real implementation would connect to the model available either in * this or another plug-in (e.g. the workspace). The view is connected to the * model using a content provider. * <p> * The view uses a label provider to define how model objects should be * presented in the view. Each view can present the same model objects using * different labels and icons, if needed. Alternatively, a single label provider * can be shared between views in order to ensure that objects of the same type * are presented in the same way everywhere. * <p> */ public class StackedDotsView extends ViewPart { /** * helper application to help track creation/activation of new plots */ private PartMonitor _myPartMonitor; /** * the plot we're plotting to plot */ private XYPlot _myPlot; /** * legacy helper class */ private StackedDotHelper _myHelper; /** * our track-data provider */ protected TrackManager _theTrackDataListener; /** * our listener for tracks being shifted... */ protected TrackShiftListener _myShiftListener; /** * flag indicating whether we should override the y-axis to ensure that zero * is always in the centre */ private Action _centreYAxis; /** * flag indicating whether we should only show stacked dots for visible fixes */ private Action _onlyVisible; /** * our layers listener... */ protected DataListener _layersListener; /** * the set of layers we're currently listening to */ protected Layers _ourLayersSubject; protected TrackDataProvider _myTrackDataProvider; private Composite _holder; /** * The constructor. */ public StackedDotsView() { _myHelper = new StackedDotHelper(); // create the actions - the 'centre-y axis' action may get called before the // interface is shown makeActions(); } /** * This is a callback that will allow us to create the viewer and initialize * it. */ public void createPartControl(Composite parent) { // right, we need an SWT.EMBEDDED object to act as a holder _holder = new Composite(parent, SWT.EMBEDDED); // now we need a Swing object to put our chart into Frame plotControl = SWT_AWT.new_Frame(_holder); plotControl.setLayout(new BorderLayout()); // hey - now create the stacked plot! createStackedPlot(plotControl); // ok - listen out for changes in the view watchMyParts(); // put the actions in the UI contributeToActionBars(); } /** * view is closing, shut down, preserve life */ public void dispose() { System.out.println("disposing of stacked dots"); // get parent to ditch itself super.dispose(); // are we listening to any layers? if (_ourLayersSubject != null) _ourLayersSubject.removeDataReformattedListener(_layersListener); if(_theTrackDataListener != null) { _theTrackDataListener.removeTrackShiftListener(_myShiftListener); _theTrackDataListener.removeTrackShiftListener(_myShiftListener); } } private void makeActions() { _centreYAxis = new Action("Center Y axis on origin", Action.AS_CHECK_BOX) { public void run() { super.run(); // ok - redraw the plot we may have changed the axis centreing updateStackedDots(); } }; _centreYAxis.setText("Center Y Axis"); _centreYAxis.setChecked(true); _centreYAxis.setToolTipText("Keep Y origin in centre of axis"); _centreYAxis.setImageDescriptor(CorePlugin .getImageDescriptor("icons/follow_selection.gif")); _onlyVisible = new Action("Only draw dots for visible data points", Action.AS_CHECK_BOX) { public void run() { super.run(); // we need to get a fresh set of data pairs - the number may have // changed _myHelper.initialise(_theTrackDataListener, true); // and a new plot please updateStackedDots(); } }; _onlyVisible.setText("Only plot visible data"); _onlyVisible.setChecked(true); _onlyVisible.setToolTipText("Only draw dots for visible data points"); _onlyVisible.setImageDescriptor(CorePlugin .getImageDescriptor("icons/follow_selection.gif")); } private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); } private void fillLocalPullDown(IMenuManager manager) { manager.add(_centreYAxis); manager.add(_onlyVisible); } /** * Passing the focus request to the viewer's control. */ public void setFocus() { } /** * method to create a working plot (to contain our data) * * @return the chart, in it's own panel */ private void createStackedPlot(Frame plotControl) { // first create the x (time) axis final HorizontalDateAxis xAxis = new HorizontalDateAxis("time"); xAxis.setStandardTickUnits(DateAxisEditor.createStandardDateTickUnitsAsTickUnits()); // now the y axis, inverting it if applicable final ModifiedVerticalNumberAxis yAxis = new ModifiedVerticalNumberAxis( "Error (degs)"); // create the special stepper plot _myPlot = new XYPlot(null, xAxis, yAxis); // create the bit to create custom tooltips final XYToolTipGenerator tooltipGenerator = new DatedToolTipGenerator(); // and the bit to plot individual points in discrete colours _myPlot.setRenderer(new ColourStandardXYItemRenderer( StandardXYItemRenderer.SHAPES_AND_LINES, tooltipGenerator, null)); // put the plot into a chart final FormattedJFreeChart fj = new FormattedJFreeChart("Bearing error", null, _myPlot, false); fj.setShowSymbols(true); final ChartPanel plotHolder = new ChartPanel(fj); plotHolder.setMouseZoomable(true, true); plotHolder.setDisplayToolTips(false); // and insert into the panel plotControl.add(plotHolder, BorderLayout.CENTER); } /** * the track has been moved, update the dots */ private void updateStackedDots() { // get the current set of data to plot final TimeSeriesCollection newData = _myHelper .getUpdatedSeries(_theTrackDataListener); if (_centreYAxis.isChecked()) { // set the y axis to autocalculate _myPlot.getVerticalValueAxis().setAutoRange(true); } // store the new data (letting it autocalcualte) _myPlot.setDataset(newData); // we will only centre the y-axis if the user hasn't performed a zoom // operation if (_centreYAxis.isChecked()) { // do a quick fudge to make sure zero is in the centre final Range rng = _myPlot.getVerticalValueAxis().getRange(); final double maxVal = Math.max(Math.abs(rng.getLowerBound()), Math.abs(rng .getUpperBound())); _myPlot.getVerticalValueAxis().setRange(-maxVal, maxVal); } } /** * sort out what we're listening to... */ private void watchMyParts() { _myPartMonitor = new PartMonitor(getSite().getWorkbenchWindow().getPartService()); _myPartMonitor.addPartListener(TrackManager.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // cool, remember about it. _theTrackDataListener = (TrackManager) part; // ok - fire off the event for the new tracks _myHelper.initialise(_theTrackDataListener, true); } }); _myPartMonitor.addPartListener(TrackManager.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // ok, ditch it. _theTrackDataListener = null; _myHelper.reset(); } }); _myPartMonitor.addPartListener(TrackDataProvider.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // ok - let's start off with a clean plot _myPlot.setDataset(null); // cool, remember about it. TrackDataProvider dataP = (TrackDataProvider) part; // do we need to generate the shift listener? if (_myShiftListener == null) { _myShiftListener = new TrackShiftListener() { public void trackShifted(TrackWrapper subject) { updateStackedDots(); } }; } // is this the one we're already listening to? if (_myTrackDataProvider != dataP) { // nope, better stop listening then if(_myTrackDataProvider != null) _myTrackDataProvider.removeTrackShiftListener(_myShiftListener); } // ok, start listening to it anyway _myTrackDataProvider = dataP; _myTrackDataProvider.addTrackShiftListener(_myShiftListener); // hey - fire a dot update updateStackedDots(); } }); _myPartMonitor.addPartListener(TrackDataProvider.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { TrackDataProvider tdp = (TrackDataProvider) part; tdp.removeTrackShiftListener(_myShiftListener); if(tdp == _myTrackDataProvider) _myTrackDataProvider = null; // hey - lets clear our plot updateStackedDots(); } }); _myPartMonitor.addPartListener(Layers.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { Layers theLayers = (Layers) part; // do we need to create our listener if (_layersListener == null) { _layersListener = new Layers.DataListener() { public void dataModified(Layers theData, Layer changedLayer) { } public void dataExtended(Layers theData) { } public void dataReformatted(Layers theData, Layer changedLayer) { _myHelper.initialise(_theTrackDataListener, false); updateStackedDots(); } }; } // is this what we're listening to? if (_ourLayersSubject != theLayers) { // nope, stop listening to the old one (if there is one!) if (_ourLayersSubject != null) _ourLayersSubject.removeDataReformattedListener(_layersListener); } // now start listening to the new one. theLayers.addDataReformattedListener(_layersListener); } }); _myPartMonitor.addPartListener(Layers.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { Layers theLayers = (Layers) part; // is this what we're listening to? if (_ourLayersSubject == theLayers) { // yup, stop listening _ourLayersSubject.removeDataReformattedListener(_layersListener); } } }); // ok we're all ready now. just try and see if the current part is valid _myPartMonitor.fireActivePart(getSite().getWorkbenchWindow().getActivePage()); } // helper class to provide support to the stacked dots private final class StackedDotHelper { /** * the track being dragged */ private TrackWrapper _primaryTrack; /** * the secondary track we're monitoring */ private TrackWrapper _secondaryTrack; /** * the set of points to watch on the primary track */ private Vector _primaryDoublets; /** * the set of points to watch on the secondary track */ private Vector _secondaryDoublets; // CONSTRUCTOR /** * constructor - takes a set of layers, within which it identifies the track * wrappers * * @param theData * the set of data to provide stacked dots for * @param myTrack * the track being dragged */ StackedDotHelper() { } // MEMBER METHODS /** * ok, our track has been dragged, calculate the new series of offsets * * @param currentOffset * how far the current track has been dragged * @return the set of data items to plot */ public TimeSeriesCollection getUpdatedSeries(TrackManager tracks) { // ok, find the track wrappers if (_secondaryTrack == null) initialise(tracks, true); // did it work? if (_secondaryTrack == null) return null; // create the collection of series final TimeSeriesCollection theTimeSeries = new TimeSeriesCollection(); // produce a dataset for each track final BasicTimeSeries primarySeries = new BasicTimeSeries(_primaryTrack.getName(), FixedMillisecond.class); final BasicTimeSeries secondarySeries = new BasicTimeSeries(_secondaryTrack .getName(), FixedMillisecond.class); // ok, run through the points on the primary track Iterator iter = _primaryDoublets.iterator(); while (iter.hasNext()) { final Doublet thisD = (Doublet) iter.next(); final Color thisColor = thisD.getColor(); final double thisValue = thisD.calculateError(null, null); final HiResDate currentTime = thisD.getDTG(); // create a new, correctly coloured data item // HI-RES NOT DONE - should provide FixedMicrosecond structure final ColouredDataItem newItem = new ColouredDataItem(new FixedMillisecond( currentTime.getDate().getTime()), thisValue, thisColor, false, null); try { // and add it to the series primarySeries.add(newItem); } catch (SeriesException e) { // hack: we shouldn't be allowing this exception. Look at why we're // getting the same // time period being entered twice for this track. // Stop catching the error, load Dave W's holistic approach plot file, // and check the track/fix which is causing the problem. // e.printStackTrace(); //To change body of catch statement use File | // Settings | File Templates. } } // ok, run through the points on the primary track iter = _secondaryDoublets.iterator(); while (iter.hasNext()) { final Doublet thisD = (Doublet) iter.next(); final Color thisColor = thisD.getColor(); final double thisValue = thisD.calculateError(null, null); final HiResDate currentTime = thisD.getDTG(); // create a new, correctly coloured data item // HI-RES NOT DONE - should have FixedMicrosecond structure final ColouredDataItem newItem = new ColouredDataItem(new FixedMillisecond( currentTime.getDate().getTime()), thisValue, thisColor, false, null); try { // and add it to the series secondarySeries.add(newItem); } catch (SeriesException e) { CorePlugin.logError(Status.WARNING, "Multiple fixes at same DTG when producing stacked dots - prob ignored", null); } } // ok, add these new series theTimeSeries.addSeries(primarySeries); theTimeSeries.addSeries(secondarySeries); return theTimeSeries; } /** * initialise the data, check we've got sensor data & the correct number of * visible tracks * @param showError TODO */ private void initialise(TrackManager tracks, boolean showError) { // have we been created? if(_holder == null) return; // are we visible? if(_holder.isDisposed()) return; _secondaryTrack = null; _primaryTrack = null; // do we have some data? if (tracks == null) { // output error message showMessage("Sorry, a Debrief plot must be selected", showError); return; } // check we have a primary track WatchableList priTrk = tracks.getPrimaryTrack(); if (priTrk == null) { showMessage("Sorry, stacked dots will not open. A primary track must be placed on the Tote", showError); return; } else { if (!(priTrk instanceof TrackWrapper)) { showMessage("Sorry, stacked dots will not open. The primary track must be a vehicle track", showError); return; } else _primaryTrack = (TrackWrapper) priTrk; } // now the sec track WatchableList[] secs = tracks.getSecondaryTracks(); // any? if ((secs == null) || (secs.length == 0)) { showMessage("Sorry, stacked dots will not open. A secondary track must be present on the tote", showError); return; } // too many? if (secs.length > 1) { showMessage("Sorry, stacked dots will not open. Only one secondary track may be present on the tote", showError); return; } // correct sort? WatchableList secTrk = secs[0]; if (!(secTrk instanceof TrackWrapper)) { showMessage("Sorry, stacked dots will not open. The secondary track must be a vehicle track", showError); return; } else { _secondaryTrack = (TrackWrapper) secTrk; } // ok - we're now there // so, do we have primary and secondary tracks? if (_primaryTrack != null && _secondaryTrack != null) { // cool sort out the list of sensor locations for these tracks _primaryDoublets = getDoublets(_primaryTrack, _secondaryTrack); _secondaryDoublets = getDoublets(_secondaryTrack, _primaryTrack); } } private Vector getDoublets(final TrackWrapper sensorHost, final TrackWrapper targetTrack) { final Vector res = new Vector(0, 1); // ok, cycle through the sensor points on the host track final Enumeration iter = sensorHost.elements(); while (iter.hasMoreElements()) { final Plottable pw = (Plottable) iter.nextElement(); if (pw.getVisible()) { if (pw instanceof SensorWrapper) { final SensorWrapper sw = (SensorWrapper) pw; // right, work through the contacts in this sensor final Enumeration theContacts = sw.elements(); while (theContacts.hasMoreElements()) { final SensorContactWrapper scw = (SensorContactWrapper) theContacts .nextElement(); boolean thisVis = scw.getVisible(); boolean onlyVis = _onlyVisible.isChecked(); if (!onlyVis || (onlyVis && thisVis)) { final Watchable[] matches = targetTrack.getNearestTo(scw.getDTG()); FixWrapper targetFix = null; final int len = matches.length; if (len > 0) { for (int i = 0; i < len; i++) { final Watchable thisOne = matches[i]; if (thisOne instanceof FixWrapper) { targetFix = (FixWrapper) thisOne; continue; } } } if (targetFix != null) { // ok. found match. store it final Doublet thisDub = new Doublet(scw, targetFix.getLocation()); res.add(thisDub); } } // if this sensor contact is visible } // looping through these sensor contacts } // is this is a sensor wrapper } // if this item is visible } // looping through the items on this track return res; } /** * clear our data, all is finished */ public void reset() { if (_primaryDoublets != null) _primaryDoublets.removeAllElements(); _primaryDoublets = null; if (_secondaryDoublets != null) _secondaryDoublets.removeAllElements(); _secondaryDoublets = null; _primaryTrack = null; _secondaryTrack = null; } // class to store combination of sensor & target at same time stamp private final class Doublet { private final SensorContactWrapper _sensor; private final WorldLocation _targetLocation; // working variables to help us along. private final WorldLocation _workingSensorLocation = new WorldLocation(0.0, 0.0, 0.0); private final WorldLocation _workingTargetLocation = new WorldLocation(0.0, 0.0, 0.0); // constructor Doublet(final SensorContactWrapper sensor, final WorldLocation targetLocation) { _sensor = sensor; _targetLocation = targetLocation; } // member methods /** * get the DTG of this contact * * @return the DTG */ public HiResDate getDTG() { return _sensor.getDTG(); } /** * get the colour of this sensor fix */ public Color getColor() { return _sensor.getColor(); } /** * ok find what the current bearing error is for this track * * @param sensorOffset * if the sensor track has been dragged * @param targetOffset * if the target track has been dragged * @return */ public double calculateError(final WorldVector sensorOffset, final WorldVector targetOffset) { // copy our locations _workingSensorLocation.copy(_sensor.getOrigin(null)); _workingTargetLocation.copy(_targetLocation); // apply the offsets if (sensorOffset != null) _workingSensorLocation.addToMe(sensorOffset); if (targetOffset != null) _workingTargetLocation.addToMe(targetOffset); // calculate the current bearing final WorldVector error = _workingTargetLocation.subtract(_workingSensorLocation); double thisError = error.getBearing(); thisError = Conversions.Rads2Degs(thisError); // and calculate the bearing error final double measuredBearing = _sensor.getBearing(); thisError = measuredBearing - thisError; while (thisError > 180) thisError -= 360.0; while (thisError < -180) thisError += 360.0; return thisError; } } } private void showMessage(String message, boolean showError) { if(showError) MessageDialog.openInformation(getSite().getShell(), "Stacked dots", message); } }
package uk.ac.ebi.atlas.trader.loader; import org.springframework.beans.factory.annotation.Value; import uk.ac.ebi.atlas.experimentimport.ExperimentDAO; import uk.ac.ebi.atlas.trader.ConfigurationTrader; import uk.ac.ebi.atlas.trader.ExperimentDesignParser; import uk.ac.ebi.atlas.trader.SpeciesFactory; import uk.ac.ebi.atlas.utils.ArrayExpressClient; import javax.inject.Inject; import javax.inject.Named; @Named public class ProteomicsBaselineExperimentsCacheLoaderFactory { private ConfigurationTrader configurationTrader; private SpeciesFactory speciesFactory; private ProteomicsBaselineExperimentExpressionLevelFile expressionLevelFile; private ArrayExpressClient arrayExpressClient; private ExperimentDesignParser experimentDesignParser; private String extraInfoPathTemplate; @Inject public ProteomicsBaselineExperimentsCacheLoaderFactory(ConfigurationTrader configurationTrader, SpeciesFactory speciesFactory, ProteomicsBaselineExperimentExpressionLevelFile expressionLevelFile, ArrayExpressClient arrayExpressClient, ExperimentDesignParser experimentDesignParser, @Value("#{configuration['experiment.extra-info-image.path.template']}") String extraInfoPathTemplate) { this.configurationTrader = configurationTrader; this.speciesFactory = speciesFactory; this.expressionLevelFile = expressionLevelFile; this.arrayExpressClient = arrayExpressClient; this.experimentDesignParser = experimentDesignParser; this.extraInfoPathTemplate = extraInfoPathTemplate; } public ProteomicsBaselineExperimentsCacheLoader create(ExperimentDAO experimentDao) { ProteomicsBaselineExperimentsCacheLoader loader = new ProteomicsBaselineExperimentsCacheLoader( expressionLevelFile, configurationTrader, speciesFactory); loader.setExtraInfoPathTemplate(extraInfoPathTemplate); loader.setExperimentDAO(experimentDao); loader.setArrayExpressClient(arrayExpressClient); loader.setExperimentDesignParser(experimentDesignParser); return loader; } }
package org.xwiki.velocity.tools; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link EscapeTool}. * * @version $Id$ * @since 2.7RC1 */ public class EscapeToolTest { /** * The tested tool. */ private EscapeTool tool; /** * Initialize the tested tool. */ @Before public void setUp() { this.tool = new EscapeTool(); } @Test public void testEscapeSimpleXML() { String escapedText = this.tool.xml("a < a' && a' < a\" => a < a\""); Assert.assertFalse("Failed to escape <", escapedText.contains("<")); Assert.assertFalse("Failed to escape >", escapedText.contains(">")); Assert.assertFalse("Failed to escape '", escapedText.contains("'")); Assert.assertFalse("Failed to escape \"", escapedText.contains("\"")); Assert.assertFalse("Failed to escape &", escapedText.contains("&&")); } @Test public void testEscapeXMLApos() { Assert.assertFalse("' wrongly escaped to non-HTML &apos;", this.tool.xml("'").equals("&apos;")); } @Test public void testEscapeXMLWithNull() { Assert.assertNull("null should be null", this.tool.xml(null)); } @Test public void testEscapeXMLNonAscii() { Assert.assertTrue("Non-ASCII characters shouldn't be escaped", this.tool.xml("\u0123").equals("\u0123")); } @Test public void testEscapeJSON() { String escapedText = this.tool.json("\"'\\/\b\f\n\r\t\u1234 plain text"); Assert.assertTrue("Failed to escape [\"]", escapedText.contains("\\\"")); Assert.assertTrue("Wrongly escaped [']", escapedText.contains("'")); Assert.assertTrue("Failed to escape [\\]", escapedText.contains("\\\\")); Assert.assertTrue("Failed to escape [/]", escapedText.contains("\\/")); Assert.assertTrue("Failed to escape [\\b]", escapedText.contains("\\b")); Assert.assertTrue("Failed to escape [\\f]", escapedText.contains("\\f")); Assert.assertTrue("Failed to escape [\\n]", escapedText.contains("\\n")); Assert.assertTrue("Failed to escape [\\r]", escapedText.contains("\\r")); Assert.assertTrue("Failed to escape [\\t]", escapedText.contains("\\t")); Assert.assertTrue("Failed to escape [\\u1234]", escapedText.contains("\\u1234")); Assert.assertTrue("Wrongly escaped plain text", escapedText.contains(" plain text")); } @Test public void testEscapeJSONWithNullInput() { Assert.assertNull("Unexpected non-null output for null input", this.tool.json(null)); } @Test public void testEscapeJSONWithNonStringInput() { Assert.assertEquals("true", this.tool.json(true)); Assert.assertEquals("42", this.tool.json(42)); Assert.assertEquals(this.tool.toString(), this.tool.json(this.tool)); } @Test public void testQuotedPrintableWithSimpleText() { Assert.assertEquals("Hello World", this.tool.quotedPrintable("Hello World")); } @Test public void testQuotedPrintableWithSpecialChars() { Assert.assertEquals("a=3Db=0A", this.tool.quotedPrintable("a=b\n")); } @Test public void testQuotedPrintableWithNonAsciiChars() { Assert.assertEquals("=C4=A3", this.tool.quotedPrintable("\u0123")); } @Test public void testQuotedPrintableWithNull() { Assert.assertNull(this.tool.quotedPrintable(null)); } @Test public void testQWithSimpleText() { Assert.assertEquals("=?UTF-8?Q?Hello_World?=", this.tool.q("Hello World")); } @Test public void testQWithSpecialChars() { Assert.assertEquals("=?UTF-8?Q?a=3Db=3F=5F=0A?=", this.tool.q("a=b?_\n")); } @Test public void testQWithNonAsciiChars() { Assert.assertEquals("=?UTF-8?Q?=C4=A3?=", this.tool.q("\u0123")); } @Test public void testQWithNull() { Assert.assertNull(this.tool.q(null)); } @Test public void testBWithSimpleText() { Assert.assertEquals("=?UTF-8?B?SGVsbG8gV29ybGQ=?=", this.tool.b("Hello World")); } @Test public void testBWithSpecialChars() { Assert.assertEquals("=?UTF-8?B?YT1iPwo=?=", this.tool.b("a=b?\n")); } @Test public void testBWithNonAsciiChars() { Assert.assertEquals("=?UTF-8?B?xKM=?=", this.tool.b("\u0123")); } @Test public void testBWithNull() { Assert.assertNull(this.tool.b(null)); } @Test public void testURL() { HashMap<String, String> map = new HashMap<String, String>(); map.put("hello", "world"); map.put(null, "value"); map.put("B&B", "yes"); map.put("empty", null); Assert.assertEquals("hello=world&B%26B=yes&empty=", this.tool.url(map)); } @Test public void testURLWithDouble() { HashMap<String, Double> map = new LinkedHashMap<>(); map.put("A&A", 1.5); map.put("B&B", 1.2); Assert.assertEquals("A%26A=1.5&B%26B=1.2", this.tool.url(map)); } @Test public void testURLWithArray() { HashMap<String, String[]> map = new HashMap<>(); String[] array = {"M&M", null, "Astronomy&Astrophysics"}; map.put("couple", array); Assert.assertEquals("couple=M%26M&couple=&couple=Astronomy%26Astrophysics", this.tool.url(map)); } @Test public void testURLWithCollection() { HashMap<String, ArrayList<String>> map = new HashMap<>(); ArrayList<String> collection1 = new ArrayList<>(); collection1.add("test"); map.put("alice", collection1); ArrayList<String> collection2 = new ArrayList<>(); collection2.add(null); collection2.add("t&t"); collection2.add("R&D"); map.put("bob", collection2); Assert.assertEquals("bob=&bob=t%26t&bob=R%26D&alice=test", this.tool.url(map)); } @Test public void xwiki() { // Since the logic is pretty simple (prepend every character with an escape character), the below tests are // mostly for exemplification. Assert.assertEquals("~~", this.tool.xwiki("~")); Assert.assertEquals("~*~*~t~e~s~t~*~*", this.tool.xwiki("**test**")); // Note: Java escaped string "\\" == "\" (real string). Assert.assertEquals("~a~\\~\\~[~[~l~i~n~k~>~>~X~.~Y~]~]", this.tool.xwiki("a\\\\[[link>>X.Y]]")); Assert.assertEquals("~{~{~{~v~e~r~b~a~t~i~m~}~}~}", this.tool.xwiki("{{{verbatim}}}")); Assert.assertEquals("~{~{~m~a~c~r~o~ ~s~o~m~e~=~'~p~a~r~a~m~e~t~e~r~'~}~}~c~o~n~t~e~n~t~{~{~/~m~a~c~r~o~}~}", this.tool.xwiki("{{macro some='parameter'}}content{{/macro}}")); } @Test public void xwikiSpaces() { Assert.assertEquals("~a~ ~*~*~t~e~s~t~*~*", this.tool.xwiki("a **test**")); } @Test public void xwikiNewLine() { Assert.assertEquals("~a~\n~b", this.tool.xwiki("a\nb")); } @Test public void xwikiWithNullInput() { Assert.assertNull("Unexpected non-null output for null input", this.tool.xwiki(null)); } }
package com.example.madiskar.experiencesamplingapp; import android.app.AlarmManager; import android.app.ListFragment; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Process; import android.support.design.widget.FloatingActionButton; import android.test.suitebuilder.TestMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Calendar; public class StudyFragment extends ListFragment { private Handler mHandler = new Handler(); private Boolean from_menu; private ActiveStudyListAdapter asla; private TextView noStudiesTxt; private ProgressBar progress; private TextView progressText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); from_menu = args.getBoolean("fromNav"); MainActivity.justStarted = false; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_study, container, false); progress = (ProgressBar) view.findViewById(R.id.myStudiesProgressBar); final FloatingActionButton floatUpdate = (FloatingActionButton) view.findViewById(R.id.floatingUpdateButton); progressText = (TextView) view.findViewById(R.id.myStudiesProgressBarText); noStudiesTxt = (TextView) view.findViewById(R.id.no_studies); progress.setVisibility(View.VISIBLE); progressText.setVisibility(View.VISIBLE); floatUpdate.setVisibility(View.GONE); noStudiesTxt.setVisibility(View.GONE); new AsyncTask<Void, Void, ArrayList<Study>>() { @Override protected ArrayList<Study> doInBackground(Void... params) { DBHandler mydb = DBHandler.getInstance(getActivity()); return mydb.getAllStudies(); } @Override protected void onPostExecute(final ArrayList<Study> results) { if(from_menu) { mHandler.postDelayed(new Runnable() { @Override public void run() { ArrayList<Study> filtered = filterStudies(results); if(filtered.size() > 0) { progress.setVisibility(View.GONE); progressText.setVisibility(View.GONE); floatUpdate.setVisibility(View.VISIBLE); asla = new ActiveStudyListAdapter(getActivity(), filtered, StudyFragment.this); setListAdapter(asla); } else { progress.setVisibility(View.GONE); progressText.setVisibility(View.GONE); noStudies(); } } }, 230); //Time for nav driver to close, for nice animations } else { ArrayList<Study> filtered = filterStudies(results); if(filtered.size() > 0) { progress.setVisibility(View.GONE); progressText.setVisibility(View.GONE); floatUpdate.setVisibility(View.VISIBLE); asla = new ActiveStudyListAdapter(getActivity(), filtered, StudyFragment.this); setListAdapter(asla); } else { progress.setVisibility(View.GONE); progressText.setVisibility(View.GONE); noStudies(); } } } }.execute(); floatUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isNetworkAvailable()) { SharedPreferences pref = view.getContext().getApplicationContext().getSharedPreferences("com.example.madiskar.ExperienceSampler", Context.MODE_PRIVATE); final ProgressDialog progressDialog = new ProgressDialog(getActivity(), R.style.AppTheme_Dark_Dialog); progressDialog.setIndeterminate(true); progressDialog.setMessage(getString(R.string.update_studies)); progressDialog.setCanceledOnTouchOutside(false); progressDialog.show(); SyncStudyDataTask syncStudyDataTask = new SyncStudyDataTask(pref.getString("token", "none"), DBHandler.getInstance(view.getContext()), false, new StudyDataSyncResponse() { @Override public void processFinish(String output, ArrayList<Study> newStudies, ArrayList<Study> allStudies, ArrayList<Study> updatedStudies, ArrayList<Study> oldStudies, ArrayList<Study> cancelledStudies) { if (output.equals("invalid_token")) { Log.i("Study Sync", getString(R.string.auth_sync_fail)); //Toast.makeText(view.getContext(), view.getContext().getString(R.string.auth_sync_fail), Toast.LENGTH_LONG).show(); } else if (output.equals("nothing")) { Log.i("Study Sync", getString(R.string.fetch_sync_fail)); //Toast.makeText(view.getContext(), view.getContext().getString(R.string.fetch_sync_fail), Toast.LENGTH_LONG).show(); } else if(!output.equals("dberror")){ for (Study s : newStudies) { Log.i("StudyFragment", "Setting up alarms for " + newStudies.size() + " studies"); setUpNewStudyAlarms(s); } for (int i=0; i<updatedStudies.size(); i++) { Log.i("STUDIES MODIFIED", "notification data changed for " + updatedStudies.size() + " studies"); cancelStudy(oldStudies.get(i), false, false); setUpNewStudyAlarms(updatedStudies.get(i)); } for (Study s : cancelledStudies) { Log.i("STUDIES CANCELLED", "removed " + cancelledStudies.size() + " studies"); for(Study ks : allStudies) { if(ks.getId() == s.getId()) { allStudies.remove(ks); break; } } cancelStudy(s, true, true); } progressDialog.dismiss(); updateUI(allStudies); Log.i("Study sync:", getString(R.string.update_success)); } else { Log.i("FINISHED SYNC:", "study sync failed"); } } }); ExecutorSupplier.getInstance().forBackgroundTasks().execute(syncStudyDataTask); } else { Toast.makeText(view.getContext(), view.getContext().getString(R.string.no_internet), Toast.LENGTH_LONG).show(); } } }); return view; } public ArrayList<Study> filterStudies(ArrayList<Study> studies) { ArrayList<Study> studiesClone = new ArrayList<>(studies); for (Study study: studiesClone) { if (Calendar.getInstance().after(study.getEndDate())) { NotificationService.cancelNotification(getActivity().getApplicationContext(), (int) study.getId()); Intent intent = new Intent(getActivity().getApplicationContext(), QuestionnaireActivity.class); ResponseReceiver.cancelExistingAlarm(getActivity(), intent, Integer.valueOf((study.getId() + 1) + "00002"), false); PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), (int) study.getId(), new Intent(getActivity().getApplicationContext(), ResponseReceiver.class), 0); AlarmManager am = (AlarmManager) getActivity().getApplicationContext().getSystemService(Context.ALARM_SERVICE); am.cancel(pendingIntent); for (Event event: EventDialogFragment.activeEvents) { if (event.getStudyId() == study.getId()) { Intent stopIntent = new Intent(getActivity().getApplicationContext(), StopReceiver.class); stopIntent.putExtra("start", event.getStartTimeCalendar()); stopIntent.putExtra("notificationId", EventDialogFragment.uniqueValueMap.get((int) event.getId())); stopIntent.putExtra("studyId", event.getStudyId()); stopIntent.putExtra("controlNotificationId", EventDialogFragment.uniqueControlValueMap.get((int) event.getId())); stopIntent.putExtra("eventId", event.getId()); getActivity().getApplicationContext().sendBroadcast(stopIntent); } } DBHandler.getInstance(getActivity().getApplicationContext()).deleteStudyEntry(study.getId()); studiesClone.remove(study); } } return studiesClone; } public void cancelStudy(final Study study, final boolean cancelEvents, final boolean removeStudy) { mHandler.post(new Runnable() { @Override public void run() { Log.i("Deleting study", study.getName()); NotificationService.cancelNotification(getActivity().getApplicationContext(), (int) study.getId()); Intent intent = new Intent(getActivity().getApplicationContext(), QuestionnaireActivity.class); ResponseReceiver.cancelExistingAlarm(getActivity().getApplicationContext(), intent, Integer.valueOf((study.getId() + 1) + "00002"), false); PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), (int) study.getId(), new Intent(getActivity().getApplicationContext(), ResponseReceiver.class), 0); AlarmManager am = (AlarmManager) getActivity().getApplicationContext().getSystemService(Context.ALARM_SERVICE); am.cancel(pendingIntent); if(cancelEvents) { for (Event event : EventDialogFragment.activeEvents) { if (event.getStudyId() == study.getId()) { Intent stopIntent = new Intent(getActivity().getApplicationContext(), StopReceiver.class); stopIntent.putExtra("start", event.getStartTimeCalendar()); stopIntent.putExtra("notificationId", EventDialogFragment.uniqueValueMap.get((int) event.getId())); stopIntent.putExtra("studyId", event.getStudyId()); stopIntent.putExtra("controlNotificationId", EventDialogFragment.uniqueControlValueMap.get((int) event.getId())); stopIntent.putExtra("eventId", event.getId()); getActivity().getApplicationContext().sendBroadcast(stopIntent); } } } if(removeStudy) { DBHandler.getInstance(getActivity().getApplicationContext()).deleteStudyEntry(study.getId()); } } }); } private void setUpNewStudyAlarms(final Study s) { mHandler.post(new Runnable() { @Override public void run() { ResponseReceiver rR = new ResponseReceiver(s); rR.setupAlarm(getActivity().getApplicationContext(), true); } }); } private void updateUI(final ArrayList<Study> newList) { mHandler.post(new Runnable() { @Override public void run() { if(newList.size() == 0) noStudies(); if(newList.size() > 0) noStudiesTxt.setVisibility(View.GONE); asla = new ActiveStudyListAdapter(getActivity(), newList, StudyFragment.this); setListAdapter(asla); } }); } public void noStudies() { noStudiesTxt.setVisibility(View.VISIBLE); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public final class MainPanel extends JPanel { private MainPanel() { super(new GridLayout(1, 2)); add(makeTitledPanel("Default", new JScrollPane(makeList(true)))); add(makeTitledPanel("clearSelection", new JScrollPane(makeList(false)))); setPreferredSize(new Dimension(320, 240)); } private static JList<String> makeList(boolean def) { DefaultListModel<String> model = new DefaultListModel<>(); model.addElement("aaaaaaa"); model.addElement("bbbbbbbbbbbbb"); model.addElement("cccccccccc"); model.addElement("ddddddddd"); model.addElement("eeeeeeeeee"); if (def) { return new JList<>(model); } JList<String> list = new JList<String>(model) { private transient MouseInputListener listener; @Override public void updateUI() { removeMouseListener(listener); removeMouseMotionListener(listener); setForeground(null); setBackground(null); setSelectionForeground(null); setSelectionBackground(null); super.updateUI(); listener = new ClearSelectionListener(); addMouseListener(listener); addMouseMotionListener(listener); } }; // list.putClientProperty("List.isFileList", Boolean.TRUE); // list.setLayoutOrientation(JList.HORIZONTAL_WRAP); // list.setFixedCellWidth(64); // list.setFixedCellHeight(64); // list.setVisibleRowCount(0); return list; } private static Component makeTitledPanel(String title, Component c) { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder(title)); p.add(c); return p; } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class ClearSelectionListener extends MouseInputAdapter { private boolean startOutside; private static <E> void clearSelectionAndFocus(JList<E> list) { list.clearSelection(); list.getSelectionModel().setAnchorSelectionIndex(-1); list.getSelectionModel().setLeadSelectionIndex(-1); } private static <E> boolean contains(JList<E> list, Point pt) { for (int i = 0; i < list.getModel().getSize(); i++) { if (list.getCellBounds(i, i).contains(pt)) { return true; } } return false; } @Override public void mousePressed(MouseEvent e) { JList<?> list = (JList<?>) e.getComponent(); startOutside = !contains(list, e.getPoint()); if (startOutside) { clearSelectionAndFocus(list); } } @Override public void mouseReleased(MouseEvent e) { startOutside = false; } @Override public void mouseDragged(MouseEvent e) { JList<?> list = (JList<?>) e.getComponent(); if (contains(list, e.getPoint())) { startOutside = false; } else if (startOutside) { clearSelectionAndFocus(list); } } }
package com.csci4448.MediaManagementSystem.controller; import com.csci4448.MediaManagementSystem.model.media.*; import com.csci4448.MediaManagementSystem.model.review.ReviewDAO; import com.csci4448.MediaManagementSystem.model.review.ReviewDAOImpl; import com.csci4448.MediaManagementSystem.model.review.Review; import com.csci4448.MediaManagementSystem.model.user.UserDAO; import com.csci4448.MediaManagementSystem.model.user.UserDAOImpl; import com.csci4448.MediaManagementSystem.model.user.User; import com.csci4448.MediaManagementSystem.ui.states.*; import com.csci4448.MediaManagementSystem.ui.components.*; import java.util.ArrayList; import java.util.List; public class MainController { private Display display; private UserDAO userDAO; private MediaDAO mediaDAO; private ReviewDAO reviewDAO; private User activeUser; private Media activeMedia; private Review activeReview; public MainController() { userDAO = new UserDAOImpl(); mediaDAO = new MediaDAOImpl(); reviewDAO = new ReviewDAOImpl(); display = new Display(this); loginRequest(); } public void loginRequest() { display.setState(new LoginPanel(this)); } public void loginSubmitRequest(String username, String password) { if (userDAO.userExists(username, password)) { User user = userDAO.getUser(username); if (user != null) activeUser = user; else { //ToDo: Database error, couldn't retrieve user, throw error in UI } storeRequest(); } else { //Todo: Pass error message to UI saying that either username or password was incorrect } } public void createAccountRequest() { display.setState(new CreateAccountPanel(this)); } public void createAccountSubmitRequest(String firstName, String lastName, String username, String email, String password) { if (userDAO.userExists(username, password)) { //ToDo: Send error message in UI that user already exists with that username } else { int res = userDAO.addUser(username, password, email, firstName, lastName); if (res == -1) { //ToDo: Error creating user, send error message to UI } else { User user = userDAO.getUser(res); if (user != null) activeUser = user; else { //ToDo: Database error, couldn't retrieve user, throw error in UI } storeRequest(); } } } public void storeRequest() { GridMediaPanel store = new GridMediaPanel(this, 215, 327, 15, 35); store.getMenuPanel().getStoreButton().setIsSelected(true); List<Media> mediaRecords = SystemInventory.getSystemInventory().getAllMedia(); for(Media media: mediaRecords) { MediaListing listing = new MediaListing(this, media.getMediaID(), media.getImage(), media.getTitle(), media.getPrice()); store.add(listing); } display.setState(store); } public void libraryRequest() { GridMediaPanel library = new GridMediaPanel(this, 215, 327, 15, 35); library.getMenuPanel().getLibraryButton().setIsSelected(true); UserDAOImpl userDAO = new UserDAOImpl(); List<Media> personalInventory = userDAO.getPersonalInventory(activeUser.getUsername()); for(Media media: personalInventory) { //ToDo: modify MediaListing so it displays owned/rented instead of price MediaListing listing = new MediaListing(this, media.getMediaID(), media.getImage(), media.getTitle(), media.getPrice()); library.add(listing); } display.setState(library); } public void adminRequest() { // ToDo: Implement this /* display.setState(new IndividualMediaPanel(this, null)); */ } public void addFundsRequest() { DisplayState state = display.getActiveState(); if (state instanceof MainContentPanel) { ((MainContentPanel) state).setPopUpWindow(new AddFundsPanel(this)); } } public void addFundsCancelRequest() { DisplayState state = display.getActiveState(); if (state instanceof MainContentPanel) { ((MainContentPanel) state).removePopUpWindow(); } } public void addFundsSubmitRequest(int amount) { userDAO.increaseAccountBalance(activeUser.getUsername(), amount); DisplayState state = display.getActiveState(); if (state instanceof MainContentPanel) { ((MainContentPanel) state).removePopUpWindow(); } } public void individualMediaRequest(int mediaId) { Media media = mediaDAO.getMedia(mediaId); if (media == null) { //ToDo: Database error, couldn't fetch media, throw error in UI return; } activeMedia = media; String mediaAction = ""; if (activeMedia.getIsRentable() && activeUser.getPersonalInventory().contains(activeMedia)) mediaAction = "Return Media"; else if (activeMedia.getIsRentable()) mediaAction = "Rent $" + media.getPrice(); else if (!activeMedia.getIsRentable() && activeUser.getPersonalInventory().contains(activeMedia)) mediaAction = "Sell $" + activeMedia.getSellPrice(); else mediaAction = "Buy $" + activeMedia.getPrice(); IndividualMediaPanel indMedia = new IndividualMediaPanel(this); indMedia.populateMedia(MediaInfo.createFromMedia(activeMedia)); List<Review> reviews = new ArrayList<Review>(activeMedia.getReviews()); ArrayList<ReviewPanel> rs = new ArrayList<ReviewPanel>(); for (Review r : reviews) { rs.add(new ReviewPanel(r.getUser().getUsername(), r.getReviewText(), r.getRatingValue())); } indMedia.populateReviews(rs); display.setState(indMedia); } public void individualMediaActionRequest(int mediaId) { Media media = mediaDAO.getMedia(mediaId); if (media == null) { // ToDo: Database error, couldn't fetch media, throw error in UI return; } activeMedia = media; String mediaAction = ""; if (activeMedia.getIsRentable() && activeUser.getPersonalInventory().contains(activeMedia)) mediaAction = "return"; else if (activeMedia.getIsRentable()) mediaAction = "rent"; else if (!activeMedia.getIsRentable() && activeUser.getPersonalInventory().contains(activeMedia)) mediaAction = "sell"; else mediaAction = "buy"; //This is how you add a confirmation window. To remove it, do the same thing but call removePopUpWindow instead DisplayState state = display.getActiveState(); if (state instanceof IndividualMediaPanel) { ((MainContentPanel) state).setPopUpWindow(new ConfirmationWindow(this, "Are you sure you want to " + mediaAction + " this?", "Yes", "No")); } } private void buyOrRentRequestErrorHandle(int res) { if (res == -4) { // ToDo: Throw error to UI saying that there was a system error } else if (res == -3) { // ToDo: Throw error to UI saying that the media is not correct purchasable type } else if (res == -2) { // ToDo: Throw error to UI saying that the media is out of stock // This may change if we implement the waitlist functionality } else if (res == -1) { // ToDo: Throw error to UI saying that the user doesn't have enough money in account balance } } private void sellOrReturnRequestErrorHandle(int res) { if (res == -3) { // ToDo: Throw error to UI saying that there was a system error } else if (res == -2) { // ToDo: Throw error to UI saying that the media is not correct purchasable type } else if (res == -1) { // ToDo: Throw error to UI saying that the media is not currently owned/rented by the user } } public void confirmationRequest(boolean isConfirmed) { if (!isConfirmed) { DisplayState state = display.getActiveState(); if (state instanceof IndividualMediaPanel) { ((MainContentPanel) state).removePopUpWindow(); } } else { if (activeMedia.getIsRentable() && activeUser.getPersonalInventory().contains(activeMedia)) { int res = SystemInventory.getSystemInventory().returnMedia(activeUser.getUsername(), activeMedia.getMediaID()); sellOrReturnRequestErrorHandle(res); } else if (activeMedia.getIsRentable()) { int res = SystemInventory.getSystemInventory().rentMedia(activeUser.getUsername(), activeMedia.getMediaID()); buyOrRentRequestErrorHandle(res); } else if (!activeMedia.getIsRentable() && activeUser.getPersonalInventory().contains(activeMedia)) { int res = SystemInventory.getSystemInventory().sellMedia(activeUser.getUsername(), activeMedia.getMediaID()); sellOrReturnRequestErrorHandle(res); } else { int res = SystemInventory.getSystemInventory().buyMedia(activeUser.getUsername(), activeMedia.getMediaID()); buyOrRentRequestErrorHandle(res); } } } public void reviewMediaRequest(int mediaId) { DisplayState state = display.getActiveState(); if (state instanceof MainContentPanel) { ((MainContentPanel) state).setPopUpWindow(new EditReviewPanel(this, mediaId)); } } public void reviewMediaCancelRequest() { DisplayState state = display.getActiveState(); if (state instanceof MainContentPanel) { ((MainContentPanel) state).removePopUpWindow(); } } public void reviewMediaSubmitRequest(int mediaId, String reviewText, int rating) { reviewDAO.addReview(reviewText, rating, activeUser.getUserID(), mediaId); DisplayState state = display.getActiveState(); if (state instanceof MainContentPanel) { ((MainContentPanel) state).removePopUpWindow(); individualMediaRequest(mediaId); } } public UserDAO getUserDAO() { return userDAO; } public boolean hasActiveUser() { return activeUser != null; } public boolean isAdmin() { return activeUser != null && activeUser.getIsAdmin(); } public MediaDAO getMediaDAO() { return mediaDAO; } public boolean hasActiveMedia() { return activeMedia != null; } public ReviewDAO getReviewDAO() { return reviewDAO; } public boolean hasActiveReview() { return activeReview != null; } }
package org.onebeartoe.modeling.openscad.test.suite; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import org.onebeartoe.modeling.openscad.test.suite.utils.DataSetValidator; import org.onebeartoe.modeling.openscad.test.suite.utils.OpenScadFileFinder; import org.onebeartoe.modeling.openscad.test.suite.utils.OpenScadTestSuiteService; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class OpenScadTestSuiteTest { private Logger logger; private RunProfile runProfile; private OpenScadTestSuiteService testService; public OpenScadTestSuiteTest() throws Exception { logger = Logger.getLogger( getClass().getName() ); testService = new OpenScadTestSuiteService(); runProfile = new RunProfile(); runProfile.executablePath = "openscad"; //TODO: use the nightly version, since it is the latest version? // runProfile.executablePath = "openscad-nightly"; runProfile.path = "src/main/openscad/basics/"; OpenScadFileFinder openScadFinder = new OpenScadFileFinder(); Path inpath = FileSystems.getDefault().getPath(runProfile.path); runProfile.openscadPaths = openScadFinder.getFiles(inpath); runProfile.redirectOpenscad = false; DataSetValidator inputValidator = new DataSetValidator(); List<String> missingPngs = inputValidator.validate(runProfile.openscadPaths); testService.printValidationResults(missingPngs); if (!missingPngs.isEmpty()) { String message = "The test suite will not continue with missing baseline PNG images."; System.err.println(); System.err.println(message); throw new Exception(message); } int count = testService.generateProposedBaselines(runProfile); // check if the count is less than 0 if(count < 0) { String message = "There was an error with proposed baseline generation."; throw new Exception(message); } } @DataProvider(name="errorFiles") public Object[][] getErrorFiles() throws Exception { List<String> compareImages = testService.compareImages(runProfile); int parameterCount = 1; List<Object []> rows = compareImages.stream() .sorted() .map( l -> { Object [] array = new Object[parameterCount]; array[0] = l; return array; }).collect(Collectors.toList()); Object[][] data = new Object[rows.size()][parameterCount]; int r = 0; for(Object [] row : rows) { data[r] = row; r++; } return data; } @Test(dataProvider="errorFiles", groups = {"openscad-test-suite"}) /** * Any parameter passed to this test represents a file that failed baseline * proposed baseline comparison; i.e. all executions of this test are * expected to file. */ public void reportErros(String comparisonFile) throws Exception { String message = "The comparison failed for: " + comparisonFile; throw new Exception(message); } }
package com.hubspot.singularity.scheduler; import io.dropwizard.lifecycle.Managed; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Singleton; import org.apache.mesos.Protos.SlaveID; import org.apache.mesos.Protos.TaskID; import org.apache.mesos.Protos.TaskState; import org.apache.mesos.Protos.TaskStatus; import org.apache.mesos.SchedulerDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.Inject; import com.google.inject.name.Named; import com.hubspot.mesos.JavaUtils; import com.hubspot.singularity.SingularityAbort; import com.hubspot.singularity.SingularityAbort.AbortReason; import com.hubspot.singularity.SingularityMainModule; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskStatusHolder; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.mesos.SchedulerDriverSupplier; import com.hubspot.singularity.sentry.SingularityExceptionNotifier; @Singleton public class SingularityTaskReconciliation implements Managed { private static final Logger LOG = LoggerFactory.getLogger(SingularityTaskReconciliation.class); private final TaskManager taskManager; private final String serverId; private final ScheduledExecutorService executorService; private final AtomicBoolean isRunningReconciliation; private final SingularityConfiguration configuration; private final SingularityAbort abort; private final SingularityExceptionNotifier exceptionNotifier; private final SchedulerDriverSupplier schedulerDriverSupplier; @Inject public SingularityTaskReconciliation(SingularityExceptionNotifier exceptionNotifier, TaskManager taskManager, SingularityConfiguration configuration, @Named(SingularityMainModule.SERVER_ID_PROPERTY) String serverId, SingularityAbort abort, SchedulerDriverSupplier schedulerDriverSupplier) { this.taskManager = taskManager; this.serverId = serverId; this.exceptionNotifier = exceptionNotifier; this.configuration = configuration; this.abort = abort; this.schedulerDriverSupplier = schedulerDriverSupplier; this.isRunningReconciliation = new AtomicBoolean(false); this.executorService = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setNameFormat("SingularityTaskReconciliation-%d").build()); } @Override public void start() { } @Override public void stop() { MoreExecutors.shutdownAndAwaitTermination(executorService, 1, TimeUnit.SECONDS); } enum ReconciliationState { ALREADY_RUNNING, STARTED, NO_DRIVER; } @VisibleForTesting boolean isReconciliationRunning() { return isRunningReconciliation.get(); } public ReconciliationState startReconciliation() { if (!isRunningReconciliation.compareAndSet(false, true)) { LOG.info("Reconciliation is already running, NOT starting a new reconciliation process"); return ReconciliationState.ALREADY_RUNNING; } Optional<SchedulerDriver> schedulerDriver = schedulerDriverSupplier.get(); if (!schedulerDriver.isPresent()) { LOG.trace("Not running reconciliation - no schedulerDriver present"); isRunningReconciliation.set(false); return ReconciliationState.NO_DRIVER; } final long reconciliationStart = System.currentTimeMillis(); final List<SingularityTaskId> activeTaskIds = taskManager.getActiveTaskIds(); LOG.info("Starting a reconciliation cycle - {} current active tasks", activeTaskIds.size()); SchedulerDriver driver = schedulerDriver.get(); driver.reconcileTasks(Collections.<TaskStatus> emptyList()); scheduleReconciliationCheck(driver, reconciliationStart, activeTaskIds, 0); return ReconciliationState.STARTED; } private void scheduleReconciliationCheck(final SchedulerDriver driver, final long reconciliationStart, final Collection<SingularityTaskId> remainingTaskIds, final int numTimes) { LOG.info("Scheduling reconciliation check #{} - {} tasks left - waiting {}", numTimes + 1, remainingTaskIds.size(), JavaUtils.durationFromMillis(configuration.getCheckReconcileWhenRunningEveryMillis())); executorService.schedule(new Runnable() { @Override public void run() { try { checkReconciliation(driver, reconciliationStart, remainingTaskIds, numTimes + 1); } catch (Throwable t) { LOG.error("While checking for reconciliation tasks", t); exceptionNotifier.notify(t); abort.abort(AbortReason.UNRECOVERABLE_ERROR); } } }, configuration.getCheckReconcileWhenRunningEveryMillis(), TimeUnit.MILLISECONDS); } private void checkReconciliation(final SchedulerDriver driver, final long reconciliationStart, final Collection<SingularityTaskId> remainingTaskIds, final int numTimes) { final List<SingularityTaskStatusHolder> taskStatusHolders = taskManager.getLastActiveTaskStatusesFor(remainingTaskIds); final List<TaskStatus> taskStatuses = Lists.newArrayListWithCapacity(taskStatusHolders.size()); for (SingularityTaskStatusHolder taskStatusHolder : taskStatusHolders) { if (taskStatusHolder.getServerId().equals(serverId) && taskStatusHolder.getServerTimestamp() > reconciliationStart) { continue; } if (taskStatusHolder.getTaskStatus().isPresent()) { LOG.debug("Re-requesting task status for {}", taskStatusHolder.getTaskId()); taskStatuses.add(taskStatusHolder.getTaskStatus().get()); } else { TaskStatus.Builder fakeTaskStatusBuilder = TaskStatus.newBuilder() .setTaskId(TaskID.newBuilder().setValue(taskStatusHolder.getTaskId().getId())) .setState(TaskState.TASK_STARTING); if (taskStatusHolder.getSlaveId().isPresent()) { fakeTaskStatusBuilder.setSlaveId(SlaveID.newBuilder().setValue(taskStatusHolder.getSlaveId().get())); } LOG.info("Task {} didn't have a TaskStatus yet, submitting fake status", taskStatusHolder.getTaskId()); taskStatuses.add(fakeTaskStatusBuilder.build()); } } if (taskStatuses.isEmpty()) { LOG.info("Task reconciliation ended after {} checks and {}", numTimes, JavaUtils.duration(reconciliationStart)); isRunningReconciliation.set(false); return; } LOG.info("Requesting reconciliation of {} taskStatuses, task reconciliation has been running for {}", taskStatuses.size(), JavaUtils.duration(reconciliationStart)); driver.reconcileTasks(taskStatuses); scheduleReconciliationCheck(driver, reconciliationStart, remainingTaskIds, numTimes); } }
package lucee.runtime.tag; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TimeZone; import java.util.jar.Attributes; import java.util.jar.Manifest; import javax.servlet.ServletConfig; import javax.servlet.jsp.tagext.Tag; import lucee.commons.collection.MapFactory; import lucee.commons.digest.HashUtil; import lucee.commons.io.IOUtil; import lucee.commons.io.SystemUtil; import lucee.commons.io.cache.Cache; import lucee.commons.io.cache.CachePro; import lucee.commons.io.compress.CompressUtil; import lucee.commons.io.log.LoggerAndSourceData; import lucee.commons.io.log.log4j.Log4jUtil; import lucee.commons.io.res.Resource; import lucee.commons.io.res.filter.DirectoryResourceFilter; import lucee.commons.io.res.filter.ExtensionResourceFilter; import lucee.commons.io.res.filter.LogResourceFilter; import lucee.commons.io.res.filter.NotResourceFilter; import lucee.commons.io.res.filter.OrResourceFilter; import lucee.commons.io.res.filter.ResourceFilter; import lucee.commons.io.res.util.ResourceUtil; import lucee.commons.lang.IDGenerator; import lucee.commons.lang.StringUtil; import lucee.commons.surveillance.HeapDumper; import lucee.loader.engine.CFMLEngine; import lucee.loader.osgi.BundleCollection; import lucee.runtime.CFMLFactory; import lucee.runtime.CFMLFactoryImpl; import lucee.runtime.Mapping; import lucee.runtime.MappingImpl; import lucee.runtime.PageContextImpl; import lucee.runtime.PageSource; import lucee.runtime.PageSourceImpl; import lucee.runtime.cache.CacheConnection; import lucee.runtime.cfx.customtag.CFXTagClass; import lucee.runtime.cfx.customtag.CPPCFXTagClass; import lucee.runtime.cfx.customtag.JavaCFXTagClass; import lucee.runtime.config.AdminSync; import lucee.runtime.config.Config; import lucee.runtime.config.ConfigImpl; import lucee.runtime.config.ConfigServer; import lucee.runtime.config.ConfigServerImpl; import lucee.runtime.config.ConfigWeb; import lucee.runtime.config.ConfigWebAdmin; import lucee.runtime.config.ConfigWebFactory; import lucee.runtime.config.ConfigWebImpl; import lucee.runtime.config.ConfigWebUtil; import lucee.runtime.config.Constants; import lucee.runtime.config.DebugEntry; import lucee.runtime.config.Password; import lucee.runtime.config.PasswordImpl; import lucee.runtime.config.RemoteClient; import lucee.runtime.config.RemoteClientImpl; import lucee.runtime.db.ClassDefinition; import lucee.runtime.db.DataSource; import lucee.runtime.db.DataSourceImpl; import lucee.runtime.db.DataSourceManager; import lucee.runtime.db.DatasourceConnectionImpl; import lucee.runtime.db.JDBCDriver; import lucee.runtime.debug.DebuggerPro; import lucee.runtime.engine.CFMLEngineImpl; import lucee.runtime.engine.ExecutionLogFactory; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.ApplicationException; import lucee.runtime.exp.DatabaseException; import lucee.runtime.exp.DeprecatedException; import lucee.runtime.exp.PageException; import lucee.runtime.exp.PageExceptionImpl; import lucee.runtime.exp.SecurityException; import lucee.runtime.ext.tag.DynamicAttributes; import lucee.runtime.ext.tag.TagImpl; import lucee.runtime.extension.Extension; import lucee.runtime.extension.ExtensionImpl; import lucee.runtime.extension.ExtensionProvider; import lucee.runtime.extension.RHExtensionProvider; import lucee.runtime.functions.cache.Util; import lucee.runtime.functions.query.QuerySort; import lucee.runtime.gateway.GatewayEngineImpl; import lucee.runtime.gateway.GatewayEntry; import lucee.runtime.gateway.GatewayEntryImpl; import lucee.runtime.gateway.GatewayUtil; import lucee.runtime.i18n.LocaleFactory; import lucee.runtime.listener.AppListenerUtil; import lucee.runtime.listener.ApplicationListener; import lucee.runtime.monitor.IntervallMonitor; import lucee.runtime.monitor.Monitor; import lucee.runtime.monitor.RequestMonitor; import lucee.runtime.net.http.CertificateInstaller; import lucee.runtime.net.http.ReqRspUtil; import lucee.runtime.net.mail.SMTPException; import lucee.runtime.net.mail.SMTPVerifier; import lucee.runtime.net.mail.Server; import lucee.runtime.net.mail.ServerImpl; import lucee.runtime.net.proxy.ProxyData; import lucee.runtime.net.proxy.ProxyDataImpl; import lucee.runtime.op.Caster; import lucee.runtime.op.Decision; import lucee.runtime.op.Duplicator; import lucee.runtime.op.date.DateCaster; import lucee.runtime.orm.ORMConfiguration; import lucee.runtime.orm.ORMConfigurationImpl; import lucee.runtime.orm.ORMEngine; import lucee.runtime.osgi.BundleBuilderFactory; import lucee.runtime.osgi.BundleFile; import lucee.runtime.osgi.JarUtil; import lucee.runtime.osgi.ManifestUtil; import lucee.runtime.osgi.OSGiUtil; import lucee.runtime.osgi.OSGiUtil.BundleDefinition; import lucee.runtime.rest.RestUtil; import lucee.runtime.security.SecurityManager; import lucee.runtime.security.SecurityManagerImpl; import lucee.runtime.spooler.ExecutionPlan; import lucee.runtime.spooler.SpoolerEngine; import lucee.runtime.spooler.SpoolerEngineImpl; import lucee.runtime.spooler.SpoolerTask; import lucee.runtime.spooler.remote.RemoteClientTask; import lucee.runtime.type.Array; import lucee.runtime.type.ArrayImpl; import lucee.runtime.type.Collection; import lucee.runtime.type.Collection.Key; import lucee.runtime.type.KeyImpl; import lucee.runtime.type.Query; import lucee.runtime.type.QueryImpl; import lucee.runtime.type.Struct; import lucee.runtime.type.StructImpl; import lucee.runtime.type.dt.DateTime; import lucee.runtime.type.dt.DateTimeImpl; import lucee.runtime.type.dt.TimeSpan; import lucee.runtime.type.scope.Cluster; import lucee.runtime.type.scope.ClusterEntryImpl; import lucee.runtime.type.util.ArrayUtil; import lucee.runtime.type.util.ComponentUtil; import lucee.runtime.type.util.KeyConstants; import lucee.runtime.type.util.ListUtil; import lucee.transformer.library.ClassDefinitionImpl; import lucee.transformer.library.function.FunctionLib; import lucee.transformer.library.tag.TagLib; import org.apache.log4j.Level; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.osgi.framework.Version; public final class Admin extends TagImpl implements DynamicAttributes { private static final short TYPE_WEB=0; private static final short TYPE_SERVER=1; private static final short ACCESS_FREE=0; private static final short ACCESS_NOT_WHEN_WEB=1; private static final short ACCESS_NOT_WHEN_SERVER=2; private static final short ACCESS_NEVER=3; private static final short ACCESS_READ=10; private static final short ACCESS_WRITE=11; private static final Collection.Key DEBUG = KeyConstants._debug; //private static final Collection.Key DEBUG_TEMPLATE = KeyImpl.intern("debugTemplate"); private static final Collection.Key DEBUG_SHOW_QUERY_USAGE = KeyImpl.intern("debugShowQueryUsage"); //private static final Collection.Key STR_DEBUG_TEMPLATE = KeyImpl.intern("strdebugTemplate"); private static final Collection.Key TEMPLATES = KeyConstants._templates; private static final Collection.Key STR = KeyConstants._str; private static final Collection.Key DO_STATUS_CODE = KeyImpl.intern("doStatusCode"); private static final Collection.Key LABEL = KeyConstants._label; private static final Collection.Key FILE_ACCESS = KeyImpl.intern("file_access"); private static final Collection.Key IP_RANGE = KeyImpl.intern("ipRange"); private static final Collection.Key CUSTOM = KeyConstants._custom; private static final Collection.Key READONLY = KeyImpl.intern("readOnly"); private static final Collection.Key LOG_ENABLED = KeyImpl.intern("logEnabled"); private static final Collection.Key CLASS = KeyConstants._class; private static final Key HAS_OWN_SEC_CONTEXT = KeyImpl.intern("hasOwnSecContext"); private static final Key CONFIG_FILE = KeyImpl.intern("config_file"); private static final Key PROCEDURE = KeyImpl.intern("procedure"); private static final Key SERVER_LIBRARY = KeyImpl.intern("serverlibrary"); private static final Key KEEP_ALIVE = KeyImpl.intern("keepalive"); private static final Key CLIENT_SIZE = KeyImpl.intern("clientSize"); private static final Key SESSION_SIZE = KeyImpl.intern("sessionSize"); private static final Key CLIENT_ELEMENTS = KeyImpl.intern("clientElements"); private static final Key SESSION_ELEMENTS = KeyImpl.intern("sessionElements"); private static final short MAPPING_REGULAR = 1; private static final short MAPPING_CT = 2; private static final short MAPPING_CFC = 4; /* others: PDFRenderer.jar ? xmlparserv2.jar not needed: slf4j-simple.jar xdb.jar */ private Struct attributes=new StructImpl(); private String action=null; private short type; private Password password; private ConfigWebAdmin admin; private ConfigImpl config; private static final ResourceFilter FILTER_CFML_TEMPLATES=new LogResourceFilter( new OrResourceFilter(new ResourceFilter[]{ new DirectoryResourceFilter(), new ExtensionResourceFilter(Constants.getExtensions()) })); private static final Key FRAGMENT = KeyImpl.init("fragment"); private static final Key HEADERS = KeyImpl.init("headers"); private static final Key SYMBOLIC_NAME = KeyImpl.init("symbolicName"); private static final Key VENDOR = KeyImpl.init("vendor"); private static final Key USED_BY = KeyImpl.init("usedBy"); private AdminSync adminSync; @Override public void release() { super.release(); attributes.clear(); } @Override public void setDynamicAttribute(String uri, String localName, Object value) { attributes.setEL(KeyImpl.getInstance(localName),value); } public void setDynamicAttribute(String uri, Collection.Key localName, Object value) { attributes.setEL(localName,value); } @Override public int doStartTag() throws PageException { config=(ConfigImpl)pageContext.getConfig(); // Action Object objAction=attributes.get(KeyConstants._action); if(objAction==null)throw new ApplicationException("missing attrbute action for tag admin"); action=StringUtil.toLowerCase(Caster.toString(objAction)).trim(); // Generals if(action.equals("buildbundle")) { doBuildBundle(); return SKIP_BODY; } if(action.equals("readbundle")) { doReadBundle(); return SKIP_BODY; } if(action.equals("getlocales")) { doGetLocales(); return SKIP_BODY; } if(action.equals("gettimezones")) { doGetTimeZones(); return SKIP_BODY; } if(action.equals("printdebug")) { throw new DeprecatedException("action [printdebug] is no longer supported, use instead [getdebugdata]"); } if(action.equals("getdebugdata")) { doGetDebugData(); return SKIP_BODY; } if(action.equals("adddump")) { doAddDump(); return SKIP_BODY; } if(action.equals("getloginsettings")) { doGetLoginSettings(); return SKIP_BODY; } // Type type=toType(getString("type","web"),true); // has Password if(action.equals("haspassword")) { //long start=System.currentTimeMillis(); boolean hasPassword=type==TYPE_WEB? pageContext.getConfig().hasPassword(): pageContext.getConfig().hasServerPassword(); pageContext.setVariable(getString("admin",action,"returnVariable",true),Caster.toBoolean(hasPassword)); return SKIP_BODY; } // update Password else if(action.equals("updatepassword")) { try { ((ConfigWebImpl)pageContext.getConfig()).updatePassword(type!=TYPE_WEB, getString("oldPassword",null),getString("admin",action,"newPassword",true)); } catch (Exception e) { throw Caster.toPageException(e); } return SKIP_BODY; } try { _doStartTag(); } catch (IOException e) { throw Caster.toPageException(e); } return Tag.SKIP_BODY; } private void doAddDump() throws ApplicationException { DebuggerPro debugger=(DebuggerPro) pageContext.getDebugger(); PageSource ps = pageContext.getCurrentTemplatePageSource(); debugger.addDump(ps, getString("admin",action,"dump",true)); } private short toType(String strType, boolean throwError) throws ApplicationException { strType=StringUtil.toLowerCase(strType).trim(); if("web".equals(strType))return TYPE_WEB; else if("server".equals(strType))return TYPE_SERVER; if(throwError) throw new ApplicationException("invalid value for attribute type ["+strType+"] of tag admin","valid values are web, server"); return TYPE_WEB; } private void doTagSchedule() throws PageException { Schedule schedule=new Schedule(); try { schedule.setPageContext(pageContext); schedule.setAction(getString("admin",action,"scheduleAction")); schedule.setTask(getString("task",null)); schedule.setHidden(getBoolV("hidden",false)); schedule.setReadonly(getBoolV("readonly",false)); schedule.setOperation(getString("operation",null)); schedule.setFile(getString("file",null)); schedule.setPath(getString("path",null)); schedule.setStartdate(getObject("startDate",null)); schedule.setStarttime(getObject("startTime",null)); schedule.setUrl(getString("url",null)); schedule.setPublish(getBoolV("publish",false)); schedule.setEnddate(getObject("endDate",null)); schedule.setEndtime(getObject("endTime",null)); schedule.setInterval(getString("interval",null)); schedule.setRequesttimeout(new Double(getDouble("requestTimeOut",-1))); schedule.setUsername(getString("username",null)); schedule.setPassword(getString("schedulePassword",null)); schedule.setProxyserver(getString("proxyServer",null)); schedule.setProxyuser(getString("proxyuser",null)); schedule.setProxypassword(getString("proxyPassword",null)); schedule.setResolveurl(getBoolV("resolveURL",false)); schedule.setPort(new Double(getDouble("port",-1))); schedule.setProxyport(new Double(getDouble("proxyPort",80))); schedule.setReturnvariable(getString("returnvariable","cfschedule")); schedule.doStartTag(); } finally { schedule.release(); adminSync.broadcast(attributes, config); adminSync.broadcast(attributes, config); } } /*private void doTagSearch() throws PageException { Search search=new Search(); try { search.setPageContext(pageContext); search.setName(getString("admin",action,"name")); search.setCollection(getString("admin",action,"collection")); search.setType(getString("type",null)); search.setMaxrows(getDouble("maxRows",-1)); search.setStartrow(getDouble("startRow",1)); search.setCategory(getString("category",null)); search.setCategorytree(getString("categoryTree",null)); search.setStatus(getString("status",null)); search.setSuggestions(getString("suggestions",null)); search.doStartTag(); } finally { search.release(); } }*/ private void doTagIndex() throws PageException { Index index=new Index(); try { index.setPageContext(pageContext); index.setCollection(getString("admin",action,"collection")); index.setAction(getString("admin",action,"indexAction")); index.setType(getString("indexType",null)); index.setTitle(getString("title",null)); index.setKey(getString("key",null)); index.setBody(getString("body",null)); index.setCustom1(getString("custom1",null)); index.setCustom2(getString("custom2",null)); index.setCustom3(getString("custom3",null)); index.setCustom4(getString("custom4",null)); index.setUrlpath(getString("URLpath",null)); index.setExtensions(getString("extensions",null)); index.setQuery(getString("query",null)); index.setRecurse(getBoolV("recurse",false)); index.setLanguage(getString("language",null)); index.setCategory(getString("category",null)); index.setCategorytree(getString("categoryTree",null)); index.setStatus(getString("status",null)); index.setPrefix(getString("prefix",null)); index.doStartTag(); } finally { index.release(); adminSync.broadcast(attributes, config); } } private void doTagCollection() throws PageException { lucee.runtime.tag.Collection coll=new lucee.runtime.tag.Collection(); try { coll.setPageContext(pageContext); //coll.setCollection(getString("admin",action,"collection")); coll.setAction(getString("collectionAction",null)); coll.setCollection(getString("collection",null)); coll.setPath(getString("path",null)); coll.setLanguage(getString("language",null)); coll.setName(getString("name",null)); coll.doStartTag(); } finally { coll.release(); adminSync.broadcast(attributes, config); } } /** * @throws PageException * */ private void _doStartTag() throws PageException,IOException { config=(ConfigImpl)pageContext.getConfig(); // getToken if(action.equals("gettoken")) { doGetToken(); return; } // schedule if(action.equals("schedule")) { doTagSchedule(); return; } // search if(action.equals("collection")) { doTagCollection(); return; } // index if(action.equals("index")) { doTagIndex(); return; } // cluster if(action.equals("setcluster")) { doSetCluster(); return; } if(action.equals("getcluster")) { doGetCluster(); return; } if(check("hashpassword",ACCESS_FREE)) { String raw=getString("admin",action,"pw"); Password pw=PasswordImpl.passwordToCompare(pageContext.getConfig(),type!=TYPE_WEB,raw); Password changed=((ConfigWebImpl)pageContext.getConfig()).updatePasswordIfNecessary(type==TYPE_SERVER,raw); if(changed!=null) pw=changed; pageContext.setVariable( getString("admin",action,"returnVariable"), pw.getPassword() ); return; // do not remove } try { // Password String strPW = getString("password",""); Password tmp = type==TYPE_SERVER?((ConfigWebImpl)config).isServerPasswordEqual(strPW):config.isPasswordEqual(strPW); // hash password if necessary (for backward compatibility) if(tmp!=null)password=tmp; else password=null; // Config if(type==TYPE_SERVER) config=(ConfigImpl)pageContext.getConfig().getConfigServer(password); adminSync = config.getAdminSync(); admin = ConfigWebAdmin.newInstance(config,password); } catch (Exception e) { throw Caster.toPageException(e); } if(check("connect",ACCESS_FREE)) { ConfigWebUtil.checkPassword(config,null,password); ConfigWebUtil.checkGeneralReadAccess(config,password); try{ if(config instanceof ConfigServer) ((PageContextImpl)pageContext).setServerPassword(password); } catch(Throwable t){} } else if(check("getinfo", ACCESS_FREE) && check2(ACCESS_READ )) doGetInfo(); else if(check("surveillance", ACCESS_FREE) && check2(ACCESS_READ )) doSurveillance(); else if(check("getRegional", ACCESS_FREE) && check2(ACCESS_READ )) doGetRegional(); else if(check("isMonitorEnabled", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ )) doIsMonitorEnabled(); else if(check("resetORMSetting", ACCESS_FREE) && check2(ACCESS_READ )) doResetORMSetting(); else if(check("getORMSetting", ACCESS_FREE) && check2(ACCESS_READ )) doGetORMSetting(); else if(check("getORMEngine", ACCESS_FREE) && check2(ACCESS_READ )) doGetORMEngine(); else if(check("updateORMSetting", ACCESS_FREE) && check2(ACCESS_READ )) doUpdateORMSetting(); else if(check("getApplicationListener", ACCESS_FREE) && check2(ACCESS_READ )) doGetApplicationListener(); else if(check("getProxy", ACCESS_FREE) && check2(ACCESS_READ )) doGetProxy(); else if(check("getCharset", ACCESS_FREE) && check2(ACCESS_READ )) doGetCharset(); else if(check("getComponent", ACCESS_FREE) && check2(ACCESS_READ )) doGetComponent(); else if(check("getScope", ACCESS_FREE) && check2(ACCESS_READ )) doGetScope(); else if(check("getApplicationSetting", ACCESS_FREE) && check2(ACCESS_READ )) doGetApplicationSetting(); else if(check("getOutputSetting", ACCESS_FREE) && check2(ACCESS_READ )) doGetOutputSetting(); else if(check("getDatasourceSetting", ACCESS_FREE) && check2(ACCESS_READ )) doGetDatasourceSetting(); else if(check("getCustomTagSetting", ACCESS_FREE) && check2(ACCESS_READ )) doGetCustomTagSetting(); else if(check("getDatasource", ACCESS_FREE) && check2(ACCESS_READ )) doGetDatasource(); else if(check("getDatasources", ACCESS_FREE) && check2(ACCESS_READ )) doGetDatasources(); else if(check("getJDBCDrivers", ACCESS_FREE) && check2(ACCESS_READ )) doGetJDBCDrivers(); else if(check("getCacheConnections", ACCESS_FREE) && check2(ACCESS_READ )) doGetCacheConnections(); else if(check("getCacheConnection", ACCESS_FREE) && check2(ACCESS_READ )) doGetCacheConnection(); else if(check("getCacheDefaultConnection",ACCESS_FREE) && check2(ACCESS_READ )) doGetCacheDefaultConnection(); else if(check("getRemoteClients", ACCESS_FREE) && check2(ACCESS_READ )) doGetRemoteClients(); else if(check("getRemoteClient", ACCESS_FREE) && check2(ACCESS_READ )) doGetRemoteClient(); else if(check("hasRemoteClientUsage", ACCESS_FREE) && check2(ACCESS_READ )) doHasRemoteClientUsage(); else if(check("getRemoteClientUsage", ACCESS_FREE) && check2(ACCESS_READ )) doGetRemoteClientUsage(); else if(check("getSpoolerTasks", ACCESS_FREE) && check2(ACCESS_READ )) doGetSpoolerTasks(); else if(check("getPerformanceSettings", ACCESS_FREE) && check2(ACCESS_READ )) doGetPerformanceSettings(); else if(check("getLogSettings", ACCESS_FREE) && check2(ACCESS_READ )) doGetLogSettings(); else if(check("getCompilerSettings", ACCESS_FREE) && check2(ACCESS_READ )) doGetCompilerSettings(); else if(check("updatePerformanceSettings",ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdatePerformanceSettings(); else if(check("updateCompilerSettings",ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateCompilerSettings(); else if(check("getGatewayentries", ACCESS_NOT_WHEN_SERVER) && check2(ACCESS_READ )) doGetGatewayEntries(); else if(check("getGatewayentry", ACCESS_NOT_WHEN_SERVER) && check2(ACCESS_READ )) doGetGatewayEntry(); else if(check("getRunningThreads", ACCESS_FREE) && check2(ACCESS_READ )) doGetRunningThreads(); else if(check("getMonitors", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ )) doGetMonitors(); else if(check("getMonitor", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ )) doGetMonitor(); else if(check("getBundles", ACCESS_FREE) && check2(ACCESS_READ )) doGetBundles(); else if(check("getExecutionLog", ACCESS_FREE) && check2(ACCESS_READ )) doGetExecutionLog(); else if(check("gateway", ACCESS_NOT_WHEN_SERVER) && check2(ACCESS_READ )) doGateway(); // alias for getSpoolerTasks else if(check("getRemoteClientTasks", ACCESS_FREE) && check2(ACCESS_READ )) doGetSpoolerTasks(); else if(check("getDatasourceDriverList",ACCESS_FREE) && check2(ACCESS_READ )) doGetDatasourceDriverList(); else if(check("getDebuggingList", ACCESS_FREE) && check2(ACCESS_READ )) doGetDebuggingList(); else if(check("getLoggedDebugData", ACCESS_FREE) && check2(ACCESS_READ )) doGetLoggedDebugData(); else if(check("getDebugSetting", ACCESS_FREE) && check2(ACCESS_READ )) doGetDebugSetting(); else if(check("getSSLCertificate", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ )) doGetSSLCertificate(); else if(check("getPluginDirectory", ACCESS_FREE) && check2(ACCESS_READ )) doGetPluginDirectory(); else if(check("getPlugins", ACCESS_FREE) && check2(ACCESS_READ )) doGetPlugins(); else if(check("updatePlugin", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdatePlugin(); else if(check("removePlugin", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemovePlugin(); else if(check("getContextDirectory",ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ )) getContextDirectory(); else if(check("updateContext", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateContext(); else if(check("removeContext", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doRemoveContext(); else if(check("getJars", ACCESS_FREE) && check2(ACCESS_READ )) doGetJars(); else if(check("getFlds", ACCESS_FREE) && check2(ACCESS_READ )) doGetFLDs(); else if(check("getTlds", ACCESS_FREE) && check2(ACCESS_READ )) doGetTLDs(); else if(check("getRHExtensions", ACCESS_FREE) && check2(ACCESS_READ )) doGetRHExtensions(); else if(check("getMailSetting", ACCESS_FREE) && check2(ACCESS_READ )) doGetMailSetting(); else if(check("getTaskSetting", ACCESS_FREE) && check2(ACCESS_READ )) doGetTaskSetting(); else if(check("getMailServers", ACCESS_FREE) && check2(ACCESS_READ )) doGetMailServers(); else if(check("getMapping", ACCESS_FREE) && check2(ACCESS_READ )) doGetMapping(); else if(check("getMappings", ACCESS_FREE) && check2(ACCESS_READ )) doGetMappings(); else if(check("getRestMappings", ACCESS_FREE) && check2(ACCESS_READ )) doGetRestMappings(); else if(check("getRestSettings", ACCESS_FREE) && check2(ACCESS_READ )) doGetRestSettings(); else if(check("getExtensions", ACCESS_FREE) && check2(ACCESS_READ )) doGetExtensions(); else if(check("getExtensionProviders", ACCESS_FREE) && check2(ACCESS_READ )) doGetExtensionProviders(); else if(check("getRHExtensionProviders",ACCESS_FREE) && check2(ACCESS_READ )) doGetRHExtensionProviders(); else if(check("getExtensionInfo", ACCESS_FREE) && check2(ACCESS_READ )) doGetExtensionInfo(); else if(check("getCustomTagMappings", ACCESS_FREE) && check2(ACCESS_READ )) doGetCustomTagMappings(); else if(check("getComponentMappings", ACCESS_FREE) && check2(ACCESS_READ )) doGetComponentMappings(); else if(check("getCfxTags", ACCESS_FREE) && check2(ACCESS_READ )) doGetCFXTags(); else if(check("getCPPCfxTags", ACCESS_FREE) && check2(ACCESS_READ )) doGetCPPCFXTags(); else if(check("getJavaCfxTags", ACCESS_FREE) && check2(ACCESS_READ )) doGetJavaCFXTags(); else if(check("getDebug", ACCESS_FREE) && check2(ACCESS_READ )) doGetDebug(); else if(check("getDebugEntry", ACCESS_FREE) && check2(ACCESS_READ )) doGetDebugEntry(); else if(check("getError", ACCESS_FREE) && check2(ACCESS_READ )) doGetError(); else if(check("verifyremoteclient", ACCESS_FREE) && check2(ACCESS_READ )) doVerifyRemoteClient(); else if(check("verifyDatasource", ACCESS_FREE) && check2(ACCESS_READ )) doVerifyDatasource(); else if(check("verifyCacheConnection", ACCESS_FREE) && check2(ACCESS_READ )) doVerifyCacheConnection(); else if(check("verifyMailServer", ACCESS_FREE) && check2(ACCESS_READ )) doVerifyMailServer(); else if(check("verifyExtensionProvider",ACCESS_FREE) && check2(ACCESS_READ )) doVerifyExtensionProvider(); else if(check("verifyJavaCFX", ACCESS_FREE) && check2(ACCESS_READ )) doVerifyJavaCFX(); else if(check("verifyCFX", ACCESS_FREE) && check2(ACCESS_READ )) doVerifyCFX(); else if(check("resetId", ACCESS_FREE) && check2(ACCESS_WRITE )) doResetId(); else if(check("updateLoginSettings", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateLoginSettings(); else if(check("updateLogSettings", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateLogSettings(); else if(check("updateJar", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateJar(); else if(check("updateSSLCertificate",ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateSSLCertificate(); else if(check("updateMonitorEnabled", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateMonitorEnabled(); else if(check("updateTLD", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateTLD(); else if(check("updateFLD", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateFLD(); else if(check("updateregional", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateRegional(); else if(check("updateApplicationListener",ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateApplicationListener(); else if(check("updateCachedWithin",ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateCachedWithin(); else if(check("updateproxy", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateProxy(); else if(check("updateCharset", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateCharset(); else if(check("updatecomponent", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateComponent(); else if(check("updatescope", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateScope(); else if(check("updateRestSettings", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateRestSettings(); else if(check("updateRestMapping", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateRestMapping(); else if(check("removeRestMapping", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveRestMapping(); else if(check("updateApplicationSetting",ACCESS_FREE) && check2(ACCESS_WRITE ))doUpdateApplicationSettings(); else if(check("updateOutputSetting", ACCESS_FREE) && check2(ACCESS_WRITE ))doUpdateOutputSettings(); else if(check("updatepsq", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdatePSQ(); else if(check("updatedatasource", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateDatasource(); else if(check("updateJDBCDriver", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateJDBCDriver(); else if(check("updateCacheDefaultConnection",ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateCacheDefaultConnection(); else if(check("updateCacheConnection", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateCacheConnection(); else if(check("updateremoteclient", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateRemoteClient(); else if(check("updateRemoteClientUsage",ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateRemoteClientUsage(); else if(check("updatemailsetting", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateMailSetting(); else if(check("updatemailserver", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateMailServer(); else if(check("updatetasksetting", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateTaskSetting(); else if(check("updatemapping", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateMapping(); else if(check("updatecustomtag", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateCustomTag(); else if(check("updateComponentMapping", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateComponentMapping(); else if(check("stopThread", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doStopThread(); else if(check("updatejavacfx", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateJavaCFX(); else if(check("updatecppcfx", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateCPPCFX(); else if(check("updatedebug", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateDebug(); else if(check("updatedebugentry", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateDebugEntry(); else if(check("updatedebugsetting", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateDebugSetting(); else if(check("updateerror", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateError(); else if(check("updateCustomTagSetting", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateCustomTagSetting(); else if(check("updateExtension", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateExtension(); else if(check("updateRHExtension", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateRHExtension(); else if(check("removeRHExtension", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveRHExtension(); else if(check("updateExtensionProvider",ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateExtensionProvider(); else if(check("updateRHExtensionProvider",ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateRHExtensionProvider(); else if(check("updateExtensionInfo", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateExtensionInfo(); else if(check("updateGatewayEntry", ACCESS_NOT_WHEN_SERVER) && check2(ACCESS_WRITE )) doUpdateGatewayEntry(); //else if(check("updateLogSettings", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateUpdateLogSettings(); else if(check("updateMonitor", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateMonitor(); else if(check("updateCacheHandler", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateCacheHandler(); else if(check("updateORMEngine", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateORMEngine(); else if(check("updateExecutionLog", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateExecutionLog(); //else if(check("removeproxy", ACCESS_NOT_WHEN_SERVER )) doRemoveProxy(); else if(check("removeMonitor", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doRemoveMonitor(); else if(check("removeCacheHandler",ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doRemoveCacheHandler(); else if(check("removeORMEngine",ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveORMEngine(); else if(check("removebundle", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveBundle(); else if(check("removeTLD", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveTLD(); else if(check("removeFLD", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveFLD(); else if(check("removeJDBCDriver", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveJDBCDriver(); else if(check("removedatasource", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveDatasource(); else if(check("removeCacheConnection", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveCacheConnection(); else if(check("removeremoteclient", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveRemoteClient(); else if(check("removeRemoteClientUsage",ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveRemoteClientUsage(); else if(check("removeSpoolerTask", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveSpoolerTask(); else if(check("removeAllSpoolerTask", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveAllSpoolerTask(); // alias for executeSpoolerTask else if(check("removeRemoteClientTask", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveSpoolerTask(); else if(check("executeSpoolerTask", ACCESS_FREE) && check2(ACCESS_WRITE )) doExecuteSpoolerTask(); // alias for executeSpoolerTask else if(check("executeRemoteClientTask",ACCESS_FREE) && check2(ACCESS_WRITE )) doExecuteSpoolerTask(); else if(check("removemailserver", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveMailServer(); else if(check("removemapping", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveMapping(); else if(check("removecustomtag", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveCustomTag(); else if(check("removecomponentmapping", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveComponentMapping(); else if(check("removecfx", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveCFX(); else if(check("removeExtension", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveExtension(); else if(check("removeExtensionProvider",ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveExtensionProvider(); else if(check("removeRHExtensionProvider",ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveRHExtensionProvider(); else if(check("removeDefaultPassword", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveDefaultPassword(); else if(check("removeGatewayEntry", ACCESS_NOT_WHEN_SERVER) && check2(ACCESS_WRITE )) doRemoveGatewayEntry(); else if(check("removeDebugEntry", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveDebugEntry(); else if(check("removeCacheDefaultConnection",ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveCacheDefaultConnection(); else if(check("removeLogSetting",ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveLogSetting(); else if(check("storageGet", ACCESS_FREE) && check2(ACCESS_READ )) doStorageGet(); else if(check("storageSet", ACCESS_FREE) && check2(ACCESS_WRITE )) doStorageSet(); else if(check("getdefaultpassword", ACCESS_FREE) && check2(ACCESS_READ )) doGetDefaultPassword(); else if(check("getContexts", ACCESS_FREE) && check2(ACCESS_READ )) doGetContexts(); else if(check("getContextes", ACCESS_FREE) && check2(ACCESS_READ )) doGetContexts(); else if(check("updatedefaultpassword", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateDefaultPassword(); else if(check("hasindividualsecurity", ACCESS_FREE) && check2(ACCESS_READ )) doHasIndividualSecurity(); else if(check("resetpassword", ACCESS_FREE) && check2(ACCESS_WRITE )) doResetPassword(); else if(check("stopThread", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doStopThread(); else if(check("updateAuthKey", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateAuthKey(); else if(check("removeAuthKey", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doRemoveAuthKey(); else if(check("listAuthKey", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doListAuthKey(); else if(check("updateAPIKey", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateAPIKey(); else if(check("removeAPIKey", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveAPIKey(); else if(check("getAPIKey", ACCESS_FREE) && check2(ACCESS_READ )) doGetAPIKey(); else if(check("createsecuritymanager", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doCreateSecurityManager(); else if(check("getsecuritymanager", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ )) doGetSecurityManager(); else if(check("removesecuritymanager", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doRemoveSecurityManager(); else if(check("getdefaultsecuritymanager",ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ )) doGetDefaultSecurityManager(); else if(check("updatesecuritymanager", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateSecurityManager(); else if(check("updatedefaultsecuritymanager",ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateDefaultSecurityManager(); else if(check("compileMapping", ACCESS_FREE) && check2(ACCESS_WRITE )) doCompileMapping(); else if(check("compileComponentMapping", ACCESS_FREE) && check2(ACCESS_WRITE )) doCompileComponentMapping(); else if(check("compileCTMapping", ACCESS_FREE) && check2(ACCESS_WRITE )) doCompileCTMapping(); else if(check("createArchive", ACCESS_FREE) && check2(ACCESS_WRITE )) doCreateArchive(MAPPING_REGULAR); else if(check("createComponentArchive", ACCESS_FREE) && check2(ACCESS_WRITE )) doCreateArchive(MAPPING_CFC); else if(check("createCTArchive", ACCESS_FREE) && check2(ACCESS_WRITE )) doCreateArchive(MAPPING_CT); else if(check("reload", ACCESS_FREE) && check2(ACCESS_WRITE )) doReload(); else if(check("getResourceProviders", ACCESS_FREE) && check2(ACCESS_READ )) doGetResourceProviders(); else if(check("updateResourceProvider", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateResourceProvider(); else if(check("updateDefaultResourceProvider", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateDefaultResourceProvider(); else if(check("removeResourceProvider", ACCESS_FREE) && check2(ACCESS_WRITE )) doRemoveResourceProvider(); else if(check("getClusterClass", ACCESS_FREE) && check2(ACCESS_READ )) doGetClusterClass(); else if(check("updateClusterClass", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateClusterClass(); else if(check("getAdminSyncClass", ACCESS_FREE) && check2(ACCESS_READ )) doGetAdminSyncClass(); else if(check("updateAdminSyncClass", ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateAdminSyncClass(); else if(check("getVideoExecuterClass", ACCESS_FREE) && check2(ACCESS_READ )) doGetVideoExecuterClass(); else if(check("updateVideoExecuterClass",ACCESS_FREE) && check2(ACCESS_WRITE )) doUpdateVideoExecuterClass(); else if(check("terminateRunningThread",ACCESS_FREE) && check2(ACCESS_WRITE )) doTerminateRunningThread(); else if(check("updateLabel", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateLabel(); else if(check("restart", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doRestart(); else if(check("runUpdate", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doRunUpdate(); else if(check("removeUpdate", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doRemoveUpdate(); else if(check("getUpdate", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doGetUpdate(); else if(check("listPatches", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ )) listPatches(); else if(check("updateupdate", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateUpdate(); else if(check("getSerial", ACCESS_FREE) && check2(ACCESS_READ )) doGetSerial(); else if(check("updateSerial", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doUpdateSerial(); else if(check("heapDump", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE )) doHeapDump(); else if(check("securitymanager", ACCESS_FREE) && check2(ACCESS_READ )) doSecurityManager(); else throw new ApplicationException("invalid action ["+action+"] for tag admin"); } private boolean check2(short accessRW) throws SecurityException { if(accessRW==ACCESS_READ) ConfigWebUtil.checkGeneralReadAccess(config,password); else if(accessRW==ACCESS_WRITE) ConfigWebUtil.checkGeneralWriteAccess(config,password); /*else if(accessRW==CHECK_PW) { ConfigWebUtil.checkGeneralReadAccess(config,password); ConfigWebUtil.checkPassword(config,null,password); }*/ return true; } private boolean check(String action, short access) throws ApplicationException { if( this.action.equalsIgnoreCase(action)) { if(access==ACCESS_FREE) { } else if(access==ACCESS_NOT_WHEN_SERVER) { throwNoAccessWhenServer(); } else if(access==ACCESS_NOT_WHEN_WEB) { throwNoAccessWhenWeb(); } else if(access==ACCESS_NEVER) { throwNoAccessWhenServer(); throwNoAccessWhenServer(); } return true; } return false; } private void doRunUpdate() throws PageException { admin.runUpdate(password); adminSync.broadcast(attributes, config); } private void doRemoveUpdate() throws PageException { boolean onlyLatest = getBoolV("onlyLatest", false); if(onlyLatest) admin.removeLatestUpdate(password); else admin.removeUpdate(password); adminSync.broadcast(attributes, config); } private void doRestart() throws PageException { admin.restart(password); adminSync.broadcast(attributes, config); } private void doCreateArchive(short mappingType) throws PageException { String virtual = getString("admin",action,"virtual").toLowerCase(); String strFile = getString("admin",action,"file"); Resource file = ResourceUtil.toResourceNotExisting(pageContext, strFile); boolean addCFMLFiles = getBoolV("addCFMLFiles", true); boolean addNonCFMLFiles=getBoolV("addNonCFMLFiles", true); // compile MappingImpl mapping = (MappingImpl) doCompileMapping(mappingType,virtual, true); // class files if(mapping==null)throw new ApplicationException("there is no mapping for ["+virtual+"]"); if(!mapping.hasPhysical())throw new ApplicationException("mapping ["+virtual+"] has no physical directory"); Resource classRoot = mapping.getClassRootDirectory(); Resource temp = SystemUtil.getTempDirectory().getRealResource("mani-"+IDGenerator.stringId()); Resource mani = temp.getRealResource("META-INF/MANIFEST.MF"); try { if(file.exists())file.delete(); if(!file.exists())file.createFile(true); ResourceFilter filter; // include everything, no filter needed if(addCFMLFiles && addNonCFMLFiles)filter=null; // CFML Files but no other files else if(addCFMLFiles) { if(mappingType==MAPPING_CFC)filter=new ExtensionResourceFilter( ArrayUtil.toArray(Constants.getComponentExtensions(), "class","MF") ,true,true); else filter=new ExtensionResourceFilter(ArrayUtil.toArray(Constants.getExtensions(), "class","MF"),true,true); } // No CFML Files, but all other files else if(addNonCFMLFiles) { filter=new NotResourceFilter(new ExtensionResourceFilter(Constants.getExtensions(),false,true)); } // no files at all else { filter=new ExtensionResourceFilter(new String[]{"class","MF"},true,true); } String id = HashUtil.create64BitHashAsString(mapping.getStrPhysical(), Character.MAX_RADIX); //String id = MD5.getDigestAsString(mapping.getStrPhysical()); String type; if(mappingType==MAPPING_CFC)type="cfc"; else if(mappingType==MAPPING_CT)type="ct"; else type="regular"; String token = HashUtil.create64BitHashAsString(System.currentTimeMillis()+"", Character.MAX_RADIX); // create manifest Manifest mf=new Manifest(); //StringBuilder manifest=new StringBuilder(); // Write OSGi specific stuff Attributes attrs = mf.getMainAttributes(); attrs.putValue("Bundle-ManifestVersion", Caster.toString(BundleBuilderFactory.MANIFEST_VERSION)); attrs.putValue("Bundle-SymbolicName",id); attrs.putValue("Bundle-Name",ListUtil.trim(mapping.getVirtual().replace('/', '.'),".")); attrs.putValue("Bundle-Description","this is a "+type+" mapping generated by "+Constants.NAME+"."); attrs.putValue("Bundle-Version","1.0.0."+token); //attrs.putValue("Import-Package","lucee.*"); attrs.putValue("Require-Bundle","lucee.core"); // Mapping attrs.putValue("mapping-id",id); attrs.putValue("mapping-type",type); attrs.putValue("mapping-virtual-path",mapping.getVirtual()); attrs.putValue("mapping-hidden",Caster.toString(mapping.isHidden())); attrs.putValue("mapping-physical-first",Caster.toString(mapping.isPhysicalFirst())); attrs.putValue("mapping-readonly",Caster.toString(mapping.isReadonly())); attrs.putValue("mapping-top-level",Caster.toString(mapping.isTopLevel())); attrs.putValue("mapping-inspect",ConfigWebUtil.inspectTemplate(mapping.getInspectTemplateRaw(), "")); mani.createFile(true); IOUtil.write(mani, ManifestUtil.toString(mf, 100, null, null), "UTF-8", false); // source files Resource[] sources; if(!addCFMLFiles && !addNonCFMLFiles) sources=new Resource[]{temp,classRoot}; else sources=new Resource[]{temp,mapping.getPhysical(),classRoot}; CompressUtil.compressZip(ResourceUtil.listResources(sources,filter), file, filter); if(getBoolV("append", false)) { if(mappingType==MAPPING_CFC) { admin.updateComponentMapping( mapping.getVirtual(), mapping.getStrPhysical(), strFile, mapping.isPhysicalFirst()?"physical":"archive", mapping.getInspectTemplateRaw()); } else if(mappingType==MAPPING_CT) { admin.updateCustomTag( mapping.getVirtual(), mapping.getStrPhysical(), strFile, mapping.isPhysicalFirst()?"physical":"archive", mapping.getInspectTemplateRaw()); } else admin.updateMapping( mapping.getVirtual(), mapping.getStrPhysical(), strFile, mapping.isPhysicalFirst()?"physical":"archive", mapping.getInspectTemplateRaw(), mapping.isTopLevel() ); store(); } } catch (IOException e) { throw Caster.toPageException(e); } finally{ ResourceUtil.removeEL(temp, true); } adminSync.broadcast(attributes, config); } private void doCompileMapping() throws PageException { doCompileMapping(MAPPING_REGULAR,getString("admin",action,"virtual").toLowerCase(), getBoolV("stoponerror", true)); adminSync.broadcast(attributes, config); } private void doCompileComponentMapping() throws PageException { doCompileMapping(MAPPING_CFC,getString("admin",action,"virtual").toLowerCase(), getBoolV("stoponerror", true)); adminSync.broadcast(attributes, config); } private void doCompileCTMapping() throws PageException { doCompileMapping(MAPPING_CT,getString("admin",action,"virtual").toLowerCase(), getBoolV("stoponerror", true)); adminSync.broadcast(attributes, config); } private Mapping doCompileMapping(short mappingType,String virtual, boolean stoponerror) throws PageException { if(StringUtil.isEmpty(virtual))return null; if(!StringUtil.startsWith(virtual,'/'))virtual='/'+virtual; if(!StringUtil.endsWith(virtual,'/'))virtual+='/'; Mapping[] mappings = null; if(mappingType==MAPPING_CFC)mappings=config.getComponentMappings(); else if(mappingType==MAPPING_CT)mappings=config.getCustomTagMappings(); else mappings=config.getMappings(); for(int i=0;i<mappings.length;i++) { Mapping mapping = mappings[i]; if(mapping.getVirtualLowerCaseWithSlash().equals(virtual)) { Map<String,String> errors = stoponerror?null:MapFactory.<String,String>getConcurrentMap(); doCompileFile(mapping,mapping.getPhysical(),"",errors); if(errors!=null && errors.size()>0) { StringBuilder sb=new StringBuilder(); Iterator<String> it = errors.keySet().iterator(); Object key; while(it.hasNext()) { key=it.next(); if(sb.length()>0)sb.append("\n\n"); sb.append(errors.get(key)); } throw new ApplicationException(sb.toString()); } return mapping; } } return null; } private void doCompileFile(Mapping mapping,Resource file,String path,Map<String,String> errors) throws PageException { if(ResourceUtil.exists(file)) { if(file.isDirectory()) { Resource[] files = file.listResources(FILTER_CFML_TEMPLATES); if(files!=null)for(int i=0;i<files.length;i++) { String p=path+'/'+files[i].getName(); //print.ln(files[i]+" - "+p); doCompileFile(mapping,files[i],p,errors); } } else if(file.isFile()) { PageSourceImpl ps=(PageSourceImpl) mapping.getPageSource(path); try { ps.clear(); ps.loadPage(pageContext,false); //pageContext.compile(ps); } catch (PageException pe) { //PageException pe = pse.getPageException(); String template=ps.getDisplayPath(); StringBuilder msg=new StringBuilder(pe.getMessage()); msg.append(", Error Occurred in File ["); msg.append(template); if(pe instanceof PageExceptionImpl) { try{ PageExceptionImpl pei=(PageExceptionImpl)pe; Array context = pei.getTagContext(config); if(context.size()>0){ msg.append(":"); msg.append(Caster.toString(((Struct)context.getE(1)).get("line"))); } } catch(Throwable t){} } msg.append("]"); if(errors!=null) errors.put(template,msg.toString()); else throw new ApplicationException(msg.toString()); } } } } /** * @throws PageException * */ private void doResetPassword() throws PageException { try { admin.removePassword(getString("contextPath",null)); }catch (Exception e) {e.printStackTrace();} store(); } private void doUpdateAPIKey() throws PageException { admin.updateAPIKey(getString("key",null)); store(); } private void doRemoveAPIKey() throws PageException { try { admin.removeAPIKey(); }catch (Exception e) {} store(); } private void doGetAPIKey() throws PageException { pageContext.setVariable( getString("admin",action,"returnVariable"), config.getIdentification().getApiKey()); } private void doUpdateAuthKey() throws PageException { try { admin.updateAuthKey(getString("key",null)); }catch (Exception e) {} store(); } private void doRemoveAuthKey() throws PageException { try { admin.removeAuthKeys(getString("key",null)); }catch (Exception e) {} store(); } private void doListAuthKey() throws PageException { ConfigServerImpl cs=(ConfigServerImpl) config; pageContext.setVariable( getString("admin",action,"returnVariable"), Caster.toArray(cs.getAuthenticationKeys())); } /** * @throws PageException */ private void doGetContexts() throws PageException { CFMLFactory[] factories; if(config instanceof ConfigServerImpl) { ConfigServerImpl cs=(ConfigServerImpl) config; factories = cs.getJSPFactories(); } else { ConfigWebImpl cw=(ConfigWebImpl) config; factories = new CFMLFactory[]{cw.getFactory()}; } lucee.runtime.type.Query qry= new QueryImpl( new Collection.Key[]{ KeyConstants._path, KeyConstants._id,KeyConstants._hash, KeyConstants._label, HAS_OWN_SEC_CONTEXT, KeyConstants._url, CONFIG_FILE, CLIENT_SIZE,CLIENT_ELEMENTS,SESSION_SIZE,SESSION_ELEMENTS}, factories.length,getString("admin",action,"returnVariable")); pageContext.setVariable(getString("admin",action,"returnVariable"),qry); ConfigWebImpl cw; for(int i=0;i<factories.length;i++) { int row=i+1; CFMLFactoryImpl factory = (CFMLFactoryImpl) factories[i]; cw = (ConfigWebImpl) factory.getConfig(); qry.setAtEL(KeyConstants._path,row,ReqRspUtil.getRootPath(factory.getConfigWebImpl().getServletContext())); qry.setAtEL(CONFIG_FILE,row,factory.getConfigWebImpl().getConfigFile().getAbsolutePath()); if(factory.getURL()!=null)qry.setAtEL(KeyConstants._url,row,factory.getURL().toExternalForm()); qry.setAtEL(KeyConstants._id,row,factory.getConfig().getIdentification().getId()); qry.setAtEL(KeyConstants._hash,row,SystemUtil.hash(factory.getConfigWebImpl().getServletContext())); qry.setAtEL(KeyConstants._label,row,factory.getLabel()); qry.setAtEL(HAS_OWN_SEC_CONTEXT,row,Caster.toBoolean(cw.hasIndividualSecurityManager())); setScopeDirInfo(qry,row,CLIENT_SIZE,CLIENT_ELEMENTS,cw.getClientScopeDir()); setScopeDirInfo(qry,row,SESSION_SIZE,SESSION_ELEMENTS,cw.getSessionScopeDir()); } } private void setScopeDirInfo(Query qry, int row, Key sizeName,Key elName, Resource dir) { qry.setAtEL(sizeName,row,Caster.toDouble(ResourceUtil.getRealSize(dir))); qry.setAtEL(elName,row,Caster.toDouble(ResourceUtil.getChildCount(dir))); } private void doHasIndividualSecurity() throws PageException { pageContext.setVariable( getString("admin",action,"returnVariable"), Caster.toBoolean( pageContext.getConfig().getConfigServer(password).hasIndividualSecurityManager( getString("admin",action,"id") ) ) ); } private void doUpdateUpdate() throws PageException { admin.updateUpdate(getString("admin",action,"updatetype"),getString("admin",action,"updatelocation")); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doUpdateSerial() throws PageException { admin.updateSerial(getString("admin",action,"serial")); store(); pageContext.serverScope().reload(); } /** * @throws PageException * */ private void doGetSerial() throws PageException { pageContext.setVariable( getString("admin",action,"returnVariable"), config.getSerialNumber()); } private Resource getContextDirectory() throws PageException { ConfigServerImpl cs=(ConfigServerImpl) ConfigImpl.getConfigServer(config,password); Resource dist = cs.getConfigDir().getRealResource("distribution"); dist.mkdirs(); return dist; } private void doGetPluginDirectory() throws PageException { pageContext.setVariable( getString("admin",action,"returnVariable"), config.getPluginDirectory().getAbsolutePath()); } private void doUpdatePlugin() throws PageException, IOException{ String strSrc = getString("admin",action,"source"); Resource src = ResourceUtil.toResourceExisting(pageContext, strSrc); admin.updatePlugin(pageContext,src); store(); } private void doUpdateLabel() throws PageException { if(config instanceof ConfigServer) { if(admin.updateLabel(getString("admin",action,"hash"),getString("admin",action,"label"))) { store(); adminSync.broadcast(attributes, config); } } } private void doUpdateContext() throws PageException, IOException { String strSrc = getString("admin",action,"source"); String strRealpath = getString("admin",action,"destination"); Resource src = ResourceUtil.toResourceExisting(pageContext, strSrc); ConfigServerImpl server=(ConfigServerImpl) ConfigImpl.getConfigServer(config,password); Resource trg,p; Resource deploy = server.getConfigDir().getRealResource("web-context-deployment"); deploy.mkdirs(); // deploy it trg=deploy.getRealResource(strRealpath); if(trg.exists()) trg.remove(true); p = trg.getParentResource(); if(!p.isDirectory())p.createDirectory(true); src.copyTo(trg, false); store(); ConfigWeb[] webs = server.getConfigWebs(); for(int i=0;i<webs.length;i++){ ConfigWebFactory.deployWebContext(server,webs[i], true); } } private void doRemoveContext() throws PageException { String strRealpath = getString("admin",action,"destination"); ConfigServerImpl server = (ConfigServerImpl) config; try { admin.removeContext(server, true,strRealpath); } catch (Throwable t) { throw Caster.toPageException(t); } store(); } private void doRemovePlugin() throws PageException, IOException { Resource dir = config.getPluginDirectory(); String name = getString("admin",action,"name"); Resource trgDir = dir.getRealResource(name); trgDir.remove(true); store(); } private void doGetPlugins() throws PageException { Resource dir = config.getPluginDirectory(); String[] list = dir.list(new ConfigWebAdmin.PluginFilter()); lucee.runtime.type.Query qry= new QueryImpl( new Collection.Key[]{KeyConstants._name}, list.length,getString("admin",action,"returnVariable")); pageContext.setVariable(getString("admin",action,"returnVariable"),qry); for(int i=0;i<list.length;i++) { int row=i+1; qry.setAtEL(KeyConstants._name,row,list[i]); } } private void doStorageSet() throws PageException { try { admin.storageSet(config,getString("admin",action,"key"),getObject("admin", action, "value")); } catch (Exception e) { throw Caster.toPageException(e); } } private void doStorageGet() throws PageException { try { pageContext.setVariable( getString("admin",action,"returnVariable"), admin.storageGet(config,getString("admin",action,"key"))); } catch (Exception e) { throw Caster.toPageException(e); } } /** * @throws PageException * */ private void doGetDefaultPassword() throws PageException { Password password = admin.getDefaultPassword(); pageContext.setVariable( getString("admin",action,"returnVariable"), password==null?"":password.getPassword()); } /** * @throws PageException * */ private void doUpdateDefaultPassword() throws PageException { try { admin.updateDefaultPassword(getString("admin",action,"newPassword")); } catch (Exception e) { throw Caster.toPageException(e); } store(); } private void doRemoveDefaultPassword() throws PageException { admin.removeDefaultPassword(); store(); } /* * * @throws PageException * * / private void doUpdatePassword() throws PageException { try { ConfigWebAdmin.setPassword(config,password==null?null:Caster.toString(password),getString("admin",action,"newPassword")); } catch (Exception e) { throw Caster.toPageException(e); } //store(); }*/ /** * @throws PageException * */ private void doGetDebug() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); sct.set(DEBUG,Caster.toBoolean(config.debug())); sct.set(KeyConstants._database,Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_DATABASE))); sct.set(KeyConstants._exception,Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION))); sct.set("tracing",Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_TRACING))); sct.set("dump",Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_DUMP))); sct.set("timer",Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_TIMER))); sct.set("implicitAccess",Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_IMPLICIT_ACCESS))); sct.set("queryUsage",Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_QUERY_USAGE))); } private void doGetError() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); //sct.set("errorTemplate",config.getErrorTemplate()); Struct templates=new StructImpl(); Struct str=new StructImpl(); sct.set(TEMPLATES, templates); sct.set(STR, str); sct.set(DO_STATUS_CODE, Caster.toBoolean(config.getErrorStatusCode())); // 500 String template=config.getErrorTemplate(500); try { PageSource ps = ((PageContextImpl)pageContext).getPageSourceExisting(template); if(ps!=null) templates.set("500",ps.getDisplayPath()); else templates.set("500",""); } catch (PageException e) { templates.set("500",""); } str.set("500",template); // 404 template=config.getErrorTemplate(404); try { PageSource ps = ((PageContextImpl)pageContext).getPageSourceExisting(template); if(ps!=null) templates.set("404",ps.getDisplayPath()); else templates.set("404",""); } catch (PageException e) { templates.set("404",""); } str.set("404",template); } /** * @throws PageException * */ private void doGetDebugData() throws PageException { pageContext.setVariable( getString("admin",action,"returnVariable"), pageContext.getConfig().debug()?pageContext.getDebugger().getDebuggingData(pageContext):null); } private void doGetLoggedDebugData() throws PageException { if(config instanceof ConfigServer) return ; ConfigWebImpl cw=(ConfigWebImpl) config; pageContext.setVariable( getString("admin",action,"returnVariable"), cw.getDebuggerPool().getData(pageContext)); } private void doGetInfo() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable( getString("admin",action,"returnVariable"), sct); if(config instanceof ConfigWebImpl){ ConfigWebImpl cw=(ConfigWebImpl) config; sct.setEL(KeyConstants._label, cw.getLabel()); sct.setEL(KeyConstants._hash, cw.getHash()); sct.setEL(KeyConstants._root, cw.getRootDirectory().getAbsolutePath()); sct.setEL("configServerDir", cw.getConfigServerDir().getAbsolutePath()); sct.setEL("configWebDir", cw.getConfigDir().getAbsolutePath()); } else { sct.setEL("configServerDir", config.getConfigDir().getAbsolutePath()); sct.setEL("configWebDir", pageContext.getConfig().getConfigDir().getAbsolutePath()); } sct.setEL(KeyConstants._config, config.getConfigFile().getAbsolutePath()); // Servlets if(config instanceof ConfigServer) { ConfigServer cs=(ConfigServer) config; CFMLEngineImpl engine = (CFMLEngineImpl) cs.getCFMLEngine(); Struct srv=new StructImpl(),params; ServletConfig[] configs = engine.getServletConfigs(); ServletConfig sc; Enumeration e; String name,value; for(int i=0;i<configs.length;i++){ sc=configs[i]; e = sc.getInitParameterNames(); params=new StructImpl(); while(e.hasMoreElements()){ name=(String) e.nextElement(); value = sc.getInitParameter(name); params.set(name, value); } srv.set(sc.getServletName(), params); } sct.set("servlets", srv); } //sct.setEL("javaAgentSupported", Caster.toBoolean(InstrumentationUtil.isSupported())); sct.setEL("javaAgentSupported", Boolean.TRUE); //sct.setEL("javaAgentPath", ClassUtil.getSourcePathForClass("lucee.runtime.instrumentation.Agent", "")); } /** * @throws PageException * */ private void doCreateSecurityManager() throws PageException { admin.createSecurityManager(password,getString("admin",action,"id")); store(); } private void doRemoveSecurityManager() throws PageException { admin.removeSecurityManager(password,getString("admin",action,"id")); store(); } private short fb(String key) throws PageException { return getBool("admin",action,key)?SecurityManager.VALUE_YES:SecurityManager.VALUE_NO; } private short fb2(String key) throws PageException { return SecurityManagerImpl.toShortAccessRWValue(getString("admin",action,key)); } private void doUpdateDefaultSecurityManager() throws PageException { admin.updateDefaultSecurity( fb("setting"), SecurityManagerImpl.toShortAccessValue(getString("admin",action,"file")), getFileAcces(), fb("direct_java_access"), fb("mail"), SecurityManagerImpl.toShortAccessValue(getString("admin",action,"datasource")), fb("mapping"), fb("remote"), fb("custom_tag"), fb("cfx_setting"), fb("cfx_usage"), fb("debugging"), fb("search"), fb("scheduled_task"), fb("tag_execute"), fb("tag_import"), fb("tag_object"), fb("tag_registry"), fb("cache"), fb("gateway"), fb("orm"), fb2("access_read"), fb2("access_write") ); store(); adminSync.broadcast(attributes, config); } private Resource[] getFileAcces() throws PageException { Object value=attributes.get(FILE_ACCESS,null); if(value==null) return null; Array arr = Caster.toArray(value); List rtn = new ArrayList(); Iterator it = arr.valueIterator(); String path; Resource res; while(it.hasNext()){ path=Caster.toString(it.next()); if(StringUtil.isEmpty(path))continue; res=config.getResource(path); if(!res.exists()) throw new ApplicationException("path ["+path+"] does not exist"); if(!res.isDirectory()) throw new ApplicationException("path ["+path+"] is not a directory"); rtn.add(res); } return (Resource[])rtn.toArray(new Resource[rtn.size()]); } private void doUpdateSecurityManager() throws PageException { admin.updateSecurity( getString("admin",action,"id"), fb("setting"), SecurityManagerImpl.toShortAccessValue(getString("admin",action,"file")), getFileAcces(), fb("direct_java_access"), fb("mail"), SecurityManagerImpl.toShortAccessValue(getString("admin",action,"datasource")), fb("mapping"), fb("remote"), fb("custom_tag"), fb("cfx_setting"), fb("cfx_usage"), fb("debugging"), fb("search"), fb("scheduled_task"), fb("tag_execute"), fb("tag_import"), fb("tag_object"), fb("tag_registry"), fb("cache"), fb("gateway"), fb("orm"), fb2("access_read"), fb2("access_write") ); store(); } /** * @throws PageException * */ private void doGetDefaultSecurityManager() throws PageException { ConfigServer cs=ConfigImpl.getConfigServer(config,password); SecurityManager dsm = cs.getDefaultSecurityManager(); _fillSecData(dsm); } private void doGetSecurityManager() throws PageException { ConfigServer cs=ConfigImpl.getConfigServer(config,password); SecurityManager sm = cs.getSecurityManager(getString("admin",action,"id")); _fillSecData(sm); } private void _fillSecData(SecurityManager sm) throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); sct.set("cfx_setting",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_CFX_SETTING)==SecurityManager.VALUE_YES)); sct.set("cfx_usage",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_CFX_USAGE)==SecurityManager.VALUE_YES)); sct.set("custom_tag",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_CUSTOM_TAG)==SecurityManager.VALUE_YES)); sct.set(KeyConstants._datasource,_fillSecDataDS(sm.getAccess(SecurityManager.TYPE_DATASOURCE))); sct.set("debugging",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_DEBUGGING)==SecurityManager.VALUE_YES)); sct.set("direct_java_access",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_DIRECT_JAVA_ACCESS)==SecurityManager.VALUE_YES)); sct.set("mail",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_MAIL)==SecurityManager.VALUE_YES)); sct.set(KeyConstants._mapping,Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_MAPPING)==SecurityManager.VALUE_YES)); sct.set("remote",Caster.toBoolean(sm.getAccess(SecurityManagerImpl.TYPE_REMOTE)==SecurityManager.VALUE_YES)); sct.set("setting",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_SETTING)==SecurityManager.VALUE_YES)); sct.set("search",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_SEARCH)==SecurityManager.VALUE_YES)); sct.set("scheduled_task",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_SCHEDULED_TASK)==SecurityManager.VALUE_YES)); sct.set(KeyConstants._cache,Caster.toBoolean(sm.getAccess(SecurityManagerImpl.TYPE_CACHE)==SecurityManager.VALUE_YES)); sct.set("gateway",Caster.toBoolean(sm.getAccess(SecurityManagerImpl.TYPE_GATEWAY)==SecurityManager.VALUE_YES)); sct.set(KeyConstants._orm,Caster.toBoolean(sm.getAccess(SecurityManagerImpl.TYPE_ORM)==SecurityManager.VALUE_YES)); sct.set("tag_execute",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_TAG_EXECUTE)==SecurityManager.VALUE_YES)); sct.set("tag_import",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_TAG_IMPORT)==SecurityManager.VALUE_YES)); sct.set("tag_object",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_TAG_OBJECT)==SecurityManager.VALUE_YES)); sct.set("tag_registry",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_TAG_REGISTRY)==SecurityManager.VALUE_YES)); sct.set("access_read",SecurityManagerImpl.toStringAccessRWValue(sm.getAccess(SecurityManager.TYPE_ACCESS_READ))); sct.set("access_write",SecurityManagerImpl.toStringAccessRWValue(sm.getAccess(SecurityManager.TYPE_ACCESS_WRITE))); short accessFile = sm.getAccess(SecurityManager.TYPE_FILE); String str = SecurityManagerImpl.toStringAccessValue(accessFile); if(str.equals("yes"))str="all"; sct.set(KeyConstants._file,str); Array arr=new ArrayImpl(); if(accessFile!=SecurityManager.VALUE_ALL){ Resource[] reses = ((SecurityManagerImpl)sm).getCustomFileAccess(); for(int i=0;i<reses.length;i++){ arr.appendEL(reses[i].getAbsolutePath()); } } sct.set("file_access",arr); } private Double _fillSecDataDS(short access) { switch(access) { case SecurityManager.VALUE_YES: return Caster.toDouble(-1); case SecurityManager.VALUE_NO: return Caster.toDouble(0); case SecurityManager.VALUE_1: return Caster.toDouble(1); case SecurityManager.VALUE_2: return Caster.toDouble(2); case SecurityManager.VALUE_3: return Caster.toDouble(3); case SecurityManager.VALUE_4: return Caster.toDouble(4); case SecurityManager.VALUE_5: return Caster.toDouble(5); case SecurityManager.VALUE_6: return Caster.toDouble(6); case SecurityManager.VALUE_7: return Caster.toDouble(7); case SecurityManager.VALUE_8: return Caster.toDouble(8); case SecurityManager.VALUE_9: return Caster.toDouble(9); case SecurityManager.VALUE_10: return Caster.toDouble(10); } return Caster.toDouble(-1); } /** * @throws PageException * */ private void doUpdateDebug() throws PageException { admin.updateDebug( Caster.toBoolean(getString("debug",""),null), Caster.toBoolean(getString("database",""),null), Caster.toBoolean(getString("exception",""),null), Caster.toBoolean(getString("tracing",""),null), Caster.toBoolean(getString("dump",""),null), Caster.toBoolean(getString("timer",""),null), Caster.toBoolean(getString("implicitAccess",""),null), Caster.toBoolean(getString("queryUsage",""),null) ); admin.updateDebugTemplate(getString("admin",action,"debugTemplate")); store(); adminSync.broadcast(attributes, config); } private void doGetDebugSetting() throws PageException { Struct sct=new StructImpl(); sct.set("maxLogs", Caster.toDouble(config.getDebugMaxRecordsLogged())); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); } private void doUpdateDebugSetting() throws PageException { String str = getString("admin",action,"maxLogs"); int maxLogs; if(StringUtil.isEmpty(str,true))maxLogs=-1; else maxLogs=Caster.toIntValue(str); admin.updateDebugSetting(maxLogs); store(); adminSync.broadcast(attributes, config); } private void doUpdateDebugEntry() throws PageException { try { admin.updateDebugEntry( getString("admin","updateDebugEntry","debugtype"), getString("admin","updateDebugEntry","iprange"), getString("admin","updateDebugEntry","label"), getString("admin","updateDebugEntry","path"), getString("admin","updateDebugEntry","fullname"), getStruct("admin","updateDebugEntry","custom") ); } catch (IOException e) { throw Caster.toPageException(e); } store(); adminSync.broadcast(attributes, config); } private void doGetDebugEntry() throws PageException { DebugEntry[] entries = config.getDebugEntries(); String rtn = getString("admin",action,"returnVariable"); lucee.runtime.type.Query qry= new QueryImpl(new Collection.Key[]{KeyConstants._id,LABEL,IP_RANGE,READONLY,KeyConstants._type,CUSTOM},entries.length,rtn); pageContext.setVariable(rtn,qry); DebugEntry de; for(int i=0;i<entries.length;i++) { int row=i+1; de=entries[i]; qry.setAtEL(KeyConstants._id,row,de.getId()); qry.setAtEL(LABEL,row,de.getLabel()); qry.setAtEL(IP_RANGE,row,de.getIpRangeAsString()); qry.setAtEL(KeyConstants._type,row,de.getType()); qry.setAtEL(READONLY,row,Caster.toBoolean(de.isReadOnly())); qry.setAtEL(CUSTOM,row,de.getCustom()); } } private void doUpdateError() throws PageException { admin.updateErrorTemplate(500,getString("admin",action,"template500")); admin.updateErrorTemplate(404,getString("admin",action,"template404")); admin.updateErrorStatusCode(getBoolObject("admin",action,"statuscode")); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doUpdateJavaCFX() throws PageException { String name=getString("admin",action,"name"); if(StringUtil.startsWithIgnoreCase(name,"cfx_"))name=name.substring(4); lucee.runtime.db.ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.updateJavaCFX( name, cd ); store(); adminSync.broadcast(attributes, config); } private void doVerifyJavaCFX() throws PageException { String name=getString("admin",action,"name"); ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.verifyJavaCFX( name, cd ); } private void doVerifyCFX() throws PageException { String name=getString("admin",action,"name"); if(StringUtil.startsWithIgnoreCase(name,"cfx_"))name=name.substring(4); admin.verifyCFX(name); } private void doUpdateCPPCFX() throws PageException { String name=getString("admin",action,"name"); String procedure=getString("admin",action,"procedure"); String serverLibrary=getString("admin",action,"serverLibrary"); boolean keepAlive=getBool("admin",action,"keepAlive"); if(StringUtil.startsWithIgnoreCase(name,"cfx_"))name=name.substring(4); admin.updateCPPCFX(name,procedure,serverLibrary,keepAlive); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doRemoveCFX() throws PageException { admin.removeCFX( getString("admin",action,"name") ); store(); adminSync.broadcast(attributes, config); } private void doRemoveExtension() throws PageException { admin.removeExtension( getString("admin",action,"provider"), getString("admin",action,"id") ); store(); //adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doGetJavaCFXTags() throws PageException { Map map = config.getCFXTagPool().getClasses(); lucee.runtime.type.Query qry=new QueryImpl(new Collection.Key[]{ KeyConstants._displayname, KeyConstants._sourcename, KeyConstants._readonly, KeyConstants._name, KeyConstants._class, KeyConstants._bundleName, KeyConstants._bundleVersion, KeyConstants._isvalid},0,"query"); Iterator it = map.keySet().iterator(); int row=0; while(it.hasNext()) { CFXTagClass tag=(CFXTagClass) map.get(it.next()); if(tag instanceof JavaCFXTagClass) { row++; qry.addRow(1); JavaCFXTagClass jtag =(JavaCFXTagClass) tag; qry.setAt(KeyConstants._displayname,row,tag.getDisplayType()); qry.setAt(KeyConstants._sourcename,row,tag.getSourceName()); qry.setAt(KeyConstants._readonly,row,Caster.toBoolean(tag.isReadOnly())); qry.setAt(KeyConstants._isvalid,row,Caster.toBoolean(tag.isValid())); qry.setAt(KeyConstants._name,row,jtag.getName()); qry.setAt(KeyConstants._class,row,jtag.getClassDefinition().getClassName()); qry.setAt(KeyConstants._bundleName,row,jtag.getClassDefinition().getName()); qry.setAt(KeyConstants._bundleVersion,row,jtag.getClassDefinition().getVersionAsString()); } } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetCPPCFXTags() throws PageException { Map map = config.getCFXTagPool().getClasses(); lucee.runtime.type.Query qry=new QueryImpl(new Collection.Key[]{ KeyConstants._displayname, KeyConstants._sourcename, KeyConstants._readonly, PROCEDURE, KeyConstants._name, KeyConstants._isvalid, SERVER_LIBRARY, KEEP_ALIVE},0,"query"); Iterator it = map.keySet().iterator(); int row=0; while(it.hasNext()) { CFXTagClass tag=(CFXTagClass) map.get(it.next()); if(tag instanceof CPPCFXTagClass) { row++; qry.addRow(1); CPPCFXTagClass ctag =(CPPCFXTagClass) tag; qry.setAt(KeyConstants._displayname,row,tag.getDisplayType()); qry.setAt(KeyConstants._sourcename,row,tag.getSourceName()); qry.setAt(KeyConstants._readonly,row,Caster.toBoolean(tag.isReadOnly())); qry.setAt(KeyConstants._isvalid,row,Caster.toBoolean(tag.isValid())); qry.setAt(KeyConstants._name,row,ctag.getName()); qry.setAt(PROCEDURE,row,ctag.getProcedure()); qry.setAt(SERVER_LIBRARY,row,ctag.getServerLibrary()); qry.setAt(KEEP_ALIVE,row,Caster.toBoolean(ctag.getKeepAlive())); } } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } /** * @throws PageException * */ private void doGetCFXTags() throws PageException { Map map = config.getCFXTagPool().getClasses(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{ "displayname","sourcename","readonly","isvalid","name","procedure_class","procedure_bundleName","procedure_bundleVersion","keep_alive"},map.size(),"query"); Iterator it = map.keySet().iterator(); int row=0; while(it.hasNext()) { row++; CFXTagClass tag=(CFXTagClass) map.get(it.next()); qry.setAt("displayname",row,tag.getDisplayType()); qry.setAt("sourcename",row,tag.getSourceName()); qry.setAt("readonly",row,Caster.toBoolean(tag.isReadOnly())); qry.setAt("isvalid",row,Caster.toBoolean(tag.isValid())); if(tag instanceof CPPCFXTagClass) { CPPCFXTagClass ctag =(CPPCFXTagClass) tag; qry.setAt(KeyConstants._name,row,ctag.getName()); qry.setAt("procedure_class",row,ctag.getProcedure()); qry.setAt("keepalive",row,Caster.toBoolean(ctag.getKeepAlive())); } else if(tag instanceof JavaCFXTagClass) { JavaCFXTagClass jtag =(JavaCFXTagClass) tag; qry.setAt(KeyConstants._name,row,jtag.getName()); qry.setAt("procedure_class",row,jtag.getClassDefinition().getClassName()); qry.setAt("procedure_bundleName",row,jtag.getClassDefinition().getName()); qry.setAt("procedure_bundleVersion",row,jtag.getClassDefinition().getVersionAsString()); } } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } /** * @throws PageException */ private void doUpdateComponentMapping() throws PageException { admin.updateComponentMapping( getString("virtual",""), getString("physical",""), getString("archive",""), getString("primary","physical"), ConfigWebUtil.inspectTemplate(getString("inspect",""), ConfigImpl.INSPECT_UNDEFINED) ); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doRemoveComponentMapping() throws PageException { admin.removeComponentMapping( getString("admin",action,"virtual") ); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException */ private void doUpdateCustomTag() throws PageException { admin.updateCustomTag( getString("admin",action,"virtual"), getString("admin",action,"physical"), getString("admin",action,"archive"), getString("admin",action,"primary"), ConfigWebUtil.inspectTemplate(getString("inspect",""), ConfigImpl.INSPECT_UNDEFINED) ); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doRemoveCustomTag() throws PageException { admin.removeCustomTag( getString("admin",action,"virtual") ); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doGetCustomTagMappings() throws PageException { Mapping[] mappings = config.getCustomTagMappings(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"archive","strarchive","physical","strphysical","virtual","hidden","physicalFirst","readonly","inspect"},mappings.length,"query"); for(int i=0;i<mappings.length;i++) { MappingImpl m=(MappingImpl) mappings[i]; int row=i+1; qry.setAt("archive",row,m.getArchive()); qry.setAt("strarchive",row,m.getStrArchive()); qry.setAt("physical",row,m.getPhysical()); qry.setAt("strphysical",row,m.getStrPhysical()); qry.setAt("virtual",row,m.getVirtual()); qry.setAt("hidden",row,Caster.toBoolean(m.isHidden())); qry.setAt("physicalFirst",row,Caster.toBoolean(m.isPhysicalFirst())); qry.setAt("readonly",row,Caster.toBoolean(m.isReadonly())); qry.setAt("inspect",row,ConfigWebUtil.inspectTemplate(m.getInspectTemplateRaw(), "")); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetComponentMappings() throws PageException { Mapping[] mappings = config.getComponentMappings(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"archive","strarchive","physical","strphysical","virtual","hidden","physicalFirst","readonly","inspect"},mappings.length,"query"); for(int i=0;i<mappings.length;i++) { MappingImpl m=(MappingImpl) mappings[i]; int row=i+1; qry.setAt("archive",row,m.getArchive()); qry.setAt("strarchive",row,m.getStrArchive()); qry.setAt("physical",row,m.getPhysical()); qry.setAt("strphysical",row,m.getStrPhysical()); qry.setAt("virtual",row,m.getVirtual()); qry.setAt("hidden",row,Caster.toBoolean(m.isHidden())); qry.setAt("physicalFirst",row,Caster.toBoolean(m.isPhysicalFirst())); qry.setAt("readonly",row,Caster.toBoolean(m.isReadonly())); qry.setAt("inspect",row,ConfigWebUtil.inspectTemplate(m.getInspectTemplateRaw(), "")); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } /** * @throws PageException * */ private void doRemoveMapping() throws PageException { admin.removeMapping( getString("admin",action,"virtual") ); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doUpdateRestMapping() throws PageException { admin.updateRestMapping( getString("admin",action,"virtual"), getString("admin",action,"physical"), getBool("admin",action,"default") ); store(); adminSync.broadcast(attributes, config); RestUtil.release(config.getRestMappings()); } private void doRemoveRestMapping() throws PageException { admin.removeRestMapping( getString("admin",action,"virtual") ); store(); adminSync.broadcast(attributes, config); RestUtil.release(config.getRestMappings()); } private void doUpdateMapping() throws PageException { admin.updateMapping( getString("admin",action,"virtual"), getString("admin",action,"physical"), getString("admin",action,"archive"), getString("admin",action,"primary"), ConfigWebUtil.inspectTemplate(getString("inspect",""), ConfigImpl.INSPECT_UNDEFINED), Caster.toBooleanValue(getString("toplevel","true")) ); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doGetMapping() throws PageException { Mapping[] mappings = config.getMappings(); Struct sct=new StructImpl(); String virtual=getString("admin",action,"virtual"); for(int i=0;i<mappings.length;i++) { MappingImpl m=(MappingImpl) mappings[i]; if(!m.getVirtual().equals(virtual)) continue; sct.set("archive",m.getArchive()); sct.set("strarchive",m.getStrArchive()); sct.set("physical",m.getPhysical()); sct.set("strphysical",m.getStrPhysical()); sct.set("virtual",m.getVirtual()); sct.set(KeyConstants._hidden,Caster.toBoolean(m.isHidden())); sct.set("physicalFirst",Caster.toBoolean(m.isPhysicalFirst())); sct.set("readonly",Caster.toBoolean(m.isReadonly())); sct.set("inspect",ConfigWebUtil.inspectTemplate(m.getInspectTemplateRaw(), "")); sct.set("toplevel",Caster.toBoolean(m.isTopLevel())); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); return; } throw new ApplicationException("there is no mapping with virtual ["+virtual+"]"); } private void doGetRHExtensionProviders() throws PageException { RHExtensionProvider[] providers = config.getRHExtensionProviders(); lucee.runtime.type.Query qry=new QueryImpl(new Key[]{KeyConstants._url,KeyConstants._readonly},providers.length,"query"); RHExtensionProvider provider; for(int i=0;i<providers.length;i++) { provider=providers[i]; int row=i+1; qry.setAt(KeyConstants._url,row,provider.getURL().toExternalForm()); qry.setAt(KeyConstants._readonly,row,provider.isReadonly()); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetExtensionProviders() throws PageException { ExtensionProvider[] providers = config.getExtensionProviders(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"url","isReadOnly"},providers.length,"query"); ExtensionProvider provider; for(int i=0;i<providers.length;i++) { provider=providers[i]; int row=i+1; //qry.setAt("name",row,provider.getName()); qry.setAt(KeyConstants._url,row,provider.getUrlAsString()); qry.setAt("isReadOnly",row,Caster.toBoolean(provider.isReadOnly())); //qry.setAt("cacheTimeout",row,Caster.toDouble(provider.getCacheTimeout()/1000)); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetExtensionInfo() throws PageException { Resource ed = config.getExtensionDirectory(); Struct sct=new StructImpl(); sct.set(KeyConstants._directory, ed.getPath()); sct.set(KeyConstants._enabled, Caster.toBoolean(config.isExtensionEnabled())); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); } private void doGetExtensions() throws PageException { Extension[] extensions = config.getExtensions(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{ "type","provider","id","config","version","category","description","image","label","name", "author","codename","video","support","documentation","forum","mailinglist","network","created"},0,"query"); String provider=getString("provider",null); String id=getString("id",null); Extension extension; String extProvider,extId; int row=0; for(int i=0;i<extensions.length;i++) { extension=extensions[i]; if(!extension.getType().equalsIgnoreCase("all") && toType(extension.getType(), false)!=type) continue; extProvider=extension.getProvider(); extId=extension.getId(); if(provider!=null && !provider.equalsIgnoreCase(extProvider)) continue; if(id!=null && !id.equalsIgnoreCase(extId)) continue; qry.addRow(); row++; qry.setAt("provider",row,extProvider); qry.setAt(KeyConstants._id,row,extId); qry.setAt(KeyConstants._config,row,extension.getConfig(pageContext)); qry.setAt(KeyConstants._version,row,extension.getVersion()); qry.setAt("category",row,extension.getCategory()); qry.setAt(KeyConstants._description,row,extension.getDescription()); qry.setAt("image",row,extension.getImage()); qry.setAt(KeyConstants._label,row,extension.getLabel()); qry.setAt(KeyConstants._name,row,extension.getName()); qry.setAt(KeyConstants._author,row,extension.getAuthor()); qry.setAt("codename",row,extension.getCodename()); qry.setAt("video",row,extension.getVideo()); qry.setAt("support",row,extension.getSupport()); qry.setAt("documentation",row,extension.getDocumentation()); qry.setAt("forum",row,extension.getForum()); qry.setAt("mailinglist",row,extension.getMailinglist()); qry.setAt("network",row,extension.getNetwork()); qry.setAt(KeyConstants._created,row,extension.getCreated()); qry.setAt(KeyConstants._type,row,extension.getType()); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetMappings() throws PageException { Mapping[] mappings = config.getMappings(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"archive","strarchive","physical","strphysical","virtual","hidden","physicalFirst","readonly","inspect","toplevel"},mappings.length,"query"); for(int i=0;i<mappings.length;i++) { MappingImpl m=(MappingImpl) mappings[i]; int row=i+1; qry.setAt("archive",row,m.getArchive()); qry.setAt("strarchive",row,m.getStrArchive()); qry.setAt("physical",row,m.getPhysical()); qry.setAt("strphysical",row,m.getStrPhysical()); qry.setAt("virtual",row,m.getVirtual()); qry.setAt("hidden",row,Caster.toBoolean(m.isHidden())); qry.setAt("physicalFirst",row,Caster.toBoolean(m.isPhysicalFirst())); qry.setAt("readonly",row,Caster.toBoolean(m.isReadonly())); qry.setAt("inspect",row,ConfigWebUtil.inspectTemplate(m.getInspectTemplateRaw(), "")); qry.setAt("toplevel",row,Caster.toBoolean(m.isTopLevel())); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetRestMappings() throws PageException { lucee.runtime.rest.Mapping[] mappings = config.getRestMappings(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"physical","strphysical","virtual","hidden","readonly","default"},mappings.length,"query"); lucee.runtime.rest.Mapping m; for(int i=0;i<mappings.length;i++) { m=mappings[i]; int row=i+1; qry.setAt("physical",row,m.getPhysical()); qry.setAt("strphysical",row,m.getStrPhysical()); qry.setAt("virtual",row,m.getVirtual()); qry.setAt("hidden",row,Caster.toBoolean(m.isHidden())); qry.setAt("readonly",row,Caster.toBoolean(m.isReadonly())); qry.setAt("default",row,Caster.toBoolean(m.isDefault())); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetRestSettings() throws PageException { Struct sct=new StructImpl(); sct.set(KeyConstants._list, Caster.toBoolean(config.getRestList())); //sct.set(KeyImpl.init("allowChanges"), Caster.toBoolean(config.getRestAllowChanges())); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); } private void doGetResourceProviders() throws PageException { pageContext.setVariable(getString("admin",action,"returnVariable"),admin.getResourceProviders()); } private void doGetClusterClass() throws PageException { pageContext.setVariable(getString("admin",action,"returnVariable"),config.getClusterClass().getName()); } private void doUpdateClusterClass() throws PageException { ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.updateClusterClass(cd); store(); } private void doUpdateAdminSyncClass() throws PageException { ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.updateAdminSyncClass(cd); store(); } private void doGetAdminSyncClass() throws PageException { pageContext.setVariable(getString("admin",action,"returnVariable"),config.getAdminSyncClass().getName()); } private void doUpdateVideoExecuterClass() throws PageException { ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.updateVideoExecuterClass(cd); store(); } private void doGetVideoExecuterClass() throws PageException { pageContext.setVariable(getString("admin",action,"returnVariable"),config.getVideoExecuterClass().getName()); } /** * @throws PageException * */ private void doRemoveMailServer() throws PageException { admin.removeMailServer(getString("admin",action,"hostname")); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doUpdateMailServer() throws PageException { admin.updateMailServer( getString("admin",action,"hostname"), getString("admin",action,"dbusername"), getString("admin",action,"dbpassword"), Caster.toIntValue(getString("admin",action,"port")), getBoolV("tls", false), getBoolV("ssl", false) ); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doUpdateMailSetting() throws PageException { //admin.setMailLog(getString("admin",action,"logfile"),getString("loglevel","ERROR")); admin.setMailSpoolEnable(getBoolObject("admin",action,"spoolenable")); /*/ spool interval String str=getString("admin",action,"maxThreads"); Integer i=null; if(!StringUtil.isEmpty(str))i=Caster.toInteger(maxThreads);*/ // timeout String str = getString("admin",action,"timeout"); Integer i = null; if(!StringUtil.isEmpty(str))i=Caster.toInteger(str); admin.setMailTimeout(i); admin.setMailDefaultCharset(getString("admin", action, "defaultencoding")); store(); adminSync.broadcast(attributes, config); } private void doUpdateTaskSetting() throws PageException { // max Threads String str=getString("admin",action,"maxThreads"); Integer i=null; if(!StringUtil.isEmpty(str)){ i=Caster.toInteger(str); if(i.intValue()<10) throw new ApplicationException("we need at least 10 threads to run tasks properly"); } admin.setTaskMaxThreads(i); store(); adminSync.broadcast(attributes, config); } private void listPatches() throws PageException { try { pageContext.setVariable(getString("admin",action,"returnVariable"),Caster.toArray(((ConfigServerImpl)config).getInstalledPatches())); } catch (Exception e) { throw Caster.toPageException(e); } } private void doGetMailServers() throws PageException { Server[] servers = config.getMailServers(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"hostname","password","username","port","authentication","readonly","tls","ssl"},servers.length,"query"); for(int i=0;i<servers.length;i++) { Server s= servers[i]; int row=i+1; qry.setAt("hostname",row,s.getHostName()); qry.setAt("password",row,s.isReadOnly()?"":s.getPassword()); qry.setAt("username",row,s.isReadOnly()?"":s.getUsername()); qry.setAt("port",row,Caster.toInteger(s.getPort())); qry.setAt("readonly",row,Caster.toBoolean(s.isReadOnly())); qry.setAt("authentication",row,Caster.toBoolean(s.hasAuthentication())); if(s instanceof ServerImpl) { ServerImpl si = (ServerImpl)s; qry.setAt("ssl",row,Caster.toBoolean(si.isSSL())); qry.setAt("tls",row,Caster.toBoolean(si.isTLS())); } } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetRunningThreads() throws PageException { lucee.runtime.type.Query qry=new QueryImpl(new String[]{"Id","Start","Timeout","ThreadType","StackTrace","TagContext", "Label","RootPath","ConfigFile","URL"},0,"query"); if(type==TYPE_WEB){ fillGetRunningThreads(qry,pageContext.getConfig()); } else { ConfigServer cs = pageContext.getConfig().getConfigServer(password); ConfigWeb[] webs = cs.getConfigWebs(); for(int i=0;i<webs.length;i++){ fillGetRunningThreads(qry,webs[i]); } } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private static void fillGetRunningThreads(lucee.runtime.type.Query qry, ConfigWeb configWeb) throws PageException { CFMLFactoryImpl factory = ((CFMLFactoryImpl)configWeb.getFactory()); Map<Integer, PageContextImpl> pcs = factory.getActivePageContexts(); Iterator<PageContextImpl> it = pcs.values().iterator(); PageContextImpl pc; Collection.Key key; int row=0; while(it.hasNext()) { pc=it.next(); qry.addRow(); row++; StackTraceElement[] st = pc.getThread().getStackTrace(); configWeb.getConfigDir(); configWeb.getIdentification().getId(); configWeb.getConfigDir(); qry.setAt("Id",row,new Double(pc.getId())); qry.setAt("Start",row,new DateTimeImpl(pc.getStartTime(),false)); qry.setAt("Timeout",row,new Double(pc.getRequestTimeout()/1000)); qry.setAt("ThreadType",row,pc.getParentPageContext()==null?"main":"child"); qry.setAt("StackTrace",row,toString(st)); qry.setAt("TagContext",row,PageExceptionImpl.getTagContext(pc.getConfig(), st)); qry.setAt("label",row,factory.getLabel()); qry.setAt("RootPath",row,ReqRspUtil.getRootPath(((ConfigWebImpl)configWeb).getServletContext())); qry.setAt("ConfigFile",row,configWeb.getConfigFile().getAbsolutePath()); if(factory.getURL()!=null)qry.setAt("url",row,factory.getURL().toExternalForm()); } } private static String toString(StackTraceElement[] traces) { StackTraceElement trace; StringBuilder sb=new StringBuilder( traces.length * 32 ); for(int i=0;i<traces.length;i++){ trace=traces[i]; sb.append("\tat "); sb.append(trace.toString()); sb.append(':'); sb.append(trace.getLineNumber()); sb.append(SystemUtil.getOSSpecificLineSeparator()); } return sb.toString(); } /** * @throws PageException * */ private void doGetMailSetting() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); //LoggerAndSourceData data = config.getLoggerAndSourceData("mail"); //lucee.commons.io.log.Log log=ls.getLog(); //String logFile=""; //String logLevel=""; //if(log instanceof LogResource)logFile=((LogResource)log).getResource().toString(); //String logLevel=LogUtil.toStringType(data.getLevel(),"ERROR"); //sct.set("strlogfile",ls.getSource()); //sct.set("logfile",logFile); //sct.set("loglevel",logLevel); int maxThreads=20; SpoolerEngine engine = config.getSpoolerEngine(); if(engine instanceof SpoolerEngineImpl) { maxThreads=((SpoolerEngineImpl)engine).getMaxThreads(); } sct.set("spoolEnable",Caster.toBoolean(config.isMailSpoolEnable())); sct.set("spoolInterval",Caster.toInteger(config.getMailSpoolInterval())); sct.set("maxThreads",Caster.toDouble(maxThreads)); sct.set("timeout",Caster.toInteger(config.getMailTimeout())); sct.set("defaultencoding", config.getMailDefaultCharset().name()); } private void doGetTaskSetting() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); int maxThreads=20; SpoolerEngine engine = config.getSpoolerEngine(); if(engine instanceof SpoolerEngineImpl) { SpoolerEngineImpl ei = ((SpoolerEngineImpl)engine); maxThreads=ei.getMaxThreads(); } sct.set("maxThreads",Caster.toDouble(maxThreads)); } /** * @throws PageException * */ private void doGetTLDs() throws PageException { lucee.runtime.type.Query qry=new QueryImpl( new String[]{"displayname","namespace","namespaceseparator","shortname","type","description","uri","elclass","elBundleName","elBundleVersion","source"}, new String[]{"varchar","varchar","varchar","varchar","varchar","varchar","varchar","varchar","varchar","varchar","varchar"}, 0,"tlds"); int dialect="lucee".equalsIgnoreCase(getString("dialect","cfml"))?CFMLEngine.DIALECT_LUCEE:CFMLEngine.DIALECT_CFML; TagLib[] libs = config.getTLDs(dialect); for(int i=0;i<libs.length;i++) { qry.addRow(); qry.setAt("displayname", i+1, libs[i].getDisplayName()); qry.setAt("namespace", i+1, libs[i].getNameSpace()); qry.setAt("namespaceseparator", i+1, libs[i].getNameSpaceSeparator()); qry.setAt("shortname", i+1, libs[i].getShortName()); qry.setAt("type", i+1, libs[i].getType()); qry.setAt("description", i+1, libs[i].getDescription()); qry.setAt("uri", i+1, Caster.toString(libs[i].getUri())); qry.setAt("elclass", i+1, libs[i].getELClassDefinition().getClassName()); qry.setAt("elBundleName", i+1, libs[i].getELClassDefinition().getName()); qry.setAt("elBundleVersion", i+1, libs[i].getELClassDefinition().getVersionAsString()); qry.setAt("source", i+1, StringUtil.emptyIfNull(libs[i].getSource())); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetRHExtensions() throws PageException { pageContext.setVariable(getString("admin",action,"returnVariable"),admin.getRHExtensionsAsQuery(config)); } /** * @throws PageException * */ private void doGetFLDs() throws PageException { lucee.runtime.type.Query qry=new QueryImpl( new String[]{"displayname","namespace","namespaceseparator","shortname","description","uri","source"}, new String[]{"varchar","varchar","varchar","varchar","varchar","varchar","varchar"}, 0,"tlds"); int dialect="lucee".equalsIgnoreCase(getString("dialect","cfml"))?CFMLEngine.DIALECT_LUCEE:CFMLEngine.DIALECT_CFML; FunctionLib[] libs = config.getFLDs(dialect); for(int i=0;i<libs.length;i++) { qry.addRow(); qry.setAt("displayname", i+1, libs[i].getDisplayName()); qry.setAt("namespace", i+1, "");// TODO support for namespace qry.setAt("namespaceseparator", i+1, ""); qry.setAt("shortname", i+1, libs[i].getShortName()); qry.setAt("description", i+1, libs[i].getDescription()); qry.setAt("uri", i+1, Caster.toString(libs[i].getUri())); qry.setAt("source", i+1, StringUtil.emptyIfNull(libs[i].getSource())); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetRemoteClientUsage() throws PageException { lucee.runtime.type.Query qry=new QueryImpl( new String[]{"code","displayname"}, new String[]{"varchar","varchar"}, 0,"usage"); Struct usages = config.getRemoteClientUsage(); //Key[] keys = usages.keys(); Iterator<Entry<Key, Object>> it = usages.entryIterator(); Entry<Key, Object> e; int i=-1; while(it.hasNext()) { i++; e = it.next(); qry.addRow(); qry.setAt(KeyConstants._code, i+1, e.getKey().getString()); qry.setAt(KeyConstants._displayname, i+1, e.getValue()); //qry.setAt("description", i+1, usages[i].getDescription()); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doHasRemoteClientUsage() throws PageException { Struct usages = config.getRemoteClientUsage(); pageContext.setVariable(getString("admin",action,"returnVariable"),usages.isEmpty()?Boolean.FALSE:Boolean.TRUE); } private void doGetJars() throws PageException { Resource lib = config.getLibraryDirectory(); lucee.runtime.type.Query qry=new QueryImpl(new Key[]{KeyConstants._name,KeyConstants._source,KeyConstants._info},new String[]{"varchar","varchar","varchar"},0,"jars"); if(lib.isDirectory()){ Resource[] children = lib.listResources(new ExtensionResourceFilter(new String[]{".jar",".zip"},false,true)); for(int i=0;i<children.length;i++){ qry.addRow(); qry.setAt(KeyConstants._name, i+1, children[i].getName()); qry.setAt(KeyConstants._source, i+1, children[i].getAbsolutePath()); try { qry.setAt(KeyConstants._info, i+1, new BundleFile(children[i]).info()); } catch (Exception e) {} } } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doUpdateJDBCDriver() throws PageException { ClassDefinition cd=new ClassDefinitionImpl( getString("admin",action,"classname") , getString("bundleName",null) , getString("bundleVersion",null) , config.getIdentification()); String label=getString("admin",action,"label"); admin.updateJDBCDriver(label,cd); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doUpdateDatasource() throws PageException { int allow= (getBoolV("allowed_select",false)?DataSource.ALLOW_SELECT:0)+ (getBoolV("allowed_insert",false)?DataSource.ALLOW_INSERT:0)+ (getBoolV("allowed_update",false)?DataSource.ALLOW_UPDATE:0)+ (getBoolV("allowed_delete",false)?DataSource.ALLOW_DELETE:0)+ (getBoolV("allowed_alter",false)?DataSource.ALLOW_ALTER:0)+ (getBoolV("allowed_drop",false)?DataSource.ALLOW_DROP:0)+ (getBoolV("allowed_revoke",false)?DataSource.ALLOW_REVOKE:0)+ (getBoolV("allowed_grant",false)?DataSource.ALLOW_GRANT:0)+ (getBoolV("allowed_create",false)?DataSource.ALLOW_CREATE:0); if(allow==0)allow=DataSource.ALLOW_ALL; String cn = getString("admin",action,"classname"); if("com.microsoft.jdbc.sqlserver.SQLServerDriver".equals(cn)) { cn="com.microsoft.sqlserver.jdbc.SQLServerDriver"; } ClassDefinition cd=new ClassDefinitionImpl( cn , getString("bundleName",null) , getString("bundleVersion",null) , config.getIdentification()); String dsn=getString("admin",action,"dsn"); String name=getString("admin",action,"name"); String newName=getString("admin",action,"newName"); String username=getString("admin",action,"dbusername"); String password=getString("admin",action,"dbpassword"); String host=getString("host",""); String timezone=getString("timezone",""); String database=getString("database",""); int port=getInt("port",-1); int connLimit=getInt("connectionLimit",-1); int connTimeout=getInt("connectionTimeout",-1); long metaCacheTimeout=getLong("metaCacheTimeout",60000); boolean blob=getBoolV("blob",false); boolean clob=getBoolV("clob",false); boolean validate=getBoolV("validate",false); boolean storage=getBoolV("storage",false); boolean verify=getBoolV("verify",true); Struct custom=getStruct("custom",new StructImpl()); String dbdriver = getString("dbdriver", ""); //config.getDatasourceConnectionPool().remove(name); DataSource ds=null; try { ds = new DataSourceImpl(null,name,cd,host,dsn,database,port,username,password,connLimit,connTimeout,metaCacheTimeout,blob,clob,allow,custom,false,validate,storage,null, dbdriver,config.getLog("application")); } catch (Exception e) { throw new DatabaseException( "can't find class ["+cd.toString()+"] for jdbc driver, check if driver (jar file) is inside lib folder ("+e.getMessage()+")",null,null,null); } if(verify)_doVerifyDatasource(ds,username,password); //print.out("limit:"+connLimit); admin.updateDataSource( name, newName, cd, dsn, username, password, host, database, port, connLimit, connTimeout, metaCacheTimeout, blob, clob, allow, validate, storage, timezone, custom, dbdriver ); store(); adminSync.broadcast(attributes, config); } private void doUpdateCacheConnection() throws PageException { ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.updateCacheConnection( getString("admin",action,"name"), cd, toCacheConstant("default"), getStruct("admin", action, "custom"), getBoolV("readOnly", false), getBoolV("storage", false) ); store(); adminSync.broadcast(attributes, config); } private void doUpdateGatewayEntry() throws PageException { String strStartupMode=getString("admin",action,"startupMode"); int startup=GatewayEntryImpl.toStartup(strStartupMode,-1); if(startup==-1) throw new ApplicationException("invalid startup mode ["+strStartupMode+"], valid values are [automatic,manual,disabled]"); //print.out("doUpdateGatewayEntry"); ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.updateGatewayEntry( getString("admin",action,"id"), cd, getString("admin",action,"cfcPath"), getString("admin",action,"listenerCfcPath"), startup, getStruct("admin", action, "custom"), getBoolV("readOnly", false) ); store(); adminSync.broadcast(attributes, config); } private int toCacheConstant(String name) throws ApplicationException { String def = getString(name, null); if(StringUtil.isEmpty(def)) return Config.CACHE_TYPE_NONE; def=def.trim().toLowerCase(); if(def.equals("object")) return ConfigImpl.CACHE_TYPE_OBJECT; if(def.equals("template")) return ConfigImpl.CACHE_TYPE_TEMPLATE; if(def.equals("query")) return ConfigImpl.CACHE_TYPE_QUERY; if(def.equals("resource")) return ConfigImpl.CACHE_TYPE_RESOURCE; if(def.equals("function")) return ConfigImpl.CACHE_TYPE_FUNCTION; if(def.equals("include")) return ConfigImpl.CACHE_TYPE_INCLUDE; if(def.equals("http")) return ConfigImpl.CACHE_TYPE_HTTP; if(def.equals("file")) return ConfigImpl.CACHE_TYPE_FILE; if(def.equals("webservice")) return ConfigImpl.CACHE_TYPE_WEBSERVICE; throw new ApplicationException("invalid default type ["+def+"], valid default types are [object,template,query,resource,function]"); } private void doUpdateCacheDefaultConnection() throws PageException { admin.updateCacheDefaultConnection(ConfigImpl.CACHE_TYPE_OBJECT,getString("admin",action,"object")); admin.updateCacheDefaultConnection(ConfigImpl.CACHE_TYPE_TEMPLATE,getString("admin",action,"template")); admin.updateCacheDefaultConnection(ConfigImpl.CACHE_TYPE_QUERY,getString("admin",action,"query")); admin.updateCacheDefaultConnection(ConfigImpl.CACHE_TYPE_RESOURCE,getString("admin",action,"resource")); admin.updateCacheDefaultConnection(ConfigImpl.CACHE_TYPE_FUNCTION,getString("admin",action,"function")); admin.updateCacheDefaultConnection(ConfigImpl.CACHE_TYPE_INCLUDE,getString("admin",action,"include")); admin.updateCacheDefaultConnection(ConfigImpl.CACHE_TYPE_HTTP,getString("admin",action,"http")); admin.updateCacheDefaultConnection(ConfigImpl.CACHE_TYPE_FILE,getString("admin",action,"file")); admin.updateCacheDefaultConnection(ConfigImpl.CACHE_TYPE_WEBSERVICE,getString("admin",action,"webservice")); store(); adminSync.broadcast(attributes, config); } private void doRemoveCacheDefaultConnection() throws PageException { admin.removeCacheDefaultConnection(ConfigImpl.CACHE_TYPE_OBJECT); admin.removeCacheDefaultConnection(ConfigImpl.CACHE_TYPE_TEMPLATE); admin.removeCacheDefaultConnection(ConfigImpl.CACHE_TYPE_QUERY); admin.removeCacheDefaultConnection(ConfigImpl.CACHE_TYPE_RESOURCE); admin.removeCacheDefaultConnection(ConfigImpl.CACHE_TYPE_FUNCTION); admin.removeCacheDefaultConnection(ConfigImpl.CACHE_TYPE_INCLUDE); admin.removeCacheDefaultConnection(ConfigImpl.CACHE_TYPE_HTTP); admin.removeCacheDefaultConnection(ConfigImpl.CACHE_TYPE_FILE); admin.removeCacheDefaultConnection(ConfigImpl.CACHE_TYPE_WEBSERVICE); store(); adminSync.broadcast(attributes, config); } private void doRemoveLogSetting() throws PageException { admin.removeLogSetting(getString("admin", "RemoveLogSettings", "name")); store(); adminSync.broadcast(attributes, config); } private void doRemoveResourceProvider() throws PageException { ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.removeResourceProvider(cd); store(); adminSync.broadcast(attributes, config); } private void doUpdateResourceProvider() throws PageException { ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); String scheme=getString("admin",action,"scheme"); Struct sctArguments = getStruct("arguments", null); if(sctArguments!=null) { admin.updateResourceProvider(scheme,cd,sctArguments); } else { String strArguments=getString("admin",action,"arguments"); admin.updateResourceProvider(scheme,cd,strArguments); } //admin.updateResourceProvider(scheme,clazz,arguments); store(); adminSync.broadcast(attributes, config); } private void doUpdateDefaultResourceProvider() throws PageException { ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); String arguments=getString("admin",action,"arguments"); admin.updateDefaultResourceProvider(cd,arguments); store(); adminSync.broadcast(attributes, config); } private void doVerifyMailServer() throws PageException { _doVerifyMailServer( getString("admin",action,"hostname"), getInt("admin",action,"port"), getString("admin",action,"mailusername"), getString("admin",action,"mailpassword") ); } private void _doVerifyMailServer(String host, int port, String user, String pass) throws PageException { try { SMTPVerifier.verify(host,user,pass,port); } catch (SMTPException e) { throw Caster.toPageException(e); } } /** * @throws PageException * */ private void doVerifyDatasource() throws PageException { ClassDefinition cd=new ClassDefinitionImpl( Caster.toString(attributes.get("classname",null),null) ,Caster.toString(attributes.get("bundleName",null),null) ,Caster.toString(attributes.get("bundleVersion",null),null) ,config.getIdentification() ); String connStr=(String) attributes.get("connStr",null); if(StringUtil.isEmpty(connStr))connStr=(String) attributes.get("dsn",null); if(cd.hasClass() && connStr!=null) { _doVerifyDatasource(cd,connStr, getString("admin",action,"dbusername"), getString("admin",action,"dbpassword")); } else { _doVerifyDatasource( getString("admin",action,"name"), getString("admin",action,"dbusername"), getString("admin",action,"dbpassword")); } } private void doVerifyRemoteClient() throws PageException { // SNSN /*SerialNumber sn = config.getSerialNumber(); if(sn.getVersion()==SerialNumber.VERSION_COMMUNITY) throw new SecurityException("can not verify remote client with "+sn.getStringVersion()+" version of Lucee"); */ ProxyData pd=null; String proxyServer=getString("proxyServer",null); if(!StringUtil.isEmpty(proxyServer)) { String proxyUsername=getString("proxyUsername",null); String proxyPassword=getString("proxyPassword",null); int proxyPort = getInt("proxyPort",-1); pd=new ProxyDataImpl(); pd.setServer(proxyServer); if(!StringUtil.isEmpty(proxyUsername))pd.setUsername(proxyUsername); if(!StringUtil.isEmpty(proxyPassword))pd.setPassword(proxyPassword); if(proxyPort!=-1)pd.setPort(proxyPort); } RemoteClient client = new RemoteClientImpl( getString("admin",action,"label"), type==TYPE_WEB?"web":"server", getString("admin",action,"url"), getString("serverUsername",null), getString("serverPassword",null), getString("admin",action,"adminPassword"), pd, getString("admin",action,"securityKey"), getString("admin",action,"usage") ); Struct attrColl=new StructImpl(); attrColl.setEL("action", "connect"); try { new RemoteClientTask(null,client,attrColl,getCallerId(),"synchronisation").execute(config); } catch (Throwable t) { throw Caster.toPageException(t); } } private void _doVerifyDatasource(DataSource ds, String username, String password) throws PageException { try { DataSourceManager manager = pageContext.getDataSourceManager(); DatasourceConnectionImpl dc = new DatasourceConnectionImpl(ds.getConnection(config, username, password), ds, username, password); manager.releaseConnection(pageContext,dc); } catch (Exception e) { throw Caster.toPageException(e); } } private void _doVerifyDatasource(String name, String username, String password) throws PageException { DataSourceManager manager = pageContext.getDataSourceManager(); manager.releaseConnection(pageContext,manager.getConnection(pageContext,name, username, password)); } private void _doVerifyDatasource(ClassDefinition cd, String connStrTranslated, String user, String pass) throws PageException { try { DataSourceImpl.verify(config,null, cd, connStrTranslated, user, pass); } catch (Exception e) { throw Caster.toPageException(e); } } /** * @throws PageException * */ private void doUpdatePSQ() throws PageException { admin.updatePSQ(getBoolObject("admin",action,"psq")); store(); adminSync.broadcast(attributes, config); } private void doReload() throws PageException { store(); } private void doRemoveJDBCDriver() throws PageException { admin.removeJDBCDriver(getString("admin",action,"class")); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doRemoveDatasource() throws PageException { admin.removeDataSource(getString("admin",action,"name")); store(); adminSync.broadcast(attributes, config); } private void doTerminateRunningThread() throws PageException { int id = getInt("admin", "RemoveRunningThread", "id"); if(type==TYPE_WEB){ terminateRunningThread(pageContext.getConfig(),id); } else { ConfigServer cs = pageContext.getConfig().getConfigServer(password); ConfigWeb[] webs = cs.getConfigWebs(); for(int i=0;i<webs.length;i++){ if(terminateRunningThread(webs[i],id))break; } } } private static boolean terminateRunningThread(ConfigWeb configWeb,int id) { Map<Integer, PageContextImpl> pcs = ((CFMLFactoryImpl)configWeb.getFactory()).getActivePageContexts(); Iterator<PageContextImpl> it = pcs.values().iterator(); PageContextImpl pc; Collection.Key key; while(it.hasNext()) { pc=it.next(); if(pc.getId()==id){ CFMLFactoryImpl.terminate(pc); return true; } } return false; } private void doRemoveRemoteClient() throws PageException { admin.removeRemoteClient(getString("admin",action,"url")); store(); } private void doRemoveSpoolerTask() throws PageException { config.getSpoolerEngine().remove(getString("admin",action,"id")); } private void doRemoveAllSpoolerTask() { ((SpoolerEngineImpl)config.getSpoolerEngine()).removeAll(); } private void doExecuteSpoolerTask() throws PageException { PageException pe = config.getSpoolerEngine().execute(getString("admin",action,"id")); if(pe!=null) throw pe; } /** * @throws PageException * */ private void doGetDatasourceSetting() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); sct.set("psq",Caster.toBoolean(config.getPSQL())); } private void doGetORMSetting() throws PageException { pageContext.setVariable(getString("admin",action,"returnVariable"),config.getORMConfig().toStruct()); } private void doGetORMEngine() throws PageException { ClassDefinition<? extends ORMEngine> cd = config.getORMEngineClassDefintion(); Struct sct=new StructImpl(); sct.set(KeyConstants._class, cd.getClassName()); sct.set(KeyConstants._bundleName, cd.getName()); sct.set(KeyConstants._bundleVersion, cd.getVersionAsString()); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); } private void doUpdateORMSetting() throws SecurityException, PageException { ORMConfiguration oc = config.getORMConfig(); Struct settings=new StructImpl(); settings.set(ORMConfigurationImpl.AUTO_GEN_MAP, getBool("admin",action,"autogenmap")); settings.set(ORMConfigurationImpl.EVENT_HANDLING, getBool("admin",action,"eventHandling")); settings.set(ORMConfigurationImpl.FLUSH_AT_REQUEST_END, getBool("admin",action,"flushatrequestend")); settings.set(ORMConfigurationImpl.LOG_SQL, getBool("admin",action,"logSQL")); settings.set(ORMConfigurationImpl.SAVE_MAPPING, getBool("admin",action,"savemapping")); settings.set(ORMConfigurationImpl.USE_DB_FOR_MAPPING, getBool("admin",action,"useDBForMapping")); settings.set(ORMConfigurationImpl.SECONDARY_CACHE_ENABLED, getBool("admin",action,"secondarycacheenabled")); settings.set(ORMConfigurationImpl.CATALOG, getString("admin",action,"catalog")); settings.set(ORMConfigurationImpl.SCHEMA, getString("admin",action,"schema")); settings.set(ORMConfigurationImpl.SQL_SCRIPT, getString("admin",action,"sqlscript")); settings.set(ORMConfigurationImpl.CACHE_CONFIG, getString("admin",action,"cacheconfig")); settings.set(ORMConfigurationImpl.CACHE_PROVIDER, getString("admin",action,"cacheProvider")); settings.set(ORMConfigurationImpl.ORM_CONFIG, getString("admin",action,"ormConfig")); // dbcreate String strDbcreate=getString("admin",action,"dbcreate"); String dbcreate="none"; if("none".equals(strDbcreate)) dbcreate="none"; else if("update".equals(strDbcreate)) dbcreate="update"; else if("dropcreate".equals(strDbcreate)) dbcreate="dropcreate"; else throw new ApplicationException("invalid dbcreate definition ["+strDbcreate+"], valid dbcreate definitions are [none,update,dropcreate]"); settings.set(ORMConfigurationImpl.DB_CREATE, dbcreate); // cfclocation String strCfclocation=getString("admin",action,"cfclocation"); Array arrCfclocation = lucee.runtime.type.util.ListUtil.listToArray(strCfclocation, ",\n"); Iterator it = arrCfclocation.valueIterator(); String path; while(it.hasNext()){ path=(String) it.next(); ResourceUtil.toResourceExisting(config, path); } settings.set(KeyConstants._cfcLocation, arrCfclocation); admin.updateORMSetting(ORMConfigurationImpl.load(config, null, settings, null, oc)); store(); adminSync.broadcast(attributes, config); } private void doResetORMSetting() throws SecurityException, PageException { config.getORMConfig(); admin.resetORMSetting(); store(); adminSync.broadcast(attributes, config); } private void doUpdatePerformanceSettings() throws SecurityException, PageException { admin.updateInspectTemplate(getString("admin",action,"inspectTemplate")); admin.updateTypeChecking(getBoolObject("admin",action,"typeChecking")); store(); adminSync.broadcast(attributes, config); } private void doUpdateCompilerSettings() throws SecurityException, PageException { admin.updateCompilerSettings( getBoolObject("admin", "UpdateCompilerSettings", "dotNotationUpperCase"), getBoolObject("admin", "UpdateCompilerSettings", "suppressWSBeforeArg"), getBoolObject("admin", "UpdateCompilerSettings", "nullSupport"), getBoolObject("admin", "UpdateCompilerSettings", "handleUnquotedAttrValueAsString") ); admin.updateTemplateCharset(getString("admin",action,"templateCharset")); store(); adminSync.broadcast(attributes, config); } /*private void doGetLogSetting() throws PageException { String name=getString("admin", "GetLogSetting", "name"); name=name.trim().toLowerCase(); Query qry=_doGetLogSettings(); int records = qry.getRecordcount(); for(int row=1;row<=records;row++){ String n = Caster.toString(qry.getAt("name", row, null),null); if(!StringUtil.isEmpty(n) && n.trim().equalsIgnoreCase(name)) { Struct sct=new StructImpl(); String returnVariable=getString("admin",action,"returnVariable"); pageContext.setVariable(returnVariable,sct); sct.setEL(KeyConstants._name, qry.getAt(KeyConstants._name, row, "")); sct.setEL(KeyConstants._level, qry.getAt(KeyConstants._level, row, "")); sct.setEL("virtualpath", qry.getAt("virtualpath", row, "")); sct.setEL(KeyConstants._class, qry.getAt(KeyConstants._class, row, "")); sct.setEL("maxFile", qry.getAt("maxFile", row, "")); sct.setEL("maxFileSize", qry.getAt("maxFileSize", row, "")); sct.setEL(KeyConstants._path, qry.getAt(KeyConstants._path, row, "")); return; } } throw new ApplicationException("invalig log name ["+name+"]"); }*/ private void doGetCompilerSettings() throws PageException { String returnVariable=getString("admin",action,"returnVariable"); Struct sct=new StructImpl(); pageContext.setVariable(returnVariable,sct); sct.set("DotNotationUpperCase", config.getDotNotationUpperCase()?Boolean.TRUE:Boolean.FALSE); sct.set("suppressWSBeforeArg", config.getSuppressWSBeforeArg()?Boolean.TRUE:Boolean.FALSE); sct.set("nullSupport", config.getFullNullSupport()?Boolean.TRUE:Boolean.FALSE); sct.set("handleUnquotedAttrValueAsString", config.getHandleUnQuotedAttrValueAsString()?Boolean.TRUE:Boolean.FALSE); sct.set("templateCharset", config.getTemplateCharset()); } private void doGetLogSettings() throws PageException { String returnVariable=getString("admin",action,"returnVariable"); pageContext.setVariable(returnVariable,_doGetLogSettings()); } private Query _doGetLogSettings() { Map<String, LoggerAndSourceData> loggers = config.getLoggers(); Query qry=new QueryImpl( new String[]{"name","level" ,"appenderClass","appenderBundleName","appenderBundleVersion","appenderArgs" ,"layoutClass","layoutBundleName","layoutBundleVersion","layoutArgs","readonly"}, loggers.size(),lucee.runtime.type.util.ListUtil.last("logs", '.')); int row=0; Iterator<Entry<String, LoggerAndSourceData>> it = loggers.entrySet().iterator(); Entry<String, LoggerAndSourceData> e; LoggerAndSourceData logger; while(it.hasNext()){ e = it.next(); logger = e.getValue(); row++; qry.setAtEL("name", row, e.getKey()); qry.setAtEL("level", row,logger.getLevel().toString()); qry.setAtEL("appenderClass", row, logger.getAppenderClassDefinition().getClassName()); qry.setAtEL("appenderBundleName", row, logger.getAppenderClassDefinition().getName()); qry.setAtEL("appenderBundleVersion", row, logger.getAppenderClassDefinition().getVersionAsString()); qry.setAtEL("appenderArgs", row, toStruct(logger.getAppenderArgs())); qry.setAtEL("layoutClass", row, logger.getLayoutClassDefinition().getClassName()); qry.setAtEL("layoutBundleName", row, logger.getLayoutClassDefinition().getName()); qry.setAtEL("layoutBundleVersion", row, logger.getLayoutClassDefinition().getVersionAsString()); qry.setAtEL("layoutArgs", row, toStruct(logger.getLayoutArgs())); qry.setAtEL("readonly", row, logger.getReadOnly()); } return qry; } private Object toStruct(Map<String, String> map) { Struct sct=new StructImpl(); if(map!=null) { Iterator<Entry<String, String>> it = map.entrySet().iterator(); Entry<String, String> e; while(it.hasNext()){ e = it.next(); sct.setEL(e.getKey(), e.getValue()); } } return sct; } private void doGetPerformanceSettings() throws ApplicationException, PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); short it = config.getInspectTemplate(); String str="once"; if(it==ConfigImpl.INSPECT_ALWAYS)str="always"; else if(it==ConfigImpl.INSPECT_NEVER)str="never"; sct.set("inspectTemplate",str); sct.set("typeChecking",config.getTypeChecking()); } private void doGetCustomTagSetting() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); sct.set("customTagDeepSearch",Caster.toBoolean(config.doCustomTagDeepSearch()));// deprecated sct.set("customTagLocalSearch",Caster.toBoolean(config.doLocalCustomTag()));// deprecated sct.set("deepSearch",Caster.toBoolean(config.doCustomTagDeepSearch())); sct.set("localSearch",Caster.toBoolean(config.doLocalCustomTag())); sct.set("customTagPathCache",Caster.toBoolean(config.useCTPathCache())); sct.set("extensions",new ArrayImpl(config.getCustomTagExtensions())); } private void doGetDatasourceDriverList() throws PageException { Resource luceeContext = ResourceUtil.toResourceExisting(pageContext ,"/lucee/admin/dbdriver/"); Resource[] children = luceeContext.listResources(new ExtensionResourceFilter(Constants.getComponentExtensions())); String rtnVar=getString("admin",action,"returnVariable"); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"name"},children.length,rtnVar); for(int i=0;i<children.length;i++) { qry.setAt("name", i+1, children[i].getName()); } pageContext.setVariable(rtnVar,qry); } private void doGetDebuggingList() throws PageException { Resource luceeContext = ResourceUtil.toResourceExisting(pageContext ,"/lucee/templates/debugging/"); Resource[] children = luceeContext.listResources(new ExtensionResourceFilter(Constants.getTemplateExtensions())); String rtnVar=getString("admin",action,"returnVariable"); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"name"},children.length,rtnVar); for(int i=0;i<children.length;i++) { qry.setAt("name", i+1, children[i].getName()); } pageContext.setVariable(rtnVar,qry); } private void doGetGatewayEntries() throws PageException { Map entries = ((ConfigWebImpl)config).getGatewayEngine().getEntries(); Iterator it = entries.entrySet().iterator(); lucee.runtime.type.Query qry= new QueryImpl(new String[]{"class","bundleName","bundleVersion","id","custom","cfcPath","listenerCfcPath","startupMode","state","readOnly"}, 0, "entries"); Map.Entry entry; GatewayEntry ge; //Gateway g; int row=0; while(it.hasNext()){ row++; entry=(Entry) it.next(); ge=(GatewayEntry) entry.getValue(); //g=ge.getGateway(); qry.addRow(); qry.setAtEL("class", row, ge.getClassDefinition().getClassName()); qry.setAtEL("bundleName", row,ge.getClassDefinition().getName()); qry.setAtEL("bundleVersion", row, ge.getClassDefinition().getVersionAsString()); qry.setAtEL("id", row, ge.getId()); qry.setAtEL("listenerCfcPath", row, ge.getListenerCfcPath()); qry.setAtEL("cfcPath", row, ge.getCfcPath()); qry.setAtEL("startupMode", row, GatewayEntryImpl.toStartup(ge.getStartupMode(),"automatic")); qry.setAtEL("custom", row, ge.getCustom()); qry.setAtEL("readOnly", row, Caster.toBoolean(ge.isReadOnly())); qry.setAtEL("state",row,GatewayEngineImpl.toStringState(GatewayUtil.getState(ge), "failed")); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetBundles() throws PageException { //if(!(config instanceof ConfigServerImpl)) // throw new ApplicationException("invalid context for this action"); //ConfigServerImpl cs=(ConfigServerImpl) config; CFMLEngine engine = ConfigWebUtil.getEngine(config); BundleCollection coreBundles = engine.getBundleCollection(); java.util.Collection<BundleDefinition> extBundles = config.getAllExtensionBundleDefintions(); List<BundleDefinition> bds = OSGiUtil.getBundleDefinitions(engine.getBundleContext()); Iterator<BundleDefinition> it = bds.iterator(); // Bundle[] bundles = cs.getCFMLEngine().getBundleContext().getBundles(); BundleDefinition bd; Bundle b; String str; Query qry=new QueryImpl(new Key[]{SYMBOLIC_NAME, KeyConstants._title,KeyConstants._description,KeyConstants._version,VENDOR,KeyConstants._state,USED_BY,KeyConstants._id,FRAGMENT ,HEADERS},bds.size(),"bundles"); int row=0; while(it.hasNext()){ row++; bd=it.next(); qry.setAt(SYMBOLIC_NAME, row, bd.getName()); qry.setAt(KeyConstants._title, row, bd.getName()); qry.setAt(KeyConstants._version, row, bd.getVersionAsString()); qry.setAt(USED_BY, row, _usedBy(bd.getName(),bd.getVersion(),coreBundles,extBundles)); b=bd.getLoadedBundle(); Map<String,Object> headers=null; if(b!=null) { qry.setAt(KeyConstants._version, row, bd.getVersion().toString()); qry.setAt(KeyConstants._id, row, b.getBundleId()); qry.setAt(KeyConstants._state, row, OSGiUtil.toState(b.getState(),null)); qry.setAt(FRAGMENT, row, OSGiUtil.isFragment(b)); headers = OSGiUtil.getHeaders(b); } else { qry.setAt(KeyConstants._state, row, "notinstalled"); try { BundleFile bf=bd.getBundleFile(); qry.setAt(KeyConstants._version, row, bf.getVersionAsString()); //qry.setAt(KeyConstants._id, row, bf.getBundleId()); qry.setAt(FRAGMENT, row, OSGiUtil.isFragment(bf)); headers=bf.getHeaders(); } catch (BundleException e) {} } if(headers!=null) { Struct h = Caster.toStruct(headers,false); qry.setAt(HEADERS, row,h); // title str=Caster.toString(h.get("Bundle-Title",null),null); if(StringUtil.isEmpty(str)) str=Caster.toString(h.get("Implementation-Title",null),null); if(StringUtil.isEmpty(str)) str=Caster.toString(h.get("Specification-Title",null),null); if(StringUtil.isEmpty(str)) str=Caster.toString(h.get("Bundle-Name",null),null); if(!StringUtil.isEmpty(str)) qry.setAt(KeyConstants._title, row, str); // description str=Caster.toString(h.get("Bundle-Description",null),null); if(StringUtil.isEmpty(str)) str=Caster.toString(h.get("Implementation-Description",null),null); if(StringUtil.isEmpty(str)) str=Caster.toString(h.get("Specification-Description",null),null); if(!StringUtil.isEmpty(str)) qry.setAt(KeyConstants._description, row, str); // Vendor str=Caster.toString(h.get("Bundle-Vendor",null),null); if(StringUtil.isEmpty(str)) str=Caster.toString(h.get("Implementation-Vendor",null),null); if(StringUtil.isEmpty(str)) str=Caster.toString(h.get("Specification-Vendor",null),null); if(!StringUtil.isEmpty(str)) qry.setAt(VENDOR, row, str); // Specification-Vendor,Bundle-Vendor } } QuerySort.call(pageContext, qry, "title"); pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private Object _usedBy(String name, Version version, BundleCollection coreBundles, java.util.Collection<BundleDefinition> extBundles) { // core if(_eq(name,version,coreBundles.core.getSymbolicName(),coreBundles.core.getVersion())) return "core"; Iterator<Bundle> it = coreBundles.getSlaves(); Bundle b; while(it.hasNext()){ b=it.next(); if(_eq(name,version,b.getSymbolicName(),b.getVersion())) return "core"; } Iterator<BundleDefinition> itt = extBundles.iterator(); BundleDefinition bd; while(itt.hasNext()){ bd = itt.next(); if(_eq(name,version,bd.getName(),bd.getVersion())) return "extension"; } return null; } private boolean _eq(String lName, Version lVersion, String rName, Version rVersion) { if(!lName.equals(rName)) return false; if(lVersion==null) return rVersion==null; return lVersion.equals(rVersion); } private void doGetMonitors() throws PageException { if(!(config instanceof ConfigServerImpl)) throw new ApplicationException("invalid context for this action"); ConfigServerImpl cs=(ConfigServerImpl) config; IntervallMonitor[] intervalls = cs.getIntervallMonitors(); RequestMonitor[] requests = cs.getRequestMonitors(); lucee.runtime.type.Query qry= new QueryImpl(new Collection.Key[]{KeyConstants._name,KeyConstants._type,LOG_ENABLED,CLASS}, 0, "monitors"); doGetMonitors(qry,intervalls); doGetMonitors(qry,requests); pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetMonitor() throws PageException { if(!(config instanceof ConfigServerImpl)) throw new ApplicationException("invalid context for this action"); ConfigServerImpl cs=(ConfigServerImpl) config; String type=getString("admin",action,"monitorType"); String name=getString("admin",action,"name"); type=type.trim(); Monitor m; if("request".equalsIgnoreCase(type)) m=cs.getRequestMonitor(name); else m=cs.getIntervallMonitor(name); Struct sct=new StructImpl(); sct.setEL(KeyConstants._name, m.getName()); sct.setEL(KeyConstants._type, m.getType()==Monitor.TYPE_INTERVAL?"intervall":"request"); sct.setEL(LOG_ENABLED, m.isLogEnabled()); sct.setEL(CLASS, m.getClazz().getName()); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); } private void doGetExecutionLog() throws PageException { ExecutionLogFactory factory = config.getExecutionLogFactory(); Struct sct=new StructImpl(); sct.set(KeyConstants._enabled, Caster.toBoolean(config.getExecutionLogEnabled())); Class clazz = factory.getClazz(); sct.set(KeyConstants._class, clazz!=null?clazz.getName():""); sct.set(KeyConstants._arguments, factory.getArgumentsAsStruct()); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); } private void doGetMonitors(Query qry, Monitor[] monitors) { Monitor m; int row; for(int i=0;i<monitors.length;i++){ m=monitors[i]; row=qry.addRow(); qry.setAtEL(KeyConstants._name, row, m.getName()); qry.setAtEL(KeyConstants._type, row, m.getType()==Monitor.TYPE_INTERVAL?"intervall":"request"); qry.setAtEL(LOG_ENABLED, row, m.isLogEnabled()); qry.setAtEL(CLASS, row, m.getClazz().getName()); } } private void doGetGatewayEntry() throws PageException { String id=getString("admin",action,"id"); Map entries = ((ConfigWebImpl)config).getGatewayEngine().getEntries(); Iterator it = entries.keySet().iterator(); GatewayEntry ge; //Gateway g; Struct sct; while(it.hasNext()) { String key=(String)it.next(); if(key.equalsIgnoreCase(id)) { ge=(GatewayEntry) entries.get(key); //g=ge.getGateway(); sct=new StructImpl(); sct.setEL("id",ge.getId()); sct.setEL("class",ge.getClassDefinition().getClassName()); sct.setEL("bundleName",ge.getClassDefinition().getName()); sct.setEL("bundleVersion",ge.getClassDefinition().getVersionAsString()); sct.setEL("listenerCfcPath", ge.getListenerCfcPath()); sct.setEL("cfcPath",ge.getCfcPath()); sct.setEL("startupMode",GatewayEntryImpl.toStartup(ge.getStartupMode(),"automatic")); sct.setEL("custom",ge.getCustom()); sct.setEL("readOnly",Caster.toBoolean(ge.isReadOnly())); sct.setEL("state",GatewayEngineImpl.toStringState(GatewayUtil.getState(ge), "failed")); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); return; } } throw new ApplicationException("there is no gateway entry with id ["+id+"]"); } private void doGateway() throws PageException { String id=getString("admin",action,"id"); String act=getString("admin",action,"gatewayAction").trim().toLowerCase(); if("restart".equals(act)) ((ConfigWebImpl)config).getGatewayEngine().restart(id); else if("start".equals(act))((ConfigWebImpl)config).getGatewayEngine().start(id); else if("stop".equals(act)) ((ConfigWebImpl)config).getGatewayEngine().stop(id); else throw new ApplicationException("invalid gateway action ["+act+"], valid actions are [start,stop,restart]"); } private void doGetCacheConnections() throws PageException { Map conns = config.getCacheConnections(); Iterator it = conns.entrySet().iterator(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"class","bundleName","bundleVersion","name","custom","default","readOnly","storage"}, 0, "connections"); Map.Entry entry; CacheConnection cc; CacheConnection defObj=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_OBJECT); CacheConnection defTmp=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_TEMPLATE); CacheConnection defQry=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_QUERY); CacheConnection defRes=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_RESOURCE); CacheConnection defUDF=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_FUNCTION); CacheConnection defInc=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_INCLUDE); CacheConnection defHTT=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_HTTP); CacheConnection defFil=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_FILE); CacheConnection defWSe=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_WEBSERVICE); int row=0; String def; while(it.hasNext()){ row++; entry=(Entry) it.next(); cc=(CacheConnection) entry.getValue(); qry.addRow(); def=""; if(cc==defObj)def="object"; if(cc==defTmp)def="template"; if(cc==defQry)def="query"; if(cc==defRes)def="resource"; if(cc==defUDF)def="function"; if(cc==defInc)def="include"; if(cc==defHTT)def="http"; if(cc==defFil)def="file"; if(cc==defWSe)def="webservice"; qry.setAtEL(KeyConstants._class, row, cc.getClassDefinition().getClassName()); qry.setAtEL(KeyConstants._bundleName, row, cc.getClassDefinition().getName()); qry.setAtEL(KeyConstants._bundleVersion, row, cc.getClassDefinition().getVersionAsString()); qry.setAtEL(KeyConstants._name, row, cc.getName()); qry.setAtEL(KeyConstants._custom, row, cc.getCustom()); qry.setAtEL(KeyConstants._default, row, def); qry.setAtEL(KeyConstants._readonly, row, Caster.toBoolean(cc.isReadOnly())); qry.setAtEL(KeyConstants._storage, row, Caster.toBoolean(cc.isStorage())); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doGetCacheDefaultConnection() throws PageException { int type; String strType=getString("admin", "GetCacheDefaultConnection", "cacheType"); strType=strType.toLowerCase().trim(); if(strType.equals("object")) type=ConfigImpl.CACHE_TYPE_OBJECT; else if(strType.equals("template")) type=ConfigImpl.CACHE_TYPE_TEMPLATE; else if(strType.equals("query")) type=ConfigImpl.CACHE_TYPE_QUERY; else if(strType.equals("resource")) type=ConfigImpl.CACHE_TYPE_RESOURCE; else if(strType.equals("function")) type=ConfigImpl.CACHE_TYPE_FUNCTION; else if(strType.equals("include")) type=ConfigImpl.CACHE_TYPE_INCLUDE; else if(strType.equals("http")) type=ConfigImpl.CACHE_TYPE_HTTP; else if(strType.equals("file")) type=ConfigImpl.CACHE_TYPE_FILE; else if(strType.equals("webservice")) type=ConfigImpl.CACHE_TYPE_WEBSERVICE; else throw new ApplicationException("inv,query,resourcealid type defintion, valid values are [object,template,query,resource,function,include]"); CacheConnection cc = config.getCacheDefaultConnection(type); if(cc!=null){ Struct sct=new StructImpl(); sct.setEL(KeyConstants._name,cc.getName()); sct.setEL(KeyConstants._class,cc.getClassDefinition().getClassName()); sct.setEL(KeyConstants._bundleName,cc.getClassDefinition().getName()); sct.setEL(KeyConstants._bundleVersion,cc.getClassDefinition().getVersionAsString()); sct.setEL(KeyConstants._custom,cc.getCustom()); sct.setEL(KeyConstants._default,Caster.toBoolean(true)); sct.setEL(KeyConstants._readonly,Caster.toBoolean(cc.isReadOnly())); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); } else throw new ApplicationException("there is no cache default connection"); } private void doGetCacheConnection() throws PageException { String name=getString("admin",action,"name"); Map conns = config.getCacheConnections(); Iterator it = conns.keySet().iterator(); CacheConnection cc; CacheConnection dObj=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_OBJECT); CacheConnection dTmp=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_TEMPLATE); CacheConnection dQry=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_QUERY); CacheConnection dRes=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_RESOURCE); CacheConnection dUDF=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_FUNCTION); CacheConnection dInc=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_INCLUDE); CacheConnection dHTT=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_HTTP); CacheConnection dFil=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_FILE); CacheConnection dWSe=config.getCacheDefaultConnection(ConfigImpl.CACHE_TYPE_WEBSERVICE); Struct sct; String d; while(it.hasNext()) { String key=(String)it.next(); if(key.equalsIgnoreCase(name)) { cc=(CacheConnection) conns.get(key); sct=new StructImpl(); d=""; if(cc==dObj)d="object"; else if(cc==dTmp)d="template"; else if(cc==dQry)d="query"; else if(cc==dRes)d="resource"; else if(cc==dUDF)d="function"; else if(cc==dInc)d="include"; else if(cc==dHTT)d="http"; else if(cc==dFil)d="file"; else if(cc==dWSe)d="webservice"; sct.setEL(KeyConstants._name,cc.getName()); sct.setEL(KeyConstants._class,cc.getClassDefinition().getClassName()); sct.setEL(KeyConstants._bundleName,cc.getClassDefinition().getName()); sct.setEL(KeyConstants._bundleVersion,cc.getClassDefinition().getVersionAsString()); sct.setEL(KeyConstants._custom,cc.getCustom()); sct.setEL(KeyConstants._default,d); sct.setEL("readOnly",Caster.toBoolean(cc.isReadOnly())); sct.setEL("storage",Caster.toBoolean(cc.isStorage())); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); return; } } throw new ApplicationException("there is no cache connection with name ["+name+"]"); } private void doRemoveCacheConnection() throws PageException { admin.removeCacheConnection(getString("admin",action,"name")); store(); adminSync.broadcast(attributes, config); } private void doRemoveGatewayEntry() throws PageException { admin.removeCacheGatewayEntry(getString("admin",action,"id")); store(); adminSync.broadcast(attributes, config); } private void doRemoveDebugEntry() throws PageException { admin.removeDebugEntry(getString("admin",action,"id")); store(); adminSync.broadcast(attributes, config); } private void doVerifyCacheConnection() throws PageException { try { Cache cache = Util.getCache(pageContext.getConfig(), getString("admin",action,"name")); if(cache instanceof CachePro) ((CachePro)cache).verify(); else cache.getCustomInfo(); } catch (IOException e) { throw Caster.toPageException(e); } } /** * @throws PageException * */ private void doGetDatasource() throws PageException { String name=getString("admin",action,"name"); Map ds = config.getDataSourcesAsMap(); Iterator it = ds.keySet().iterator(); while(it.hasNext()) { String key=(String)it.next(); if(key.equalsIgnoreCase(name)) { DataSource d=(DataSource) ds.get(key); Struct sct=new StructImpl(); ClassDefinition cd = d.getClassDefinition(); sct.setEL(KeyConstants._name,key); sct.setEL(KeyConstants._host,d.getHost()); sct.setEL("classname",cd.getClassName()); sct.setEL("class",cd.getClassName()); sct.setEL("bundleName",cd.getName()); sct.setEL("bundleVersion",cd.getVersionAsString()); sct.setEL("dsn",d.getDsnOriginal()); sct.setEL("database",d.getDatabase()); sct.setEL("port",d.getPort()<1?"":Caster.toString(d.getPort())); sct.setEL("dsnTranslated",d.getDsnTranslated()); sct.setEL("timezone",toStringTimeZone(d.getTimeZone())); sct.setEL("password",d.getPassword()); sct.setEL("passwordEncrypted",ConfigWebFactory.encrypt(d.getPassword())); sct.setEL("username",d.getUsername()); sct.setEL("readonly",Caster.toBoolean(d.isReadOnly())); sct.setEL("select",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_SELECT))); sct.setEL("delete",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DELETE))); sct.setEL("update",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_UPDATE))); sct.setEL("insert",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT))); sct.setEL("create",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_CREATE))); sct.setEL("insert",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT))); sct.setEL("drop",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DROP))); sct.setEL("grant",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_GRANT))); sct.setEL("revoke",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_REVOKE))); sct.setEL("alter",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_ALTER))); sct.setEL("connectionLimit",d.getConnectionLimit()<1?"":Caster.toString(d.getConnectionLimit())); sct.setEL("connectionTimeout",d.getConnectionTimeout()<1?"":Caster.toString(d.getConnectionTimeout())); sct.setEL("metaCacheTimeout",Caster.toDouble(d.getMetaCacheTimeout())); sct.setEL("custom",d.getCustoms()); sct.setEL("blob",Boolean.valueOf(d.isBlob())); sct.setEL("clob",Boolean.valueOf(d.isClob())); sct.setEL("validate",Boolean.valueOf(d.validate())); sct.setEL("storage",Boolean.valueOf(d.isStorage())); if (d instanceof DataSourceImpl) { sct.setEL("dbdriver", Caster.toString( ((DataSourceImpl)d).getDbDriver(), "" )); } pageContext.setVariable(getString("admin",action,"returnVariable"),sct); return; } } throw new ApplicationException("there is no datasource with name ["+name+"]"); } private Object toStringTimeZone(TimeZone timeZone) { if(timeZone==null) return ""; return timeZone.getID(); } private void doGetRemoteClient() throws PageException { String url=getString("admin",action,"url"); RemoteClient[] clients = config.getRemoteClients(); RemoteClient client; for(int i=0;i<clients.length;i++) { client=clients[i]; if(client.getUrl().equalsIgnoreCase(url)) { Struct sct=new StructImpl(); ProxyData pd = client.getProxyData(); sct.setEL("label",client.getLabel()); sct.setEL("usage",client.getUsage()); sct.setEL("securityKey",client.getSecurityKey()); sct.setEL("adminPassword",client.getAdminPassword()); sct.setEL("ServerUsername",client.getServerUsername()); sct.setEL("ServerPassword",client.getServerPassword()); sct.setEL("type",client.getType()); sct.setEL("url",client.getUrl()); sct.setEL("proxyServer",pd==null?"":StringUtil.emptyIfNull(pd.getServer())); sct.setEL("proxyUsername",pd==null?"":StringUtil.emptyIfNull(pd.getUsername())); sct.setEL("proxyPassword",pd==null?"":StringUtil.emptyIfNull(pd.getPassword())); sct.setEL("proxyPort",pd==null?"":(pd.getPort()==-1?"":Caster.toString(pd.getPort()))); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); return; } } throw new ApplicationException("there is no remote client with url ["+url+"]"); } private void doGetSpoolerTasks() throws PageException { int startrow = getInt("startrow",1); if(startrow <1) startrow=1; int maxrow = getInt("maxrow",-1); String result=getString("result", null); SpoolerEngineImpl engine = (SpoolerEngineImpl) config.getSpoolerEngine(); Query qry = engine.getAllTasksAsQuery(startrow,maxrow); pageContext.setVariable(getString("admin",action,"returnVariable"),qry); if(!StringUtil.isEmpty(result)){ Struct sct=new StructImpl(); pageContext.setVariable(result,sct); sct.setEL("open", engine.getOpenTaskCount()); sct.setEL("closed", engine.getClosedTaskCount()); } /* SpoolerTask[] open = config.getSpoolerEngine().getOpenTasks(); SpoolerTask[] closed = config.getSpoolerEngine().getClosedTasks(); String v="VARCHAR"; lucee.runtime.type.Query qry=new QueryImpl( new String[]{"type","name","detail","id","lastExecution","nextExecution","closed","tries","exceptions","triesmax"}, new String[]{v,v,"object",v,d,d,"boolean","int","object","int"}, open.length+closed.length,"query"); int row=0; row=doGetRemoteClientTasks(qry,open,row); doGetRemoteClientTasks(qry,closed,row); pageContext.setVariable(getString("admin",action,"returnVariable"),qry); */ } private int doGetRemoteClientTasks(lucee.runtime.type.Query qry, SpoolerTask[] tasks, int row) { SpoolerTask task; for(int i=0;i<tasks.length;i++) { row++; task=tasks[i]; try{ qry.setAt("type", row, task.getType()); qry.setAt("name", row, task.subject()); qry.setAt("detail", row, task.detail()); qry.setAt("id", row, task.getId()); qry.setAt("lastExecution", row,new DateTimeImpl(pageContext,task.lastExecution(),true)); qry.setAt("nextExecution", row,new DateTimeImpl(pageContext,task.nextExecution(),true)); qry.setAt("closed", row,Caster.toBoolean(task.closed())); qry.setAt("tries", row,Caster.toDouble(task.tries())); qry.setAt("triesmax", row,Caster.toDouble(task.tries())); qry.setAt("exceptions", row,translateTime(task.getExceptions())); int triesMax=0; ExecutionPlan[] plans = task.getPlans(); for(int y=0;y<plans.length;y++) { triesMax+=plans[y].getTries(); } qry.setAt("triesmax", row,Caster.toDouble(triesMax)); } catch(Throwable t){} } return row; } private Array translateTime(Array exp) { exp=(Array) Duplicator.duplicate(exp,true); Iterator<Object> it = exp.valueIterator(); Struct sct; while(it.hasNext()) { sct=(Struct) it.next(); sct.setEL("time",new DateTimeImpl(pageContext,Caster.toLongValue(sct.get("time",null),0),true)); } return exp; } private void doGetRemoteClients() throws PageException { RemoteClient[] clients = config.getRemoteClients(); RemoteClient client; ProxyData pd; lucee.runtime.type.Query qry=new QueryImpl(new String[]{"label","usage","securityKey","adminPassword","serverUsername","serverPassword","type","url", "proxyServer","proxyUsername","proxyPassword","proxyPort"},clients.length,"query"); int row=0; for(int i=0;i<clients.length;i++) { client=clients[i]; pd=client.getProxyData(); row=i+1; qry.setAt("label",row,client.getLabel()); qry.setAt("usage",row,client.getUsage()); qry.setAt("securityKey",row,client.getSecurityKey()); qry.setAt("adminPassword",row,client.getAdminPassword()); qry.setAt("ServerUsername",row,client.getServerUsername()); qry.setAt("ServerPassword",row,client.getServerPassword()); qry.setAt("type",row,client.getType()); qry.setAt("url",row,client.getUrl()); qry.setAt("proxyServer",row,pd==null?"":pd.getServer()); qry.setAt("proxyUsername",row,pd==null?"":pd.getUsername()); qry.setAt("proxyPassword",row,pd==null?"":pd.getPassword()); qry.setAt("proxyPort",row,pd==null?"":Caster.toString(pd.getPort())); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } private void doSetCluster() {// MUST remove this try { _doSetCluster(); } catch (Throwable t) { //print.printST(t); } } private void _doSetCluster() throws PageException { Struct entries = Caster.toStruct(getObject("admin",action,"entries")); Struct entry; Iterator<Object> it = entries.valueIterator(); Cluster cluster = pageContext.clusterScope(); while(it.hasNext()) { entry=Caster.toStruct(it.next()); cluster.setEntry( new ClusterEntryImpl( KeyImpl.getInstance(Caster.toString(entry.get(KeyConstants._key))), Caster.toSerializable(entry.get(KeyConstants._value,null),null), Caster.toLongValue(entry.get(KeyConstants._time)) ) ); } cluster.broadcast(); } private void doGetCluster() throws PageException { pageContext.setVariable( getString("admin",action,"returnVariable"), ((PageContextImpl)pageContext).clusterScope(false) ); } private void doGetToken() throws PageException { pageContext.setVariable( getString("admin",action,"returnVariable"), config.getIdentification().getSecurityToken() ); } private void doGetJDBCDrivers() throws PageException { JDBCDriver[] drivers = config.getJDBCDrivers(); lucee.runtime.type.Query qry=new QueryImpl( new Key[]{KeyConstants._label,KeyConstants._class,KeyConstants._bundleName,KeyConstants._bundleVersion}, drivers.length,"jdbc"); JDBCDriver driver; for(int row=0;row<drivers.length;row++) { driver=drivers[row]; qry.setAt(KeyConstants._label,row,driver.label); qry.setAt(KeyConstants._class,row,driver.cd.getClassName()); qry.setAt(KeyConstants._bundleName,row,driver.cd.getName()); qry.setAt(KeyConstants._bundleVersion,row,driver.cd.getVersion().toString()); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } /** * @throws PageException * */ private void doGetDatasources() throws PageException { Map ds = config.getDataSourcesAsMap(); Iterator it = ds.keySet().iterator(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"name","host","classname","bundleName","bundleVersion","dsn","DsnTranslated","database","port", "timezone","username","password","passwordEncrypted","readonly" ,"grant","drop","create","revoke","alter","select","delete","update","insert" ,"connectionLimit","connectionTimeout","clob","blob","validate","storage","customSettings","metaCacheTimeout"},ds.size(),"query"); int row=0; while(it.hasNext()) { Object key=it.next(); DataSource d=(DataSource) ds.get(key); row++; qry.setAt(KeyConstants._name,row,key); qry.setAt(KeyConstants._host,row,d.getHost()); qry.setAt("classname",row,d.getClassDefinition().getClassName()); qry.setAt("bundleName",row,d.getClassDefinition().getName()); qry.setAt("bundleVersion",row,d.getClassDefinition().getVersionAsString()); qry.setAt("dsn",row,d.getDsnOriginal()); qry.setAt("database",row,d.getDatabase()); qry.setAt(KeyConstants._port,row,d.getPort()<1?"":Caster.toString(d.getPort())); qry.setAt("dsnTranslated",row,d.getDsnTranslated()); qry.setAt("timezone",row,toStringTimeZone(d.getTimeZone())); qry.setAt(KeyConstants._password,row,d.getPassword()); qry.setAt("passwordEncrypted",row,ConfigWebFactory.encrypt(d.getPassword())); qry.setAt(KeyConstants._username,row,d.getUsername()); qry.setAt(KeyConstants._readonly,row,Caster.toBoolean(d.isReadOnly())); qry.setAt(KeyConstants._select,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_SELECT))); qry.setAt(KeyConstants._delete,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DELETE))); qry.setAt(KeyConstants._update,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_UPDATE))); qry.setAt(KeyConstants._create,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_CREATE))); qry.setAt(KeyConstants._insert,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT))); qry.setAt(KeyConstants._drop,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DROP))); qry.setAt(KeyConstants._grant,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_GRANT))); qry.setAt(KeyConstants._revoke,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_REVOKE))); qry.setAt(KeyConstants._alter,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_ALTER))); qry.setAt("connectionLimit",row,d.getConnectionLimit()<1?"":Caster.toString(d.getConnectionLimit())); qry.setAt("connectionTimeout",row,d.getConnectionTimeout()<1?"":Caster.toString(d.getConnectionTimeout())); qry.setAt("customSettings",row,d.getCustoms()); qry.setAt("blob",row,Boolean.valueOf(d.isBlob())); qry.setAt("clob",row,Boolean.valueOf(d.isClob())); qry.setAt("validate",row,Boolean.valueOf(d.validate())); qry.setAt("storage",row,Boolean.valueOf(d.isStorage())); qry.setAt("metaCacheTimeout",row,Caster.toDouble(d.getMetaCacheTimeout())); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } /** * @throws PageException * */ private void doUpdateScope() throws PageException { admin.updateScopeCascadingType(getString("admin",action,"scopeCascadingType")); admin.updateAllowImplicidQueryCall(getBoolObject("admin",action,"allowImplicidQueryCall")); admin.updateMergeFormAndUrl(getBoolObject("admin",action,"mergeFormAndUrl")); admin.updateSessionManagement(getBoolObject("admin",action,"sessionManagement")); admin.updateClientManagement(getBoolObject("admin",action,"clientManagement")); admin.updateDomaincookies(getBoolObject("admin",action,"domainCookies")); admin.updateClientCookies(getBoolObject("admin",action,"clientCookies")); //admin.updateRequestTimeout(getTimespan("admin",action,"requestTimeout")); admin.updateClientTimeout(getTimespan("admin",action,"clientTimeout")); admin.updateSessionTimeout(getTimespan("admin",action,"sessionTimeout")); admin.updateClientStorage(getString("admin",action,"clientStorage")); admin.updateSessionStorage(getString("admin",action,"sessionStorage")); admin.updateApplicationTimeout(getTimespan("admin",action,"applicationTimeout")); admin.updateSessionType(getString("admin",action,"sessionType")); admin.updateLocalMode(getString("admin",action,"localMode")); store(); adminSync.broadcast(attributes, config); } private void doUpdateRestSettings() throws PageException { admin.updateRestList(getBool("list", null)); //admin.updateRestAllowChanges(getBool("allowChanges", null)); store(); adminSync.broadcast(attributes, config); } private void doUpdateApplicationSettings() throws PageException { admin.updateRequestTimeout(getTimespan("admin",action,"requestTimeout")); admin.updateScriptProtect(getString("admin",action,"scriptProtect")); admin.updateAllowURLRequestTimeout(getBoolObject("admin",action,"allowURLRequestTimeout")); // DIFF 23 store(); adminSync.broadcast(attributes, config); } private void doUpdateOutputSettings() throws PageException { admin.updateCFMLWriterType(getString("admin",action, "cfmlWriter")); admin.updateSuppressContent(getBoolObject("admin",action, "suppressContent")); //admin.updateShowVersion(getBoolObject("admin",action, "showVersion")); admin.updateAllowCompression(getBoolObject("admin",action, "allowCompression")); admin.updateContentLength(getBoolObject("admin",action, "contentLength")); admin.updateBufferOutput(getBoolObject("admin",action, "bufferOutput")); store(); adminSync.broadcast(attributes, config); } private void doUpdateCustomTagSetting() throws PageException { admin.updateCustomTagDeepSearch(getBool("admin", action, "deepSearch")); admin.updateCustomTagLocalSearch(getBool("admin", action, "localSearch")); admin.updateCTPathCache(getBool("admin", action, "customTagPathCache")); admin.updateCustomTagExtensions(getString("admin", action, "extensions")); store(); adminSync.broadcast(attributes, config); } /*private void doUpdateUpdateLogSettings() throws PageException { int level=LogUtil.toIntType(getString("admin", "updateUpdateLogSettings", "level"), -1); String source=getString("admin", "updateUpdateLogSettings", "path"); if(source.indexOf("{")==-1){ Resource res = ResourceUtil.toResourceNotExisting(pageContext, source, false); String tmp=SystemUtil.addPlaceHolder(res, config, null); if(tmp!=null) source=tmp; else source=ContractPath.call(pageContext, source); } admin.updateLogSettings( getString("admin", "updateUpdateLogSettings", "name"), level, source, getInt("admin", "updateUpdateLogSettings", "maxfile"), getInt("admin", "updateUpdateLogSettings", "maxfilesize") ); store(); adminSync.broadcast(attributes, config); }*/ private void doUpdateMonitor() throws PageException { ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.updateMonitor( cd, getString("admin", "updateMonitor", "monitorType"), getString("admin", "updateMonitor", "name"), getBool("admin", "updateMonitor", "logEnabled") ); store(); adminSync.broadcast(attributes, config); } private void doUpdateORMEngine() throws PageException { ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.updateORMEngine(cd); store(); adminSync.broadcast(attributes, config); } private void doUpdateCacheHandler() throws PageException { ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.updateCacheHandler( getString("admin", "updateCacheHandler", "id"), cd ); store(); adminSync.broadcast(attributes, config); } private void doUpdateExecutionLog() throws PageException { lucee.runtime.db.ClassDefinition cd = new ClassDefinitionImpl( getString("admin",action,"class") , getString("bundleName",null) ,getString("bundleVersion",null), config.getIdentification()); admin.updateExecutionLog( cd, getStruct("admin", "updateExecutionLog", "arguments"), getBool("admin", "updateExecutionLog", "enabled") ); store(); adminSync.broadcast(attributes, config); } private void doRemoveMonitor() throws PageException { admin.removeMonitor( getString("admin", "removeMonitor", "type"), getString("admin", "removeMonitor", "name") ); store(); adminSync.broadcast(attributes, config); } private void doRemoveCacheHandler() throws PageException { admin.removeCacheHandler( getString("admin", "removeCacheHandler", "id") ); store(); adminSync.broadcast(attributes, config); } private void doRemoveORMEngine() throws PageException { admin.removeORMEngine(); store(); adminSync.broadcast(attributes, config); } private void doUpdateRHExtension() throws PageException { // this can be a binary that represent the extension or a string that is a path to the extension Object obj = getObject("admin", "UpdateRHExtensions", "source"); // path if(obj instanceof String) { Resource src = ResourceUtil.toResourceExisting(config, (String)obj); ConfigWebAdmin.updateRHExtension(config, src,true); } else { try{ Resource tmp = SystemUtil.getTempFile("lex", true); IOUtil.copy(new ByteArrayInputStream(Caster.toBinary(obj)), tmp, true); ConfigWebAdmin.updateRHExtension(config, tmp,true); } catch(IOException ioe){ throw Caster.toPageException(ioe); } } } private void doRemoveRHExtension() throws PageException { String id = getString("admin", "removeRHExtensions", "id"); if(!Decision.isUUId(id)) throw new ApplicationException("invalid id ["+id+"], id must be a UUID"); try { admin.removeRHExtension(id); } catch (Exception e) { throw Caster.toPageException(e); } store(); } private void doUpdateExtension() throws PageException { admin.updateExtension(pageContext,new ExtensionImpl( getStruct("config", null), getString("admin", "UpdateExtensions", "id"), getString("admin", "UpdateExtensions","provider"), getString("admin", "UpdateExtensions","version"), getString("admin", "UpdateExtensions","name"), getString("label",""), getString("description",""), getString("category",""), getString("image",""), getString("author",""), getString("codename",""), getString("video",""), getString("support",""), getString("documentation",""), getString("forum",""), getString("mailinglist",""), getString("network",""), getDateTime("created",null), getString("admin", "UpdateExtensions","_type") )); store(); //adminSync.broadcast(attributes, config); } private void doUpdateExtensionProvider() throws PageException { admin.updateExtensionProvider( getString("admin", "UpdateExtensionProvider","url") ); store(); } private void doUpdateRHExtensionProvider() throws PageException { try { admin.updateRHExtensionProvider( getString("admin", "UpdateRHExtensionProvider","url") ); } catch (MalformedURLException e) { throw Caster.toPageException(e); } store(); } private void doUpdateExtensionInfo() throws PageException { admin.updateExtensionInfo( getBool("admin", "UpdateExtensionInfo","enabled") ); store(); } private void doVerifyExtensionProvider() throws PageException { admin.verifyExtensionProvider(getString("admin", "VerifyExtensionProvider","url")); } private void doResetId() throws PageException { admin.resetId(); store(); } private void doRemoveExtensionProvider() throws PageException { admin.removeExtensionProvider(getString("admin", "RemoveExtensionProvider","url")); store(); } private void doRemoveRHExtensionProvider() throws PageException { admin.removeRHExtensionProvider(getString("admin", "RemoveRHExtensionProvider","url")); store(); } /** * @throws PageException * */ private void doGetApplicationSetting() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); sct.set("scriptProtect",AppListenerUtil.translateScriptProtect(config.getScriptProtect())); // request timeout sct.set("requestTimeout",config.getRequestTimeout()); sct.set("requestTimeout_day",Caster.toInteger(config.getRequestTimeout().getDay())); sct.set("requestTimeout_hour",Caster.toInteger(config.getRequestTimeout().getHour())); sct.set("requestTimeout_minute",Caster.toInteger(config.getRequestTimeout().getMinute())); sct.set("requestTimeout_second",Caster.toInteger(config.getRequestTimeout().getSecond())); // AllowURLRequestTimeout sct.set("AllowURLRequestTimeout",Caster.toBoolean(config.isAllowURLRequestTimeout()));// DIF 23 } private void doGetOutputSetting() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); sct.set("suppressContent",Caster.toBoolean(config.isSuppressContent())); sct.set("contentLength",Caster.toBoolean(config.contentLength())); //sct.set("showVersion",Caster.toBoolean(config.isShowVersion())); sct.set("allowCompression",Caster.toBoolean(config.allowCompression())); int wt = config.getCFMLWriterType(); String cfmlWriter="regular"; if(wt==ConfigImpl.CFML_WRITER_WS) cfmlWriter="white-space"; else if(wt==ConfigImpl.CFML_WRITER_WS_PREF) cfmlWriter="white-space-pref"; sct.set("cfmlWriter",cfmlWriter); sct.set("bufferOutput",Caster.toBoolean(config.getBufferOutput())); } /** * @throws PageException * */ private void doGetScope() throws PageException { String sessionType=config.getSessionType()==Config.SESSION_TYPE_JEE?"j2ee":"cfml"; String localMode=AppListenerUtil.toLocalMode(config.getLocalMode(),"classic"); Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); sct.set("allowImplicidQueryCall",Caster.toBoolean(config.allowImplicidQueryCall())); sct.set("mergeFormAndUrl",Caster.toBoolean(config.mergeFormAndURL())); sct.set("sessiontype",sessionType); sct.set("localmode",localMode); sct.set("sessionManagement",Caster.toBoolean(config.isSessionManagement())); sct.set("clientManagement",Caster.toBoolean(config.isClientManagement())); sct.set("domainCookies",Caster.toBoolean(config.isDomainCookies())); sct.set("clientCookies",Caster.toBoolean(config.isClientCookies())); sct.set("clientStorage",config.getClientStorage()); sct.set("sessionStorage",config.getSessionStorage()); TimeSpan ts=config.getSessionTimeout(); sct.set("sessionTimeout",ts); sct.set("sessionTimeout_day",Caster.toInteger(ts.getDay())); sct.set("sessionTimeout_hour",Caster.toInteger(ts.getHour())); sct.set("sessionTimeout_minute",Caster.toInteger(ts.getMinute())); sct.set("sessionTimeout_second",Caster.toInteger(ts.getSecond())); ts=config.getApplicationTimeout(); sct.set("applicationTimeout",ts); sct.set("applicationTimeout_day",Caster.toInteger(ts.getDay())); sct.set("applicationTimeout_hour",Caster.toInteger(ts.getHour())); sct.set("applicationTimeout_minute",Caster.toInteger(ts.getMinute())); sct.set("applicationTimeout_second",Caster.toInteger(ts.getSecond())); ts=config.getClientTimeout(); sct.set("clientTimeout",ts); sct.set("clientTimeout_day",Caster.toInteger(ts.getDay())); sct.set("clientTimeout_hour",Caster.toInteger(ts.getHour())); sct.set("clientTimeout_minute",Caster.toInteger(ts.getMinute())); sct.set("clientTimeout_second",Caster.toInteger(ts.getSecond())); // scope cascading type if(config.getScopeCascadingType()==Config.SCOPE_STRICT) sct.set("scopeCascadingType","strict"); else if(config.getScopeCascadingType()==Config.SCOPE_SMALL) sct.set("scopeCascadingType","small"); else if(config.getScopeCascadingType()==Config.SCOPE_STANDARD) sct.set("scopeCascadingType","standard"); } /** * @throws PageException * */ private void doUpdateComponent() throws PageException { admin.updateComponentDeepSearch(getBoolObject("admin", action, "deepSearch")); admin.updateBaseComponent(getString("admin",action,"baseComponentTemplateCFML"),getString("admin",action,"baseComponentTemplateLucee")); admin.updateComponentDumpTemplate(getString("admin",action,"componentDumpTemplate")); admin.updateComponentDataMemberDefaultAccess(getString("admin",action,"componentDataMemberDefaultAccess")); admin.updateTriggerDataMember(getBoolObject("admin",action,"triggerDataMember")); admin.updateComponentUseShadow(getBoolObject("admin",action,"useShadow")); admin.updateComponentDefaultImport(getString("admin",action,"componentDefaultImport")); admin.updateComponentLocalSearch(getBoolObject("admin",action,"componentLocalSearch")); admin.updateComponentPathCache(getBoolObject("admin",action,"componentPathCache")); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * @throws PageException * */ private void doGetComponent() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); // Base Component try { PageSource psCFML = config.getBaseComponentPageSource(CFMLEngine.DIALECT_CFML); if(psCFML!=null && psCFML.exists()) sct.set("baseComponentTemplateCFML",psCFML.getDisplayPath()); else sct.set("baseComponentTemplateCFML",""); } catch (PageException e) { sct.set("baseComponentTemplateCFML",""); } try { PageSource psLucee = config.getBaseComponentPageSource(CFMLEngine.DIALECT_LUCEE); if(psLucee!=null && psLucee.exists()) sct.set("baseComponentTemplateLucee",psLucee.getDisplayPath()); else sct.set("baseComponentTemplateLucee",""); } catch (PageException e) { sct.set("baseComponentTemplateLucee",""); } sct.set("strBaseComponentTemplateCFML",config.getBaseComponentTemplate(CFMLEngine.DIALECT_CFML)); sct.set("strBaseComponentTemplateLucee",config.getBaseComponentTemplate(CFMLEngine.DIALECT_LUCEE)); // dump template try { PageSource ps = ((PageContextImpl)pageContext).getPageSourceExisting(config.getComponentDumpTemplate()); if(ps!=null) sct.set("componentDumpTemplate",ps.getDisplayPath()); else sct.set("componentDumpTemplate",""); } catch (PageException e) { sct.set("componentDumpTemplate",""); } sct.set("strComponentDumpTemplate",config.getComponentDumpTemplate()); sct.set("deepSearch",Caster.toBoolean(config.doComponentDeepSearch())); sct.set("componentDataMemberDefaultAccess",ComponentUtil.toStringAccess(config.getComponentDataMemberDefaultAccess())); sct.set("triggerDataMember",Caster.toBoolean(config.getTriggerComponentDataMember())); sct.set("useShadow",Caster.toBoolean(config.useComponentShadow())); sct.set("ComponentDefaultImport",config.getComponentDefaultImport()); sct.set("componentLocalSearch",config.getComponentLocalSearch()); sct.set("componentPathCache",config.useComponentPathCache()); } /** * @throws PageException * */ private void doUpdateRegional() throws PageException { Boolean useTimeServer=getBool("usetimeserver",null); try{ admin.updateLocale(getString("admin",action,"locale")); admin.updateTimeZone(getString("admin",action,"timezone")); admin.updateTimeServer(getString("admin",action,"timeserver"),useTimeServer); admin.updateTimeZone(getString("admin",action,"timezone")); } finally { store(); } adminSync.broadcast(attributes, config); } private void doUpdateMonitorEnabled() throws PageException { try{ admin.updateMonitorEnabled(getBool("admin","UpdateMonitorEnabled","monitorEnabled")); } finally { store(); } adminSync.broadcast(attributes, config); } private void doUpdateTLD() throws PageException { try { String jar = getString("jar",null); if(!StringUtil.isEmpty(jar,true)){ Resource resJar = ResourceUtil.toResourceExisting(pageContext, jar); admin.updateJar(resJar); } Resource resTld = ResourceUtil.toResourceExisting(pageContext, getString("admin",action,"tld")); admin.updateTLD(resTld); } catch (Exception e) { throw Caster.toPageException(e); } store(); } private void doUpdateFLD() throws PageException { try { String jar = getString("jar",null); if(!StringUtil.isEmpty(jar,true)){ Resource resJar = ResourceUtil.toResourceExisting(pageContext, jar); admin.updateJar(resJar); } Resource resFld = ResourceUtil.toResourceExisting(pageContext, getString("admin",action,"fld")); admin.updateFLD(resFld); } catch (Exception e) { throw Caster.toPageException(e); } store(); } private void doUpdateJar() throws PageException { try { Resource resJar = ResourceUtil.toResourceExisting(pageContext, getString("admin",action,"jar")); admin.updateJar(resJar); } catch (Exception e) { throw Caster.toPageException(e); } store(); } private void doUpdateLoginSettings() throws PageException { boolean rememberMe = getBool("admin", "UpdateLoginSettings", "rememberme"); boolean captcha = getBool("admin", "UpdateLoginSettings", "captcha"); int delay = getInt("admin", "UpdateLoginSettings", "delay"); admin.updateLoginSettings(captcha,rememberMe,delay); store(); } private void doUpdateLogSettings() throws PageException { String str = getString("admin", "UpdateLogSettings", "level", true); Level l = Log4jUtil.toLevel(str,null); if(l==null)throw new ApplicationException("invalid log level name ["+str+"], valid log level names are [INFO,DEBUG,WARN,ERROR,FATAL,TRACE]"); ClassDefinition acd=new ClassDefinitionImpl( getString("admin", action, "appenderClass", true) , getString("appenderBundleName", null) , getString("appenderBundleVersion", null) , config.getIdentification() ); ClassDefinition lcd=new ClassDefinitionImpl( getString("admin", action, "layoutClass", true) , getString("layoutBundleName", null) , getString("layoutBundleVersion", null) , config.getIdentification() ); admin.updateLogSettings( getString("admin", "UpdateLogSettings", "name", true) ,l ,acd ,Caster.toStruct(getObject("admin", "UpdateLogSettings", "appenderArgs")) ,lcd ,Caster.toStruct(getObject("admin", "UpdateLogSettings", "layoutArgs")) ); store(); } private void doUpdateSSLCertificate() throws PageException { String host=getString("admin", "UpdateSSLCertificateInstall", "host"); int port = getInt("port", 443); updateSSLCertificate(config, host, port); } public static void updateSSLCertificate(Config config,String host, int port) throws PageException { Resource cacerts=config.getSecurityDirectory(); try { CertificateInstaller installer = new CertificateInstaller(cacerts,host,port); installer.installAll(); } catch (Exception e) { throw Caster.toPageException(e); } } private void doGetSSLCertificate() throws PageException { String host=getString("admin", "GetSSLCertificate", "host"); int port = getInt("port", 443); pageContext.setVariable(getString("admin",action,"returnVariable"),getSSLCertificate(config,host,port)); } public static Query getSSLCertificate(Config config,String host, int port) throws PageException { Resource cacerts=config.getSecurityDirectory(); CertificateInstaller installer; try { installer = new CertificateInstaller(cacerts,host,port); } catch (Exception e) { throw Caster.toPageException(e); } X509Certificate[] certs = installer.getCertificates(); X509Certificate cert; Query qry=new QueryImpl(new String[]{"subject","issuer"},certs.length,"certificates"); for(int i=0;i<certs.length;i++){ cert=certs[i]; qry.setAtEL("subject",i+1, cert.getSubjectDN().getName()); qry.setAtEL("issuer",i+1, cert.getIssuerDN().getName()); } return qry; } private void doRemoveBundle() throws PageException { try { String name=getString("admin",action,"name"); String version=getString("admin",action,"version"); boolean removePhysical=getBoolV("removePhysical", true); OSGiUtil.removeLocalBundle(name.trim(),OSGiUtil.toVersion(version.trim()),removePhysical); } catch (Exception e) { throw Caster.toPageException(e); } store(); } private void doRemoveTLD() throws PageException { try { String name = getString("tld",null); if(StringUtil.isEmpty(name))name=getString("admin",action,"name"); admin.removeTLD(name); } catch (Exception e) { throw Caster.toPageException(e); } store(); } private void doRemoveFLD() throws PageException { try { String name = getString("fld",null); if(StringUtil.isEmpty(name))name=getString("admin",action,"name"); admin.removeFLD(name); } catch (Exception e) { throw Caster.toPageException(e); } store(); } private void doUpdateRemoteClient() throws PageException { admin.updateRemoteClient( getString("admin",action,"label"), getString("admin",action,"url"), getString("admin",action,"remotetype"), getString("admin",action,"securityKey"), getString("admin",action,"usage"), getString("admin",action,"adminPassword"), getString("ServerUsername",""), getString("ServerPassword",""), getString("proxyServer",""), getString("proxyUsername",""), getString("proxyPassword",""), getString("proxyPort","") ); store(); } private void doReadBundle() throws PageException { String ret=getString("admin",action,"returnvariable"); Resource res=ResourceUtil.toResourceExisting(pageContext, getString("admin",action,"bundle")); if(!res.isFile()) throw new ApplicationException("["+res+"] is not a file"); try { Struct sct=new StructImpl(); pageContext.setVariable(ret, new BundleFile(res).info()); } catch (Exception e) { throw Caster.toPageException(e); } } private void doBuildBundle() throws PageException { String name=getString("admin",action,"name"); String symName=getString("symbolicname",null); String existingRelation=getString("existingrelation",null); boolean doDyn=StringUtil.isEmpty(existingRelation) || existingRelation.equalsIgnoreCase("dynamic"); boolean ignoreExistingManifest=getBoolV("ignoreExistingManifest",false); Resource dest=ResourceUtil.toResourceNotExisting(pageContext, getString("admin",action,"destination")); String strJar=getString("admin",action,"jar"); if(StringUtil.isEmpty(strJar,true)) throw new ApplicationException("missing valid jar path"); Resource jar = ResourceUtil.toResourceExisting(pageContext,strJar.trim()); Set<String> relatedPackages=null; try { relatedPackages=JarUtil.getExternalImports(jar, OSGiUtil.getBootdelegation()); } catch (IOException e1) { e1.printStackTrace(); } if(relatedPackages==null) relatedPackages=new HashSet<String>(); // org.osgi.framework.bootdelegation BundleBuilderFactory factory; try { symName=StringUtil.isEmpty(symName,true)?null:symName.trim(); if(symName==null)symName=name; factory = new BundleBuilderFactory(jar,symName); factory.setName(name); factory.setIgnoreExistingManifest(ignoreExistingManifest); } catch (Exception e) { throw Caster.toPageException(e); } String activator=getString("activator",null); if(!StringUtil.isEmpty(activator,true))factory.setActivator(activator.trim()); String version=getString("version",null); if(!StringUtil.isEmpty(version,true))factory.setVersion(OSGiUtil.toVersion(version,null)); String description=getString("description",null); if(!StringUtil.isEmpty(description,true))factory.setDescription(description.trim()); String classPath=getString("classPath",null); if(!StringUtil.isEmpty(classPath,true))factory.addClassPath(classPath.trim()); String dynamicImportPackage=getString("dynamicimportpackage",null); if(doDyn) { if(relatedPackages.size()>0) { // add importPackage to set if(!StringUtil.isEmpty(dynamicImportPackage)) { String[] arr = ListUtil.trimItems(ListUtil.listToStringArray(dynamicImportPackage, ',')); for(int i=0;i<arr.length;i++){ relatedPackages.add(arr[i]); } } dynamicImportPackage=ListUtil.toList(relatedPackages, ","); } relatedPackages.clear(); } if(!StringUtil.isEmpty(dynamicImportPackage,true))factory.addDynamicImportPackage(dynamicImportPackage.trim()); // Import Package String importPackage=getString("importpackage",null); // add importPackage to set if(!StringUtil.isEmpty(importPackage)) { String[] arr = ListUtil.trimItems(ListUtil.listToStringArray(importPackage, ',')); for(int i=0;i<arr.length;i++){ relatedPackages.add(arr[i]); } } // remove all packages defined in dynamic imports if(!StringUtil.isEmpty(dynamicImportPackage)) { String[] arr = ListUtil.trimItems(ListUtil.listToStringArray(dynamicImportPackage, ',')); List<String> newDynImport=new ArrayList<String>(); for(int i=0;i<arr.length;i++){ if(!relatedPackages.contains(arr[i])) newDynImport.add(arr[i]); //relatedPackages.remove(arr[i]); } if(arr.length!=newDynImport.size()) dynamicImportPackage=ListUtil.listToListEL(newDynImport, ","); } // Set to List importPackage=ListUtil.toList(relatedPackages, ","); if(!StringUtil.isEmpty(importPackage,true))factory.addImportPackage(importPackage.trim()); String exportPackage=getString("exportpackage",null); if(!StringUtil.isEmpty(exportPackage,true))factory.addExportPackage(exportPackage.trim()); String requireBundle=getString("requireBundle",null); if(!StringUtil.isEmpty(requireBundle,true))factory.addRequireBundle(requireBundle.trim()); String fragmentHost=getString("fragmentHost",null); if(!StringUtil.isEmpty(fragmentHost,true))factory.addFragmentHost(fragmentHost.trim()); try { factory.build(dest); } catch (IOException e) { throw Caster.toPageException(e); } } private void doUpdateRemoteClientUsage() throws PageException { admin.updateRemoteClientUsage( getString("admin",action,"code"), getString("admin",action,"displayname") ); store(); } private void doRemoveRemoteClientUsage() throws PageException { admin.removeRemoteClientUsage( getString("admin",action,"code") ); store(); } private String getCallerId() throws IOException { if(type==TYPE_WEB) { return config.getIdentification().getId(); } if(config instanceof ConfigWebImpl){ ConfigWebImpl cwi = (ConfigWebImpl)config; return cwi.getIdentification().getServerIdentification().getId(); } if(config instanceof ConfigServer){ return config.getIdentification().getId(); } throw new IOException("can not create id"); } private void doUpdateApplicationListener() throws PageException { admin.updateApplicationListener( getString("admin",action,"listenerType"), getString("admin",action,"listenerMode") ); store(); adminSync.broadcast(attributes, config); } private void doUpdateCachedWithin() throws PageException { String str = getString("admin",action,"cachedWithinType"); int type=AppListenerUtil.toCachedWithinType(str,-1); if(type==-1) throw new ApplicationException("cached within type ["+str+"] is invalid, valid types are [function,include,query,resource]"); admin.updateCachedWithin( type, getString("admin",action,"cachedWithin") ); store(); adminSync.broadcast(attributes, config); } private void doUpdateProxy() throws PageException { admin.updateProxy( getBool("admin",action,"proxyenabled"), getString("admin",action,"proxyserver"), getInt("admin",action,"proxyport"), getString("admin",action,"proxyusername"), getString("admin",action,"proxypassword") ); store(); } private void doUpdateCharset() throws PageException { admin.updateResourceCharset(getString("admin",action,"resourceCharset")); admin.updateTemplateCharset(getString("admin",action,"templateCharset")); admin.updateWebCharset(getString("admin",action,"webCharset")); store(); adminSync.broadcast(attributes, config); } /** * @throws PageException * */ private void doSecurityManager() throws PageException { String rtnVar = getString("admin",action,"returnVariable"); String secType = getString("admin",action,"sectype"); String secValue = getString("secvalue",null); boolean isServer=config instanceof ConfigServer; if(secValue==null) { if(isServer) { pageContext.setVariable( rtnVar, SecurityManagerImpl.toStringAccessValue(SecurityManager.VALUE_YES) ); } else { pageContext.setVariable( rtnVar, SecurityManagerImpl.toStringAccessValue(config.getSecurityManager().getAccess(secType)) ); } return; } pageContext.setVariable( rtnVar, Caster.toBoolean( isServer || config.getSecurityManager().getAccess(secType) == SecurityManagerImpl.toShortAccessValue(secValue) ) ); } /** * @throws PageException * */ private void doGetTimeZones() throws PageException { String strLocale=getString("locale","english (united kingdom)"); Locale locale = LocaleFactory.getLocale(strLocale); String[] timeZones = TimeZone.getAvailableIDs(); lucee.runtime.type.Query qry=new QueryImpl(new String[]{"id","display"},new String[]{"varchar","varchar"},timeZones.length,"timezones"); Arrays.sort(timeZones); TimeZone timeZone; for(int i=0;i<timeZones.length;i++) { timeZone=TimeZone.getTimeZone(timeZones[i]); qry.setAt("id",i+1,timeZones[i]); qry.setAt("display",i+1,timeZone.getDisplayName(locale)); } pageContext.setVariable(getString("admin",action,"returnVariable"),qry); } /** * @throws PageException * */ private void doGetLocales() throws PageException { Struct sct=new StructImpl(StructImpl.TYPE_LINKED); //Array arr=new ArrayImpl(); String strLocale=getString("locale","english (united kingdom)"); Locale locale = LocaleFactory.getLocale(strLocale); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); Map locales = LocaleFactory.getLocales(); Iterator it = locales.keySet().iterator(); String key; Locale l; while(it.hasNext()) { key=(String)it.next(); l=(Locale) locales.get(key); sct.setEL(l.toString(),l.getDisplayName(locale)); //arr.append(locale.getDisplayName()); } //arr.sort("textnocase","asc"); } private void doGetApplicationListener() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); ApplicationListener appListener = config.getApplicationListener(); sct.set("type",AppListenerUtil.toStringType(appListener)); sct.set("mode",AppListenerUtil.toStringMode(appListener.getMode())); // replaced with encoding outputsct.set("defaultencoding", config.get DefaultEncoding()); } /** * @throws PageException * */ private void doGetRegional() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); sct.set("locale",Caster.toString(config.getLocale())); sct.set("timezone",toStringTimeZone(pageContext.getTimeZone())); sct.set("timeserver",config.getTimeServer()); sct.set("usetimeserver",config.getUseTimeServer()); // replaced with encoding outputsct.set("defaultencoding", config.get DefaultEncoding()); } private void doIsMonitorEnabled() throws PageException { if(config instanceof ConfigServerImpl) { ConfigServerImpl cs=(ConfigServerImpl) config; pageContext.setVariable(getString("admin",action,"returnVariable"),Caster.toBoolean(cs.isMonitoringEnabled())); } } private void doSurveillance() throws PageException { // Server if(config instanceof ConfigServer) { ConfigServer cs=(ConfigServer) config; ConfigWeb[] webs = cs.getConfigWebs(); Struct sct=new StructImpl(); for(int i=0;i<webs.length;i++){ ConfigWebImpl cw=(ConfigWebImpl) webs[i]; try{ sct.setEL(cw.getLabel(), ((CFMLFactoryImpl)cw.getFactory()).getInfo()); } catch(Throwable t){} } pageContext.setVariable(getString("admin",action,"returnVariable"),sct); } // Web else { CFMLFactoryImpl factory = (CFMLFactoryImpl) ((ConfigWeb)config).getFactory(); pageContext.setVariable(getString("admin",action,"returnVariable"), factory.getInfo()); } } private void doStopThread() throws PageException { String contextId=getString("admin", "stopThread", "contextId"); String threadId=getString("admin", "stopThread", "threadId"); String stopType=getString("stopType","exception"); if(!(config instanceof ConfigServer)) throw new ApplicationException("invalid context for this action"); ConfigServer cs=(ConfigServer) config; ConfigWeb[] webs = cs.getConfigWebs(); for(int i=0;i<webs.length;i++){ ConfigWebImpl cw=(ConfigWebImpl) webs[i]; if(!cw.getIdentification().getId().equals(contextId)) continue; ((CFMLFactoryImpl)cw.getFactory()).stopThread(threadId,stopType); break; } } private void doHeapDump() throws PageException { String strDestination = getString( "admin", action, "destination" ); boolean live = getBoolV( "live" ,true); Resource destination = ResourceUtil.toResourceNotExisting(pageContext, strDestination); try { HeapDumper.dumpTo(destination, live); } catch (IOException e) { throw Caster.toPageException(e); } } private void doGetProxy() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); ProxyData pd = config.getProxyData(); String port=pd==null || pd.getPort()<=0?"":Caster.toString(pd.getPort()); //sct.set("enabled",Caster.toBoolean(config.isProxyEnable())); sct.set("port",port); sct.set("server",pd==null?"":emptyIfNull(pd.getServer())); sct.set("username",pd==null?"":emptyIfNull(pd.getUsername())); sct.set("password",pd==null?"":emptyIfNull(pd.getPassword())); } private void doGetLoginSettings() throws ApplicationException, PageException { Struct sct=new StructImpl(); ConfigImpl c = (ConfigImpl) ThreadLocalPageContext.getConfig(config); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); sct.set("captcha",Caster.toBoolean(c.getLoginCaptcha())); sct.set("delay",Caster.toDouble(c.getLoginDelay())); sct.set("rememberme",Caster.toBoolean(c.getRememberMe())); } private void doGetCharset() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); sct.set("resourceCharset",config.getResourceCharset().name()); sct.set("templateCharset",config.getTemplateCharset().name()); sct.set("webCharset",((PageContextImpl)pageContext).getWebCharset().name()); sct.set("jreCharset",SystemUtil.getCharset().name()); } /** * @throws PageException * */ private void doGetUpdate() throws PageException { Struct sct=new StructImpl(); pageContext.setVariable(getString("admin",action,"returnVariable"),sct); URL location = config.getUpdateLocation(); if(location==null) location=Constants.DEFAULT_UPDATE_URL; String type=config.getUpdateType(); if(StringUtil.isEmpty(type))type="manual"; sct.set("location",location.toExternalForm()); sct.set("type",type); } /** * @throws PageException * */ private synchronized void store() throws PageException { try { admin.storeAndReload(); } catch (Exception e) { throw Caster.toPageException(e); } } private String getString(String tagName, String actionName, String attributeName) throws ApplicationException { return getString(tagName, actionName, attributeName,true); } private String getString(String tagName, String actionName, String attributeName,boolean trim) throws ApplicationException { String value=getString(attributeName,null); if(value==null) throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]"); return trim?value.trim():value; } private double getDouble(String tagName, String actionName, String attributeName) throws ApplicationException { double value=getDouble(attributeName,Double.NaN); if(!Decision.isValid(value)) throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]"); return value; } private String getString(String attributeName, String defaultValue) { Object value=attributes.get(attributeName,null); if(value==null)return defaultValue; return Caster.toString(value,null); } private DateTime getDateTime(String attributeName, DateTime defaultValue) { Object value=attributes.get(attributeName,null); if(value==null)return defaultValue; return DateCaster.toDateAdvanced(value, null, defaultValue); } private Object getObject(String attributeName, Object defaultValue) { return attributes.get(attributeName,defaultValue); } private boolean getBool(String tagName, String actionName, String attributeName) throws PageException { Object value=attributes.get(attributeName,null); if(value==null) throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]"); return Caster.toBooleanValue(value); } private Boolean getBoolObject(String tagName, String actionName, String attributeName) throws PageException { Object value=attributes.get(attributeName,null); if(value==null) throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]"); if(StringUtil.isEmpty(value)) return null; return Caster.toBoolean(value); } private Object getObject(String tagName, String actionName, String attributeName) throws PageException { Object value=attributes.get(attributeName,null); if(value==null) throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]"); return value; } private boolean getBoolV(String attributeName, boolean defaultValue) { Object value=attributes.get(attributeName,null); if(value==null) return defaultValue; return Caster.toBooleanValue(value,defaultValue); } private Boolean getBool(String attributeName, Boolean defaultValue) { Object value=attributes.get(attributeName,null); if(value==null) return defaultValue; return Caster.toBoolean(value,defaultValue); } private Struct getStruct(String attributeName, Struct defaultValue) { Object value=attributes.get(attributeName,null); if(value==null) return defaultValue; try { return Caster.toStruct(value); } catch (PageException e) { return defaultValue; } } private Struct getStruct(String tagName, String actionName, String attributeName) throws PageException { Object value=attributes.get(attributeName,null); if(value==null) throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]"); return Caster.toStruct(value); } private int getInt(String tagName, String actionName, String attributeName) throws PageException { Object value=attributes.get(attributeName,null); if(value==null) throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]"); return (int)Caster.toDoubleValue(value); } private int getInt(String attributeName, int defaultValue) { Object value=attributes.get(attributeName,null); if(value==null) return defaultValue; return Caster.toIntValue(value,defaultValue); } private long getLong(String attributeName, long defaultValue) { Object value=attributes.get(attributeName,null); if(value==null) return defaultValue; return Caster.toLongValue(value,defaultValue); } private double getDouble(String attributeName, double defaultValue) { Object value=attributes.get(attributeName,null); if(value==null) return defaultValue; return Caster.toDoubleValue(value,true,defaultValue); } private TimeSpan getTimespan(String tagName, String actionName, String attributeName) throws PageException { Object value=attributes.get(attributeName,null); if(value==null) throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]"); if(StringUtil.isEmpty(value))return null; return Caster.toTimespan(value); } private Object emptyIfNull(String str) { if(str==null) return ""; return str; } private void throwNoAccessWhenWeb() throws ApplicationException { if(type==TYPE_WEB)throw new ApplicationException( "you have no access for action [web."+action+"]"); } private void throwNoAccessWhenServer() throws ApplicationException { if(type==TYPE_SERVER) { throw new ApplicationException( "you have no access for action [server."+action+"]"); } } }
package yuku.alkitab.base; import android.app.*; import android.content.*; import android.content.DialogInterface.OnDismissListener; import android.content.SharedPreferences.Editor; import android.content.pm.*; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.*; import android.graphics.drawable.*; import android.net.*; import android.os.*; import android.text.*; import android.text.style.*; import android.text.util.*; import android.util.*; import android.view.*; import android.view.View.OnClickListener; import android.view.animation.*; import android.view.animation.Animation.AnimationListener; import android.widget.*; import android.widget.AdapterView.OnItemClickListener; import android.widget.TextView.BufferType; import java.util.*; import yuku.alkitab.*; import yuku.alkitab.base.EdisiActivity.MEdisi; import yuku.alkitab.base.EdisiActivity.MEdisiInternal; import yuku.alkitab.base.EdisiActivity.MEdisiPreset; import yuku.alkitab.base.EdisiActivity.MEdisiYes; import yuku.alkitab.base.IsiActivity.FakeContextMenu.Item; import yuku.alkitab.base.JenisBukmakDialog.Listener; import yuku.alkitab.base.JenisCatatanDialog.RefreshCallback; import yuku.alkitab.base.Search2Engine.Query; import yuku.alkitab.base.config.*; import yuku.alkitab.base.model.*; import yuku.alkitab.base.storage.Db.Bukmak2; import yuku.alkitab.base.storage.*; import yuku.andoutil.*; public class IsiActivity extends Activity { public static final String TAG = IsiActivity.class.getSimpleName(); private static final String NAMAPREF_kitabTerakhir = "kitabTerakhir"; //$NON-NLS-1$ private static final String NAMAPREF_pasalTerakhir = "pasalTerakhir"; //$NON-NLS-1$ private static final String NAMAPREF_ayatTerakhir = "ayatTerakhir"; //$NON-NLS-1$ private static final String NAMAPREF_terakhirMintaFidbek = "terakhirMintaFidbek"; //$NON-NLS-1$ private static final String NAMAPREF_renungan_nama = "renungan_nama"; //$NON-NLS-1$ public static final int RESULT_pindahCara = RESULT_FIRST_USER + 1; ListView lsIsi; Button bTuju; ImageButton bKiri; ImageButton bKanan; View tempatJudul; TextView lJudul; View bContext; int pasal_1 = 0; SharedPreferences preferences_instan; AyatAdapter ayatAdapter_; Sejarah sejarah; //# penyimpanan state buat search2 Query search2_query = null; IntArrayList search2_hasilCari = null; int search2_posisiTerpilih = -1; CallbackSpan.OnClickListener paralelOnClickListener = new CallbackSpan.OnClickListener() { @Override public void onClick(View widget, Object data) { int ari = loncatKe((String)data); if (ari != 0) { sejarah.tambah(ari); } } }; AtributListener atributListener = new AtributListener(); Listener muatUlangAtributMapListener = new Listener() { @Override public void onOk() { ayatAdapter_.muatAtributMap(); } }; Animation fadeInAnimation; Animation fadeOutAnimation; boolean showingContextButton = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); U.nyalakanTitleBarHanyaKalauTablet(this); S.siapinKitab(); S.bacaPengaturan(this); setContentView(R.layout.activity_isi); S.siapinPengirimFidbek(this); S.pengirimFidbek.cobaKirim(); lsIsi = U.getView(this, R.id.lsIsi); bTuju = U.getView(this, R.id.bTuju); bKiri = U.getView(this, R.id.bKiri); bKanan = U.getView(this, R.id.bKanan); tempatJudul = U.getView(this, R.id.tempatJudul); lJudul = U.getView(this, R.id.lJudul); bContext = U.getView(this, R.id.bContext); terapkanPengaturan(false); lsIsi.setOnItemClickListener(lsIsi_itemClick); lsIsi.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); bTuju.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bTuju_click(); } }); bTuju.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { bTuju_longClick(); return true; } }); lJudul.setOnClickListener(new View.OnClickListener() { // pinjem bTuju @Override public void onClick(View v) { bTuju_click(); } }); lJudul.setOnLongClickListener(new View.OnLongClickListener() { // pinjem bTuju @Override public boolean onLongClick(View v) { bTuju_longClick(); return true; } }); bKiri.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bKiri_click(); } }); bKanan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bKanan_click(); } }); bContext.setOnClickListener(bContext_click); lsIsi.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { int action = event.getAction(); if (action == KeyEvent.ACTION_DOWN) { return tekan(keyCode); } else if (action == KeyEvent.ACTION_MULTIPLE) { return tekan(keyCode); } return false; } }); // adapter ayatAdapter_ = new AyatAdapter(this, paralelOnClickListener, atributListener); lsIsi.setAdapter(ayatAdapter_); // muat preferences preferences_instan = S.getPreferences(this); int kitabTerakhir = preferences_instan.getInt(NAMAPREF_kitabTerakhir, 0); int pasalTerakhir = preferences_instan.getInt(NAMAPREF_pasalTerakhir, 0); int ayatTerakhir = preferences_instan.getInt(NAMAPREF_ayatTerakhir, 0); { String renungan_nama = preferences_instan.getString(NAMAPREF_renungan_nama, null); if (renungan_nama != null) { for (String nama: RenunganActivity.ADA_NAMA) { if (renungan_nama.equals(nama)) { S.penampungan.renungan_nama = renungan_nama; } } } } sejarah = new Sejarah(preferences_instan); Log.d(TAG, "Akan menuju kitab " + kitabTerakhir + " pasal " + kitabTerakhir + " ayat " + ayatTerakhir); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // muat kitab { Kitab k = S.edisiAktif.getKitab(kitabTerakhir); if (k != null) { S.kitabAktif = k; } } // muat pasal dan ayat tampil(pasalTerakhir, ayatTerakhir); //sejarah.tambah(Ari.encode(kitabTerakhir, pasalTerakhir, ayatTerakhir)); if (D.EBUG) { new AlertDialog.Builder(this) .setMessage("D.EBUG nyala!") //$NON-NLS-1$ .show(); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); hideOrShowContextButton(); } void showContextButton() { if (! showingContextButton) { if (fadeInAnimation == null) { fadeInAnimation = AnimationUtils.loadAnimation(this, android.R.anim.fade_in); } bContext.setVisibility(View.VISIBLE); bContext.startAnimation(fadeInAnimation); bContext.setEnabled(true); showingContextButton = true; } } void hideContextButton() { if (showingContextButton) { if (fadeOutAnimation == null) { fadeOutAnimation = AnimationUtils.loadAnimation(this, android.R.anim.fade_out); } fadeOutAnimation.setAnimationListener(fadeOutAnimation_animation); bContext.startAnimation(fadeOutAnimation); bContext.setEnabled(false); showingContextButton = false; } } private AnimationListener fadeOutAnimation_animation = new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { bContext.setVisibility(View.INVISIBLE); } }; protected boolean tekan(int keyCode) { if (Preferences.getBoolean(R.string.pref_tombolVolumeNaikTurun_key, R.bool.pref_tombolVolumeNaikTurun_default)) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) keyCode = KeyEvent.KEYCODE_DPAD_DOWN; if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) keyCode = KeyEvent.KEYCODE_DPAD_UP; } if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { bKiri_click(); return true; } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { bKanan_click(); return true; } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { int posLama = getPosisiBerdasarSkrol(); if (posLama < ayatAdapter_.getCount() - 1) { lsIsi.setSelectionFromTop(posLama+1, lsIsi.getVerticalFadingEdgeLength()); } return true; } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { int posLama = getPosisiBerdasarSkrol(); if (posLama >= 1) { int posBaru = posLama - 1; while (posBaru > 0) { // cek disabled, kalo iya, mundurin lagi if (ayatAdapter_.isEnabled(posBaru)) break; posBaru } lsIsi.setSelectionFromTop(posBaru, lsIsi.getVerticalFadingEdgeLength()); } else { lsIsi.setSelectionFromTop(0, lsIsi.getVerticalFadingEdgeLength()); } return true; } return false; } private synchronized void nyalakanTerusLayarKalauDiminta() { if (Preferences.getBoolean(R.string.pref_nyalakanTerusLayar_key, R.bool.pref_nyalakanTerusLayar_default)) { lsIsi.setKeepScreenOn(true); } } private synchronized void matikanLayarKalauSudahBolehMati() { lsIsi.setKeepScreenOn(false); } int loncatKe(String alamat) { if (alamat.trim().length() == 0) { return 0; } Log.d(TAG, "akan loncat ke " + alamat); //$NON-NLS-1$ Peloncat peloncat = new Peloncat(); boolean sukses = peloncat.parse(alamat); if (! sukses) { Toast.makeText(this, getString(R.string.alamat_tidak_sah_alamat, alamat), Toast.LENGTH_SHORT).show(); return 0; } int kitabPos = peloncat.getKitab(S.edisiAktif.getConsecutiveXkitab()); Kitab terpilih; if (kitabPos != -1) { Kitab k = S.edisiAktif.getKitab(kitabPos); if (k != null) { terpilih = k; } else { // not avail, just fallback terpilih = S.kitabAktif; } } else { terpilih = S.kitabAktif; } // set kitab S.kitabAktif = terpilih; int pasal = peloncat.getPasal(); int ayat = peloncat.getAyat(); int ari_pa; if (pasal == -1 && ayat == -1) { ari_pa = tampil(1, 1); } else { ari_pa = tampil(pasal, ayat); } return Ari.encode(terpilih.pos, ari_pa); } void loncatKeAri(int ari) { if (ari == 0) return; Log.d(TAG, "akan loncat ke ari 0x" + Integer.toHexString(ari)); //$NON-NLS-1$ int kitabPos = Ari.toKitab(ari); Kitab k = S.edisiAktif.getKitab(kitabPos); if (k != null) { S.kitabAktif = k; } else { Log.w(TAG, "mana ada kitabPos " + kitabPos + " dari ari " + ari); //$NON-NLS-1$ //$NON-NLS-2$ return; } tampil(Ari.toPasal(ari), Ari.toAyat(ari)); } private OnItemClickListener lsIsi_itemClick = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { hideOrShowContextButton(); } }; private void hideOrShowContextButton() { SparseBooleanArray checkedPositions = lsIsi.getCheckedItemPositions(); boolean anyChecked = false; for (int i = 0; i < checkedPositions.size(); i++) if (checkedPositions.valueAt(i)) { anyChecked = true; break; } if (anyChecked) { showContextButton(); } else { hideContextButton(); } } private IntArrayList getAyatTerpilih_1() { // hitung ada berapa yang terpilih SparseBooleanArray positions = lsIsi.getCheckedItemPositions(); if (positions == null) { return new IntArrayList(0); } IntArrayList res = new IntArrayList(positions.size()); for (int i = 0, len = positions.size(); i < len; i++) { if (positions.valueAt(i)) { int position = positions.keyAt(i); int ayat_1 = ayatAdapter_.getAyatDariPosition(position); if (ayat_1 >= 1) res.add(ayat_1); } } return res; } private CharSequence alamatDariAyatTerpilih(IntArrayList ayatTerpilih) { if (ayatTerpilih.size() == 0) { // harusnya mustahil. Maka ga usa ngapa2in deh. return S.alamat(S.kitabAktif, this.pasal_1); } else if (ayatTerpilih.size() == 1) { return S.alamat(S.kitabAktif, this.pasal_1, ayatTerpilih.get(0)); } else { return S.alamat(S.kitabAktif, this.pasal_1, ayatTerpilih); } } static class FakeContextMenu { static class Item { String label; Item(String label) { this.label = label; } } Item menuSalinAyat; Item menuTambahBukmak; Item menuTambahCatatan; Item menuTambahStabilo; Item menuBagikan; Item[] items; String[] getLabels() { String[] res = new String[items.length]; for (int i = 0; i < items.length; i++) { res[i] = items[i].label; } return res; } } FakeContextMenu getFakeContextMenu() { FakeContextMenu res = new FakeContextMenu(); res.menuSalinAyat = new Item(getString(R.string.salin_ayat)); res.menuTambahBukmak = new Item(getString(R.string.tambah_pembatas_buku)); res.menuTambahCatatan = new Item(getString(R.string.tulis_catatan)); res.menuTambahStabilo = new Item(getString(R.string.highlight_stabilo)); res.menuBagikan = new Item(getString(R.string.bagikan)); res.items = new Item[] { res.menuSalinAyat, res.menuTambahBukmak, res.menuTambahCatatan, res.menuTambahStabilo, res.menuBagikan, }; return res; }; public void showFakeContextMenu() { IntArrayList terpilih = getAyatTerpilih_1(); if (terpilih.size() == 0) return; // pembuatan menu manual final FakeContextMenu menu = getFakeContextMenu(); // sedikit beda perlakuan antara satu terpilih dan lebih if (terpilih.size() == 1) { // diamkan saja } else { // Ganti beberapa judul menu menu.menuSalinAyat.label = getResources().getQuantityString(R.plurals.salin_n_ayat, terpilih.size(), terpilih.size()); menu.menuBagikan.label = getResources().getQuantityString(R.plurals.bagikan_n_ayat, terpilih.size(), terpilih.size()); menu.menuTambahStabilo.label = getResources().getQuantityString(R.plurals.stabilo_n_ayat, terpilih.size(), terpilih.size()); // menu.findItem(R.id.menuTambahBukmak).setTitle(getString(R.string.tambah_pembatas_buku_di_ayat, ayat_1)); // menu.findItem(R.id.menuTambahCatatan).setTitle(getString(R.string.tulis_catatan_di_ayat, ayat_1)); } new AlertDialog.Builder(this) .setTitle(alamatDariAyatTerpilih(terpilih)) .setItems(menu.getLabels(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which >= 0 && which < menu.items.length) { onFakeContextMenuSelected(menu, menu.items[which]); } } }) .show(); } public void onFakeContextMenuSelected(FakeContextMenu menu, Item item) { IntArrayList terpilih = getAyatTerpilih_1(); CharSequence alamat = alamatDariAyatTerpilih(terpilih); // ayat utama (0 kalo ga ada), yaitu kalau cuma kepilih satu. int ayatUtama_1 = 0; if (terpilih.size() == 1) { // ga ada yang di bawah pencetan jari, tapi cuma 1 ayat yang di terpilih, maka pasang ayat itu aja. ayatUtama_1 = terpilih.get(0); } if (item == menu.menuSalinAyat) { // salin, bisa multiple StringBuilder salinan = new StringBuilder(); salinan.append(alamat).append(" "); // append tiap ayat terpilih for (int i = 0; i < terpilih.size(); i++) { int ayat_1 = terpilih.get(i); if (i != 0) salinan.append('\n'); salinan.append(U.buangKodeKusus(ayatAdapter_.getAyat(ayat_1))); } U.salin(salinan); Toast.makeText(this, getString(R.string.alamat_sudah_disalin, alamat), Toast.LENGTH_SHORT).show(); } else if (item == menu.menuTambahBukmak) { if (ayatUtama_1 != 0) { final int ari = Ari.encode(S.kitabAktif.pos, this.pasal_1, ayatUtama_1); JenisBukmakDialog dialog = new JenisBukmakDialog(this, S.alamat(S.kitabAktif, this.pasal_1, ayatUtama_1), ari); dialog.setListener(muatUlangAtributMapListener); dialog.bukaDialog(); } } else if (item == menu.menuTambahCatatan) { if (ayatUtama_1 != 0) { tampilkanCatatan(S.kitabAktif, this.pasal_1, ayatUtama_1); } } else if (item == menu.menuTambahStabilo) { final int ariKp = Ari.encode(S.kitabAktif.pos, this.pasal_1, 0); int warnaRgb = S.getDb().getWarnaRgbStabilo(ariKp, terpilih); new JenisStabiloDialog(this, ariKp, terpilih, new JenisStabiloDialog.JenisStabiloCallback() { @Override public void onOk(int warnaRgb) { uncheckAll(); ayatAdapter_.muatAtributMap(); } }, warnaRgb, alamat).bukaDialog(); } else if (item == menu.menuBagikan) { String urlAyat; if (terpilih.size() == 1) { urlAyat = S.bikinUrlAyat(S.kitabAktif, this.pasal_1, terpilih.get(0)); } else { urlAyat = S.bikinUrlAyat(S.kitabAktif, this.pasal_1, 0); // sepasal aja! } StringBuilder sb = new StringBuilder(); // TODO cek fesbuk dan kalo fesbuk, maka taro url di depan, sebaliknya di belakang aja. if (urlAyat != null) sb.append(urlAyat).append(" "); sb.append(alamat).append(" "); // append tiap ayat terpilih for (int i = 0; i < terpilih.size(); i++) { int ayat_1 = terpilih.get(i); if (i != 0) sb.append('\n'); sb.append(U.buangKodeKusus(ayatAdapter_.getAyat(ayat_1))); } Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); //$NON-NLS-1$ i.putExtra(Intent.EXTRA_SUBJECT, alamat); i.putExtra(Intent.EXTRA_TEXT, sb.toString()); startActivity(Intent.createChooser(i, getString(R.string.bagikan_alamat, alamat))); } } private void terapkanPengaturan(boolean bahasaJuga) { // penerapan langsung warnaLatar { lsIsi.setBackgroundColor(S.penerapan.warnaLatar); lsIsi.setCacheColorHint(S.penerapan.warnaLatar); Window window = getWindow(); if (window != null) { ColorDrawable bg = new ColorDrawable(S.penerapan.warnaLatar); window.setBackgroundDrawable(bg); } } // penerapan langsung sembunyi navigasi { View panelNavigasi = findViewById(R.id.panelNavigasi); if (Preferences.getBoolean(R.string.pref_tanpaNavigasi_key, R.bool.pref_tanpaNavigasi_default)) { panelNavigasi.setVisibility(View.GONE); tempatJudul.setVisibility(View.VISIBLE); } else { panelNavigasi.setVisibility(View.VISIBLE); tempatJudul.setVisibility(View.GONE); } } if (bahasaJuga) { S.terapkanPengaturanBahasa(null, 0); } // wajib lsIsi.invalidateViews(); } @Override protected void onStop() { super.onStop(); Editor editor = preferences_instan.edit(); editor.putInt(NAMAPREF_kitabTerakhir, S.kitabAktif.pos); editor.putInt(NAMAPREF_pasalTerakhir, pasal_1); editor.putInt(NAMAPREF_ayatTerakhir, getAyatBerdasarSkrol()); editor.putString(NAMAPREF_renungan_nama, S.penampungan.renungan_nama); sejarah.simpan(editor); editor.commit(); matikanLayarKalauSudahBolehMati(); } @Override protected void onStart() { super.onStart(); //# nyala terus layar nyalakanTerusLayarKalauDiminta(); } /** * @return ayat mulai dari 1 */ int getAyatBerdasarSkrol() { return ayatAdapter_.getAyatDariPosition(getPosisiBerdasarSkrol()); } int getPosisiBerdasarSkrol() { int pos = lsIsi.getFirstVisiblePosition(); // cek apakah paling atas uda keskrol View child = lsIsi.getChildAt(0); if (child != null) { int top = child.getTop(); if (top == 0) { return pos; } int bottom = child.getBottom(); if (bottom > lsIsi.getVerticalFadingEdgeLength()) { return pos; } else { return pos+1; } } return pos; } void bTuju_click() { if (Preferences.getBoolean(R.string.pref_tombolAlamatLoncat_key, R.bool.pref_tombolAlamatLoncat_default)) { bukaDialogLoncat(); } else { bukaDialogTuju(); } } void bTuju_longClick() { if (sejarah.getN() > 0) { new AlertDialog.Builder(this) .setAdapter(sejarahAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int ari = sejarah.getAri(which); loncatKeAri(ari); sejarah.tambah(ari); } }) .setNegativeButton(R.string.cancel, null) .show(); } else { Toast.makeText(this, R.string.belum_ada_sejarah, Toast.LENGTH_SHORT).show(); } } private ListAdapter sejarahAdapter = new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { TextView res = (TextView) convertView; if (res == null) { res = (TextView) LayoutInflater.from(IsiActivity.this).inflate(android.R.layout.select_dialog_item, null); } int ari = sejarah.getAri(position); res.setText(S.alamat(S.edisiAktif, ari)); return res; } @Override public long getItemId(int position) { return position; } @Override public Integer getItem(int position) { return sejarah.getAri(position); } @Override public int getCount() { return sejarah.getN(); } }; void bukaDialogTuju() { Intent intent = new Intent(this, MenujuActivity.class); intent.putExtra(MenujuActivity.EXTRA_pasal, pasal_1); int ayat = getAyatBerdasarSkrol(); intent.putExtra(MenujuActivity.EXTRA_ayat, ayat); startActivityForResult(intent, R.id.menuTuju); } void bukaDialogLoncat() { final View loncat = LayoutInflater.from(this).inflate(R.layout.dialog_loncat, null); final TextView lContohLoncat = (TextView) loncat.findViewById(R.id.lContohLoncat); final EditText tAlamatLoncat = (EditText) loncat.findViewById(R.id.tAlamatLoncat); final ImageButton bKeTuju = (ImageButton) loncat.findViewById(R.id.bKeTuju); { String alamatContoh = S.alamat(S.kitabAktif, IsiActivity.this.pasal_1, getAyatBerdasarSkrol()); String text = getString(R.string.loncat_ke_alamat_titikdua); int pos = text.indexOf("%s"); if (pos >= 0) { SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(text.substring(0, pos)); sb.append(alamatContoh); sb.append(text.substring(pos + 2)); sb.setSpan(new StyleSpan(Typeface.BOLD), pos, pos + alamatContoh.length(), 0); lContohLoncat.setText(sb, BufferType.SPANNABLE); } } final DialogInterface.OnClickListener loncat_click = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int ari = loncatKe(tAlamatLoncat.getText().toString()); if (ari != 0) { sejarah.tambah(ari); } } }; final AlertDialog dialog = new AlertDialog.Builder(IsiActivity.this) .setView(loncat) .setPositiveButton(R.string.loncat, loncat_click) .create(); tAlamatLoncat.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { loncat_click.onClick(dialog, 0); dialog.dismiss(); return true; } }); bKeTuju.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); bukaDialogTuju(); } }); dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface _) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED); } }); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } public void bukaDialogDonasi() { new AlertDialog.Builder(this) .setTitle(R.string.donasi_judul) .setMessage(R.string.donasi_keterangan) .setPositiveButton(R.string.donasi_tombol_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String alamat_donasi = getString(R.string.alamat_donasi); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(alamat_donasi)); startActivity(intent); } }) .setNegativeButton(R.string.donasi_tombol_gamau, null) .show(); } public void bikinMenu(Menu menu) { menu.clear(); getMenuInflater().inflate(R.menu.activity_isi, menu); BuildConfig c = BuildConfig.get(this); if (c.menuGebug) { SubMenu menuGebug = menu.addSubMenu(R.string.gebug); menuGebug.setHeaderTitle("Untuk percobaan dan cari kutu. Tidak penting."); //$NON-NLS-1$ menuGebug.add(0, 0x985801, 0, "gebug 1: dump p+p"); //$NON-NLS-1$ menuGebug.add(0, 0x985806, 0, "gebug 6: tehel bewarna"); //$NON-NLS-1$ menuGebug.add(0, 0x985807, 0, "gebug 7: dump warna"); //$NON-NLS-1$ } //# build config menu.findItem(R.id.menuRenungan).setVisible(c.menuRenungan); menu.findItem(R.id.menuEdisi).setVisible(c.menuEdisi); menu.findItem(R.id.menuBantuan).setVisible(c.menuBantuan); menu.findItem(R.id.menuDonasi).setVisible(c.menuDonasi); } @Override public boolean onCreateOptionsMenu(Menu menu) { bikinMenu(menu); return true; } @Override public boolean onMenuOpened(int featureId, Menu menu) { if (menu != null) { bikinMenu(menu); MenuItem menuTuju = menu.findItem(R.id.menuTuju); if (menuTuju != null) { if (Preferences.getBoolean(R.string.pref_tombolAlamatLoncat_key, R.bool.pref_tombolAlamatLoncat_default)) { menuTuju.setIcon(R.drawable.menu_loncat); menuTuju.setTitle(R.string.loncat_v); } else { menuTuju.setIcon(R.drawable.ic_menu_forward); menuTuju.setTitle(R.string.tuju_v); } } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuTuju: bTuju_click(); return true; case R.id.menuBukmak: startActivityForResult(new Intent(this, BukmakActivity.class), R.id.menuBukmak); return true; case R.id.menuSearch2: menuSearch2_click(); return true; case R.id.menuEdisi: pilihEdisi(); return true; case R.id.menuRenungan: startActivityForResult(new Intent(this, RenunganActivity.class), R.id.menuRenungan); return true; case R.id.menuTentang: tampilDialogTentang(); return true; case R.id.menuPengaturan: startActivityForResult(new Intent(this, PengaturanActivity.class), R.id.menuPengaturan); return true; case R.id.menuFidbek: popupMintaFidbek(); return true; case R.id.menuBantuan: startActivity(new Intent(this, BantuanActivity.class)); return true; case R.id.menuDonasi: bukaDialogDonasi(); return true; } return false; } private void tampilDialogTentang() { String verName = "null"; //$NON-NLS-1$ int verCode = -1; try { PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); verName = packageInfo.versionName; verCode = packageInfo.versionCode; } catch (NameNotFoundException e) { Log.e(TAG, "PackageInfo ngaco", e); //$NON-NLS-1$ } TextView isi = new TextView(this); isi.setText(Html.fromHtml(U.preprocessHtml(getString(R.string.teks_about, verName, verCode)))); isi.setTextColor(0xffffffff); isi.setLinkTextColor(0xff8080ff); Linkify.addLinks(isi, Linkify.WEB_URLS); int pad = (int) (getResources().getDisplayMetrics().density * 6.f); isi.setPadding(pad, pad, pad, pad); new AlertDialog.Builder(this) .setTitle(R.string.tentang_title) .setView(isi) .setPositiveButton(R.string.ok, null) .show(); } private void pilihEdisi() { // populate dengan // 1. internal // 2. preset yang UDAH DIDONLOT dan AKTIF // 3. yes yang AKTIF BuildConfig c = BuildConfig.get(this); final List<String> pilihan = new ArrayList<String>(); // harus bareng2 sama bawah final List<MEdisi> data = new ArrayList<MEdisi>(); // harus bareng2 sama atas pilihan.add(c.internalJudul); // 1. internal data.add(new MEdisiInternal()); for (MEdisiPreset preset: c.xpreset) { // 2. preset if (AddonManager.cekAdaEdisi(preset.namafile_preset) && preset.getAktif()) { pilihan.add(preset.judul); data.add(preset); } } List<MEdisiYes> xyes = S.getDb().listSemuaEdisi(); for (MEdisiYes yes: xyes) { if (yes.getAktif()) { pilihan.add(yes.judul); data.add(yes); } } int terpilih = -1; if (S.edisiId == null) { terpilih = 0; } else { for (int i = 0; i < data.size(); i++) { MEdisi me = data.get(i); if (me.getEdisiId().equals(S.edisiId)) { terpilih = i; break; } } } new AlertDialog.Builder(this) .setTitle(R.string.pilih_edisi) .setSingleChoiceItems(pilihan.toArray(new String[pilihan.size()]), terpilih, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final MEdisi me = data.get(which); Edisi edisi = me.getEdisi(getApplicationContext()); if (edisi != null) { S.edisiAktif = edisi; S.edisiId = me.getEdisiId(); S.siapinKitab(); Kitab k = S.edisiAktif.getKitab(S.kitabAktif.pos); if (k != null) { // assign kitab aktif dengan yang baru, ga usa perhatiin pos S.kitabAktif = k; } else { S.kitabAktif = S.edisiAktif.getKitabPertama(); // apa boleh buat, ga ketemu... } dialog.dismiss(); tampil(pasal_1, getAyatBerdasarSkrol()); } else { new AlertDialog.Builder(IsiActivity.this) .setMessage(getString(R.string.ada_kegagalan_membuka_edisiid, me.getEdisiId())) .setPositiveButton(R.string.ok, null) .show(); } } }) .setPositiveButton(R.string.versi_lainnya, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(getApplicationContext(), EdisiActivity.class); startActivityForResult(intent, R.id.menuEdisi); } }) .setNegativeButton(R.string.cancel, null) .show(); } private void menuSearch2_click() { Intent intent = new Intent(this, Search2Activity.class); intent.putExtra(Search2Activity.EXTRA_query, search2_query); intent.putExtra(Search2Activity.EXTRA_hasilCari, search2_hasilCari); intent.putExtra(Search2Activity.EXTRA_posisiTerpilih, search2_posisiTerpilih); startActivityForResult(intent, R.id.menuSearch2); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult reqCode=0x" + Integer.toHexString(requestCode) + " resCode=" + resultCode + " data=" + data); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (requestCode == R.id.menuTuju) { if (resultCode == RESULT_OK) { int pasal = data.getIntExtra(MenujuActivity.EXTRA_pasal, 0); int ayat = data.getIntExtra(MenujuActivity.EXTRA_ayat, 0); int kitabPos = data.getIntExtra(MenujuActivity.EXTRA_kitab, AdapterView.INVALID_POSITION); if (kitabPos != AdapterView.INVALID_POSITION) { // ganti kitab Kitab k = S.edisiAktif.getKitab(kitabPos); if (k != null) { S.kitabAktif = k; } } int ari_pa = tampil(pasal, ayat); sejarah.tambah(Ari.encode(kitabPos, ari_pa)); } else if (resultCode == RESULT_pindahCara) { bukaDialogLoncat(); } } else if (requestCode == R.id.menuBukmak) { ayatAdapter_.muatAtributMap(); if (resultCode == RESULT_OK) { int ari = data.getIntExtra(BukmakActivity.EXTRA_ariTerpilih, 0); if (ari != 0) { // 0 berarti ga ada apa2, karena ga ada pasal 0 ayat 0 loncatKeAri(ari); sejarah.tambah(ari); } } } else if (requestCode == R.id.menuSearch2) { if (resultCode == RESULT_OK) { int ari = data.getIntExtra(Search2Activity.EXTRA_ariTerpilih, 0); if (ari != 0) { // 0 berarti ga ada apa2, karena ga ada pasal 0 ayat 0 loncatKeAri(ari); sejarah.tambah(ari); } search2_query = data.getParcelableExtra(Search2Activity.EXTRA_query); search2_hasilCari = data.getParcelableExtra(Search2Activity.EXTRA_hasilCari); search2_posisiTerpilih = data.getIntExtra(Search2Activity.EXTRA_posisiTerpilih, -1); } } else if (requestCode == R.id.menuRenungan) { if (data != null) { String alamat = data.getStringExtra(RenunganActivity.EXTRA_alamat); if (alamat != null) { int ari = loncatKe(alamat); if (ari != 0) { sejarah.tambah(ari); } } } } else if (requestCode == R.id.menuPengaturan) { // HARUS rilod pengaturan. S.bacaPengaturan(this); terapkanPengaturan(true); } } /** * @param pasal_1 basis-1 * @param ayat_1 basis-1 * @return Ari yang hanya terdiri dari pasal dan ayat. Kitab selalu 00 */ int tampil(int pasal_1, int ayat_1) { if (pasal_1 < 1) pasal_1 = 1; if (pasal_1 > S.kitabAktif.npasal) pasal_1 = S.kitabAktif.npasal; if (ayat_1 < 1) ayat_1 = 1; if (ayat_1 > S.kitabAktif.nayat[pasal_1 - 1]) ayat_1 = S.kitabAktif.nayat[pasal_1 - 1]; // muat data GA USAH pake async dong. // diapdet 20100417 biar ga usa async, ga guna. { int[] perikop_xari; Blok[] perikop_xblok; int nblok; String[] xayat = S.muatTeks(S.edisiAktif, S.kitabAktif, pasal_1); //# max dibikin pol 30 aja (1 pasal max 30 blok, cukup mustahil) int max = 30; perikop_xari = new int[max]; perikop_xblok = new Blok[max]; nblok = S.edisiAktif.pembaca.muatPerikop(S.edisiAktif, S.kitabAktif.pos, pasal_1, perikop_xari, perikop_xblok, max); //# isi adapter dengan data baru, pastikan semua checked state direset dulu uncheckAll(); ayatAdapter_.setData(S.kitabAktif, pasal_1, xayat, perikop_xari, perikop_xblok, nblok); ayatAdapter_.muatAtributMap(); // kasi tau activity this.pasal_1 = pasal_1; final int position = ayatAdapter_.getPositionAwalPerikopDariAyat(ayat_1); if (position == -1) { Log.w(TAG, "ga bisa ketemu ayat " + ayat_1 + ", ANEH!"); //$NON-NLS-1$ //$NON-NLS-2$ } else { lsIsi.setSelectionFromTop(position, lsIsi.getVerticalFadingEdgeLength()); } } String judul = S.alamat(S.kitabAktif, pasal_1); lJudul.setText(judul); bTuju.setText(judul); return Ari.encode(0, pasal_1, ayat_1); } private void uncheckAll() { SparseBooleanArray checkedPositions = lsIsi.getCheckedItemPositions(); if (checkedPositions != null && checkedPositions.size() > 0) { for (int i = checkedPositions.size() - 1; i >= 0; i if (checkedPositions.valueAt(i)) { lsIsi.setItemChecked(checkedPositions.keyAt(i), false); } } } hideContextButton(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (tekan(keyCode)) return true; return super.onKeyDown(keyCode, event); } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { if (tekan(keyCode)) return true; return super.onKeyMultiple(keyCode, repeatCount, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (Preferences.getBoolean(R.string.pref_tombolVolumeNaikTurun_key, R.bool.pref_tombolVolumeNaikTurun_default)) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) return true; if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) return true; } return super.onKeyUp(keyCode, event); } void bKiri_click() { Kitab kitabKini = S.kitabAktif; if (pasal_1 == 1) { // uda di awal pasal, masuk ke kitab sebelum int cobaKitabPos = kitabKini.pos - 1; while (cobaKitabPos >= 0) { Kitab kitabBaru = S.edisiAktif.getKitab(cobaKitabPos); if (kitabBaru != null) { S.kitabAktif = kitabBaru; int pasalBaru_1 = kitabBaru.npasal; // ke pasal terakhir tampil(pasalBaru_1, 1); break; } cobaKitabPos } // whileelse: sekarang sudah Kejadian 1. Ga usa ngapa2in } else { int pasalBaru = pasal_1 - 1; tampil(pasalBaru, 1); } } void bKanan_click() { Kitab kitabKini = S.kitabAktif; if (pasal_1 >= kitabKini.npasal) { int maxKitabPos = S.edisiAktif.getMaxKitabPos(); int cobaKitabPos = kitabKini.pos + 1; while (cobaKitabPos < maxKitabPos) { Kitab kitabBaru = S.edisiAktif.getKitab(cobaKitabPos); if (kitabBaru != null) { S.kitabAktif = kitabBaru; tampil(1, 1); break; } cobaKitabPos++; } // whileelse: uda di Wahyu (atau kitab terakhir) pasal terakhir. Ga usa ngapa2in } else { int pasalBaru = pasal_1 + 1; tampil(pasalBaru, 1); } } private OnClickListener bContext_click = new OnClickListener() { @Override public void onClick(View v) { showFakeContextMenu(); } }; private void popupMintaFidbek() { final View feedback = getLayoutInflater().inflate(R.layout.dialog_feedback, null); TextView lVersi = (TextView) feedback.findViewById(R.id.lVersi); try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0); lVersi.setText(getString(R.string.namaprog_versi_build, info.versionName, info.versionCode)); } catch (NameNotFoundException e) { Log.w(TAG, e); } new AlertDialog.Builder(IsiActivity.this).setView(feedback) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText tFeedback = (EditText) feedback.findViewById(R.id.tFeedback); String isi = tFeedback.getText().toString(); if (isi.length() > 0) { S.pengirimFidbek.tambah(isi); } S.pengirimFidbek.cobaKirim(); Editor editor = preferences_instan.edit(); editor.putLong(NAMAPREF_terakhirMintaFidbek, System.currentTimeMillis()); editor.commit(); } }).show(); } @Override public boolean onSearchRequested() { menuSearch2_click(); return true; } void tampilkanCatatan(Kitab kitab_, int pasal_1, int ayat_1) { JenisCatatanDialog dialog = new JenisCatatanDialog(IsiActivity.this, kitab_, pasal_1, ayat_1, new RefreshCallback() { @Override public void udahan() { ayatAdapter_.muatAtributMap(); } }); dialog.bukaDialog(); } public class AtributListener { public void onClick(Kitab kitab_, int pasal_1, int ayat_1, int jenis) { if (jenis == Bukmak2.jenis_bukmak) { final int ari = Ari.encode(kitab_.pos, pasal_1, ayat_1); String alamat = S.alamat(S.edisiAktif, ari); JenisBukmakDialog dialog = new JenisBukmakDialog(IsiActivity.this, alamat, ari); dialog.setListener(muatUlangAtributMapListener); dialog.bukaDialog(); } else if (jenis == Bukmak2.jenis_catatan) { tampilkanCatatan(kitab_, pasal_1, ayat_1); } } } }
package com.krishagni.catissueplus.core.administrative.services.impl; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import com.krishagni.catissueplus.core.administrative.domain.PermissibleValue; import com.krishagni.catissueplus.core.administrative.domain.StorageContainer; import com.krishagni.catissueplus.core.administrative.services.ContainerReport; import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol; import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory; import com.krishagni.catissueplus.core.common.util.AuthUtil; import com.krishagni.catissueplus.core.common.util.CsvWriter; import com.krishagni.catissueplus.core.common.util.MessageUtil; import com.krishagni.catissueplus.core.common.util.Utility; public abstract class AbstractContainerReport implements ContainerReport { protected DaoFactory daoFactory; public void setDaoFactory(DaoFactory daoFactory) { this.daoFactory = daoFactory; } protected void exportContainerSummary(StorageContainer container, CsvWriter writer) { writer.writeNext(new String[] { message(CONTAINER_DETAILS) }); writer.writeNext(new String[] { message(CONTAINER_NAME), container.getName() }); writer.writeNext(new String[] { message(CONTAINER_HIERARCHY), container.getStringifiedAncestors() }); writer.writeNext(new String[] { message(CONTAINER_RESTRICTIONS) }); List<String> cps = new ArrayList<>(); cps.add(message(CONTAINER_PROTOCOL)); if (container.getCompAllowedCps().isEmpty()) { cps.add(message(ALL)); } else { for (CollectionProtocol cp : container.getCompAllowedCps()) { cps.add(cp.getTitle()); } } writer.writeNext(cps.toArray(new String[0])); List<String> types = new ArrayList<>(); types.add(message(CONTAINER_SPECIMEN_TYPES)); if (container.getCompAllowedSpecimenClasses().isEmpty() && container.getCompAllowedSpecimenTypes().isEmpty()) { types.add(message(ALL)); } else { for (PermissibleValue specimenClass : container.getCompAllowedSpecimenClasses()) { types.add(specimenClass.getValue()); } for (PermissibleValue type : container.getCompAllowedSpecimenTypes()) { types.add(type.getValue()); } } writer.writeNext(types.toArray(new String[0])); writer.writeNext(new String[] { message(EXPORTED_BY), AuthUtil.getCurrentUser().formattedName() }); writer.writeNext(new String[] { message(EXPORTED_ON), Utility.getDateTimeString(Calendar.getInstance().getTime()) }); writer.writeNext(new String[0]); } protected String message(String key, Object... params) { return MessageUtil.getInstance().getMessage(key, params); } // <zip>_<uuid>_<userId>_<name> protected String getZipFileId(StorageContainer container, String uuid) { return getFileId(container, "zip", uuid); } // <csv>_<uuid>_<userId>_<name> protected String getCsvFileId(StorageContainer container, String uuid) { return getFileId(container, "csv", uuid); } private String getFileId(StorageContainer container, String type, String uuid) { return String.join( "_", type, uuid, AuthUtil.getCurrentUser().getId().toString(), container.getName().replaceAll("\\s+| } protected static final String CONTAINER_DETAILS = "storage_container_details"; protected static final String CONTAINER_NAME = "storage_container_name"; protected static final String CONTAINER_HIERARCHY = "storage_container_hierarchy"; protected static final String CONTAINER_RESTRICTIONS = "storage_container_restrictions"; protected static final String CONTAINER_PROTOCOL = "storage_container_restricted_protocols"; protected static final String CONTAINER_SPECIMEN_TYPES = "storage_container_specimen_types"; protected static final String ALL = "common_all"; protected static final String EXPORTED_BY = "common_exported_by"; protected static final String EXPORTED_ON = "common_exported_on"; protected static final String CONTAINER_TYPE = "container_type"; protected static final String STORES_SPMN = "container_stores_specimen"; protected static final String CELL_ROW = "container_position_row"; protected static final String CELL_COL = "container_position_column"; protected static final String CELL_POS = "container_position_position"; protected static final String YES = "common_yes"; protected static final String NO = "common_no"; }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.MBeanServerConnection; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; public class ConfluentPlatform { public static String pluginVersion="1"; private String host="127.0.0.1"; private String port="9990"; private String filePath="metrics.txt"; private static JMXConnector jmxConnector = null; private static MBeanServerConnection connection = null; public static void main(String[] args) { try { ConfluentPlatform cp = new ConfluentPlatform(); if(args.length == 2){ cp.host = args[0]; cp.port = args[1]; } cp.getConnection(cp.host, cp.port); Map<String,Object> metrics = cp.getMetrics(); printMetrics(metrics); } catch(Exception e) { System.out.print("plugin_version:"+pluginVersion+"|heartbeat:true|status:0|msg:Error Occurred"); }finally { try { jmxConnector.close(); } catch (Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); } } } private void getConnection(String host,String port) throws Exception{ String JMX_URL = "service:jmx:rmi:///jndi/rmi://"+host+":"+port+"/jmxrmi"; JMXServiceURL jmxurl = new JMXServiceURL(String.format(JMX_URL, host, port)); Map<String, Object> env = new HashMap<String, Object>(); jmxConnector = JMXConnectorFactory.connect(jmxurl, env); connection = jmxConnector.getMBeanServerConnection(); } private ArrayList<String> getRequiredMBeansList(String filePath) throws Exception{ Object path = this.getClass().getResource(filePath); if(path == null){ throw new FileNotFoundException(filePath); } String filepath = ((URL)path).getFile(); FileInputStream in = new FileInputStream(filepath); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); ArrayList<String> list = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { if (!line.startsWith("#") && !line.isEmpty()) { list.add(line); } } in.close(); reader.close(); return list; } private Map<String,Object> getMetrics() throws Exception { ArrayList<String> requiredMbeans = getRequiredMBeansList(filePath); NumberFormat formatter = new DecimalFormat("#0.0000"); Map<String, Object> metrics = new LinkedHashMap<String, Object>(); for(String mbean:requiredMbeans ) { String[] splitline = mbean.split(" "); int len = splitline.length; String mBeanName = splitline[0]; String attributetype = len == 2 ? null : splitline[1]; String label = len == 2 ? splitline[1] : splitline[2]; ObjectName query = new ObjectName(mBeanName); Set<ObjectInstance> mbeans = connection.queryMBeans(query, null); Iterator<ObjectInstance> iterator = mbeans.iterator(); while (iterator.hasNext()) { ObjectInstance instance = iterator.next(); try { String oname1Str = instance.getObjectName().toString(); ObjectName oname1 = new ObjectName(oname1Str); MBeanInfo info = connection.getMBeanInfo(oname1); MBeanAttributeInfo[] attributes = info.getAttributes(); for (MBeanAttributeInfo attribute : attributes) { if (attributetype == null || attribute.getName().matches(attributetype)) { Object obj = connection.getAttribute(oname1,attribute.getName()); String key = replaceTokens(oname1Str, label); if(attributetype ==null) { key = key + ":" +attribute.getName(); } if (obj instanceof Long) { metrics.put(key, formatter.format(obj)); } else if (obj instanceof Double) { Double d = Double.valueOf(obj.toString()); if(!d.isNaN()) { metrics.put(key, formatter.format(obj)); } } else if (obj instanceof String) { metrics.put(key, (String) obj); } else { metrics.put(key, obj); } } } } catch (NullPointerException e) { //e.printStackTrace(); } } } return metrics; } private static void printMetrics(Map<String,Object> metrics) { int i = 0; int limit = 25; int len = metrics.size(); for (String key : metrics.keySet()) { if (i < (limit-1) || i<(len-2)) { System.out.print(key + ":" + metrics.get(key) ); } else { System.out.print("plugin_version:"+pluginVersion+"|heartbeat:true|status:0|msg:No metrics Available"); System.exit(1); } if(!(i == (limit-1) || (i == len-1))){ System.out.print("|"); } i++; } System.out.print("|plugin_version:"+pluginVersion+"|heartbeat:true"); } private static String replaceTokens(String mBeanName, String text) { HashMap<String, String> replacements = new HashMap<String, String>(); int firstColon = mBeanName.indexOf(':'); String[] props = mBeanName.substring(firstColon + 1).split( "(?!\\B\"[^\"]*),(?![^\"]*\"\\B)"); for (int i = 0; i < props.length; i++) { String[] parts = props[i].split("="); replacements.put(parts[0], parts[1]); } Pattern pattern = Pattern.compile("\\<(.+?)\\>"); Matcher matcher = pattern.matcher(text); StringBuilder builder = new StringBuilder(); int i = 0; while (matcher.find()) { String replacement = replacements.get(matcher.group(1)); builder.append(text.substring(i, matcher.start())); if (replacement == null) builder.append(matcher.group(0)); else builder.append(replacement); i = matcher.end(); } builder.append(text.substring(i, text.length())); return builder.toString().replaceAll("\"", "").replaceAll(" ", "-"); } }
package org.alien4cloud.tosca.editor.services; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.annotation.Resource; import alien4cloud.tosca.normative.ToscaType; import org.alien4cloud.tosca.catalog.ArchiveDelegateType; import org.alien4cloud.tosca.catalog.index.CsarService; import org.alien4cloud.tosca.catalog.index.ICsarDependencyLoader; import org.alien4cloud.tosca.catalog.index.IToscaTypeIndexerService; import org.alien4cloud.tosca.model.Csar; import org.alien4cloud.tosca.model.definitions.AttributeDefinition; import org.alien4cloud.tosca.model.definitions.CapabilityDefinition; import org.alien4cloud.tosca.model.definitions.IValue; import org.alien4cloud.tosca.model.definitions.PropertyDefinition; import org.alien4cloud.tosca.model.definitions.RequirementDefinition; import org.alien4cloud.tosca.model.definitions.ScalarPropertyValue; import org.alien4cloud.tosca.model.templates.NodeTemplate; import org.alien4cloud.tosca.model.templates.SubstitutionTarget; import org.alien4cloud.tosca.model.templates.Topology; import org.alien4cloud.tosca.model.types.CapabilityType; import org.alien4cloud.tosca.model.types.NodeType; import org.elasticsearch.common.collect.Lists; import org.springframework.stereotype.Service; import com.google.common.collect.Maps; import alien4cloud.model.components.IndexedModelUtils; import alien4cloud.topology.TopologyServiceCore; import alien4cloud.tosca.context.ToscaContext; import alien4cloud.tosca.context.ToscaContextual; import lombok.extern.slf4j.Slf4j; /** * Manages topology substitutions */ @Service @Slf4j public class TopologySubstitutionService { @Resource private CsarService csarService; @Resource private IToscaTypeIndexerService indexerService; @Resource private ICsarDependencyLoader csarDependencyLoader; @ToscaContextual public void updateSubstitutionType(final Topology topology, Csar csar) { // FIXME we do not yet support substitution from application topology if (Objects.equals(csar.getDelegateType(), ArchiveDelegateType.APPLICATION)) { return; } if (topology.getSubstitutionMapping() == null || topology.getSubstitutionMapping().getSubstitutionType() == null) { return; } // first we update the csar and the dependencies NodeType nodeType = ToscaContext.getOrFail(NodeType.class, topology.getSubstitutionMapping().getSubstitutionType().getElementId()); csar.getDependencies().add(csarDependencyLoader.buildDependencyBean(nodeType.getArchiveName(), nodeType.getArchiveVersion())); // FIXME manage hash for substitution elements too (should we just generate based on type). // csar.setHash("-1"); csarService.save(csar); // We create the nodeType that will serve as substitute NodeType substituteNodeType = buildSubstituteNodeType(topology, csar, nodeType); // inputs from topology become properties of type substituteNodeType.setProperties(topology.getInputs()); // output attributes become attributes for the type fillSubstituteAttributesFromTypeAtttributes(topology, substituteNodeType); // output properties become attributes for the type fillSubstituteAttributesFromOutputProperties(topology, substituteNodeType); // output capabilities properties also become attributes for the type fillAttributesFromOutputCapabilitiesProperties(topology, substituteNodeType); // capabilities substitution fillCapabilities(topology, substituteNodeType); // requirement substitution fillRequirements(topology, substituteNodeType); // finally we index the created type indexerService.indexInheritableElement(csar.getName(), csar.getVersion(), substituteNodeType, csar.getDependencies()); } private void fillRequirements(Topology topology, NodeType substituteNodeType) { if (topology.getSubstitutionMapping().getRequirements() != null) { for (Map.Entry<String, SubstitutionTarget> e : topology.getSubstitutionMapping().getRequirements().entrySet()) { String key = e.getKey(); String nodeName = e.getValue().getNodeTemplateName(); String requirementName = e.getValue().getTargetId(); NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName); NodeType nodeTemplateType = ToscaContext.getOrFail(NodeType.class, nodeTemplate.getType()); RequirementDefinition requirementDefinition = IndexedModelUtils.getRequirementDefinitionById(nodeTemplateType.getRequirements(), requirementName); requirementDefinition.setId(key); substituteNodeType.getRequirements().add(requirementDefinition); } } } private void fillCapabilities(Topology topology, NodeType substituteNodeType) { if (topology.getSubstitutionMapping().getCapabilities() != null) { for (Map.Entry<String, SubstitutionTarget> e : topology.getSubstitutionMapping().getCapabilities().entrySet()) { String key = e.getKey(); String nodeName = e.getValue().getNodeTemplateName(); String capabilityName = e.getValue().getTargetId(); NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName); NodeType nodeTemplateType = ToscaContext.getOrFail(NodeType.class, nodeTemplate.getType()); CapabilityDefinition capabilityDefinition = IndexedModelUtils.getCapabilityDefinitionById(nodeTemplateType.getCapabilities(), capabilityName); capabilityDefinition.setId(key); substituteNodeType.getCapabilities().add(capabilityDefinition); } } } private void fillAttributesFromOutputCapabilitiesProperties(Topology topology, NodeType substituteNodeType) { Map<String, IValue> attributes = substituteNodeType.getAttributes(); Map<String, Map<String, Set<String>>> outputCapabilityProperties = topology.getOutputCapabilityProperties(); if (outputCapabilityProperties != null) { for (Map.Entry<String, Map<String, Set<String>>> ocpe : outputCapabilityProperties.entrySet()) { String nodeName = ocpe.getKey(); NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName); for (Map.Entry<String, Set<String>> cpe : ocpe.getValue().entrySet()) { String capabilityName = cpe.getKey(); String capabilityTypeName = nodeTemplate.getCapabilities().get(capabilityName).getType(); CapabilityType capabilityType = ToscaContext.getOrFail(CapabilityType.class, capabilityTypeName); for (String propertyName : cpe.getValue()) { PropertyDefinition pd = capabilityType.getProperties().get(propertyName); // FIXME we have an issue here : if several nodes have the same attribute name, or if an attribute and a property have the same name, // there is a conflict if (pd != null && !attributes.containsKey(propertyName)) { attributes.put(propertyName, pd); } } } } } } private void fillSubstituteAttributesFromOutputProperties(Topology topology, NodeType substituteNodeType) { Map<String, IValue> attributes = substituteNodeType.getAttributes(); Map<String, Set<String>> outputProperties = topology.getOutputProperties(); if (outputProperties != null) { for (Map.Entry<String, Set<String>> ope : outputProperties.entrySet()) { String nodeName = ope.getKey(); NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName); NodeType nodeTemplateType = ToscaContext.getOrFail(NodeType.class, nodeTemplate.getType()); for (String propertyName : ope.getValue()) { PropertyDefinition pd = nodeTemplateType.getProperties().get(propertyName); // FIXME we have an issue here : if several nodes have the same attribute name, or if an attribute and a property have the same name, there // is a conflict if (pd != null && !attributes.containsKey(propertyName)) { if (ToscaType.isSimple(pd.getType())) { AttributeDefinition attributeDefinition = new AttributeDefinition(); attributeDefinition.setType(pd.getType()); attributeDefinition.setDescription(pd.getDescription()); // FIXME known issue we don't support complex attributes right now. if (pd.getDefault() != null && pd.getDefault() instanceof ScalarPropertyValue) { attributeDefinition.setDefault(((ScalarPropertyValue) pd.getDefault()).getValue()); } attributes.put(propertyName, attributeDefinition); } // FIXME else: known issue we don't support complex attributes right now. } } } } } private void fillSubstituteAttributesFromTypeAtttributes(Topology topology, NodeType substituteNodeType) { Map<String, IValue> attributes = substituteNodeType.getAttributes(); Map<String, Set<String>> outputAttributes = topology.getOutputAttributes(); if (outputAttributes != null) { for (Map.Entry<String, Set<String>> oae : outputAttributes.entrySet()) { String nodeName = oae.getKey(); NodeTemplate nodeTemplate = TopologyServiceCore.getNodeTemplate(topology, nodeName); NodeType nodeTemplateType = ToscaContext.getOrFail(NodeType.class, nodeTemplate.getType()); for (String attributeName : oae.getValue()) { IValue ivalue = nodeTemplateType.getAttributes().get(attributeName); // FIXME we have an issue here : if several nodes have the same attribute name, or if an attribute and a property have the same name, there // is a conflict if (ivalue != null && !attributes.containsKey(attributeName)) { attributes.put(attributeName, ivalue); } } } } } private NodeType buildSubstituteNodeType(Topology topology, Csar csar, NodeType nodeType) { NodeType substituteNodeType = new NodeType(); substituteNodeType.setArchiveName(csar.getName()); substituteNodeType.setArchiveVersion(csar.getVersion()); substituteNodeType.setElementId(csar.getName()); substituteNodeType.setDerivedFrom(Lists.newArrayList(nodeType.getElementId())); substituteNodeType.setSubstitutionTopologyId(topology.getId()); substituteNodeType.setWorkspace(topology.getWorkspace()); List<CapabilityDefinition> capabilities = Lists.newArrayList(); substituteNodeType.setCapabilities(capabilities); List<RequirementDefinition> requirements = Lists.newArrayList(); substituteNodeType.setRequirements(requirements); substituteNodeType.setAttributes(Maps.newHashMap()); return substituteNodeType; } }
package uk.ac.ebi.quickgo.annotation.controller; import uk.ac.ebi.quickgo.annotation.IdGeneratorUtil; import uk.ac.ebi.quickgo.annotation.common.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.model.OntologyRelatives; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.junit.Test; import org.springframework.test.web.servlet.ResultActions; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.springframework.http.HttpMethod.GET; import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest; import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static uk.ac.ebi.quickgo.annotation.AnnotationParameters.GO_ID_PARAM; import static uk.ac.ebi.quickgo.annotation.AnnotationParameters.GO_USAGE_PARAM; import static uk.ac.ebi.quickgo.annotation.AnnotationParameters.GO_USAGE_RELATIONS_PARAM; import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker.createAnnotationDoc; import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.*; /** * Created 02/11/16 * @author Edd */ public class FilterAnnotationByGORESTIT extends AbstractFilterAnnotationByOntologyRESTIT { private static final String GO_DESCENDANTS_RESOURCE_FORMAT = "/ontology/go/terms/%s/descendants?relations=%s"; private static final String GO_SLIM_RESOURCE_FORMAT = "/ontology/go/slim?ids=%s&relations=%s"; private static final String STATS_RESOURCE = "/annotation/stats"; private static final String STATS_GROUP_NAME = "groupName"; private static final String ANNOTATION_GROUP_NAME = "annotation"; private static final String GENE_PRODUCT_GROUP_NAME = "geneProduct"; private static final String SLIMMING_GROUP_NAME = "slimming"; public FilterAnnotationByGORESTIT() { resourceFormat = GO_DESCENDANTS_RESOURCE_FORMAT; usageParam = GO_USAGE_PARAM.getName(); idParam = GO_ID_PARAM.getName(); usageRelations = GO_USAGE_RELATIONS_PARAM.getName(); } // slimming tests (which is GO specific) @Test public void slimFilterThatSlimsToItself() throws Exception { annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(1), ontologyId(1))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(2), ontologyId(2))); expectRestCallHasSlims( singletonList(ontologyId(1)), emptyList(), singletonList((singletonList(ontologyId(1))))); ResultActions response = mockMvc.perform( get(SEARCH_RESOURCE) .param(usageParam, SLIM_USAGE) .param(idParam, ontologyId(1))); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(pageInfoExists()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(idParam, ontologyId(1))) .andExpect(valuesOccurInField(SLIMMED_ID_FIELD, singletonList(singletonList(ontologyId(1))))); } @Test public void slimFilterHasSlimStatsShown() throws Exception { annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(1), ontologyId(1))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(2), ontologyId(2))); expectRestCallHasSlims( singletonList(ontologyId(1)), emptyList(), singletonList((singletonList(ontologyId(1))))); ResultActions response = mockMvc.perform( get(STATS_RESOURCE) .param(usageParam, SLIM_USAGE) .param(idParam, ontologyId(1))); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(3)) .andExpect(valuesOccurInField(STATS_GROUP_NAME, ANNOTATION_GROUP_NAME, GENE_PRODUCT_GROUP_NAME, SLIMMING_GROUP_NAME)); } @Test public void slimFilterFor1TermWith1Slim() throws Exception { annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(1), ontologyId(1))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(2), ontologyId(2))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(3), ontologyId(3))); expectRestCallHasSlims(singletonList(ontologyId(1)), emptyList(), singletonList(singletonList(ontologyId(3)))); ResultActions response = mockMvc.perform( get(SEARCH_RESOURCE) .param(usageParam, SLIM_USAGE) .param(idParam, ontologyId(3))); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(pageInfoExists()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(idParam, ontologyId(1))) .andExpect(valuesOccurInField(SLIMMED_ID_FIELD, singletonList(singletonList(ontologyId(3))))); } @Test public void slimFilterFor1TermWith2Slims() throws Exception { annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(1), ontologyId(1))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(2), ontologyId(2))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(3), ontologyId(3))); expectRestCallHasSlims( singletonList(ontologyId(1)), singletonList(IS_A), singletonList(asList(ontologyId(2), ontologyId(3)))); ResultActions response = mockMvc.perform( get(SEARCH_RESOURCE) .param(usageParam, SLIM_USAGE) .param(usageRelations, IS_A) .param(idParam, ontologyId(2), ontologyId(3))); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(pageInfoExists()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(idParam, ontologyId(1))) .andExpect(valuesOccurInField(SLIMMED_ID_FIELD, singletonList(asList(ontologyId(2), ontologyId(3))))); } @Test public void slimFilterFor2TermsWith1Slim() throws Exception { annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(1), ontologyId(1))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(2), ontologyId(2))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(3), ontologyId(3))); expectRestCallHasSlims( asList(ontologyId(1), ontologyId(2)), emptyList(), asList( singletonList(ontologyId(3)), singletonList(ontologyId(3)))); ResultActions response = mockMvc.perform( get(SEARCH_RESOURCE) .param(usageParam, SLIM_USAGE) .param(idParam, csv(ontologyId(3)))); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(pageInfoExists()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(idParam, ontologyId(1), ontologyId(2))) .andExpect(valuesOccurInField(SLIMMED_ID_FIELD, asList(singletonList(ontologyId(3)), singletonList(ontologyId(3))))); } @Test public void slimFilterFor2TermsWith2Slims() throws Exception { annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(1), ontologyId(1))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(2), ontologyId(2))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(3), ontologyId(3))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(4), ontologyId(4))); expectRestCallHasSlims( asList(ontologyId(1), ontologyId(2)), emptyList(), asList( asList(ontologyId(3), ontologyId(4)), singletonList(ontologyId(3)))); ResultActions response = mockMvc.perform( get(SEARCH_RESOURCE) .param(usageParam, SLIM_USAGE) .param(idParam, csv(ontologyId(3), ontologyId(4)))); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(pageInfoExists()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(idParam, ontologyId(1), ontologyId(2))) .andExpect(valuesOccurInField(SLIMMED_ID_FIELD, asList( asList(ontologyId(3), ontologyId(4)), singletonList(ontologyId(3))))); } @Test public void wrongResourcePathForSlimCausesErrorMessage() throws Exception { annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(1), ontologyId(1))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(2), ontologyId(2))); ResultActions response = mockMvc.perform( get(SEARCH_RESOURCE) .param(usageParam, SLIM_USAGE) .param(idParam, ontologyId(1))); response.andDo(print()) .andExpect(status().is5xxServerError()) .andExpect(contentTypeToBeJson()) .andExpect(valueStartingWithOccursInErrorMessage(FAILED_REST_FETCH_PREFIX)); } @Test public void fetchTimeoutForSlimFilteringCauses500() throws Exception { annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(1), ontologyId(1))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(2), ontologyId(2))); expectRestCallResponse(GET, buildResource(resourceFormat, ontologyId(1)), withTimeout()); ResultActions response = mockMvc.perform( get(SEARCH_RESOURCE) .param(usageParam, SLIM_USAGE) .param(idParam, ontologyId(1))); response.andDo(print()) .andExpect(status().is5xxServerError()) .andExpect(contentTypeToBeJson()) .andExpect(valueStartingWithOccursInErrorMessage(FAILED_REST_FETCH_PREFIX)); } @Test public void serverErrorForSlimFilteringCauses500() throws Exception { annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(1), ontologyId(1))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(2), ontologyId(2))); expectRestCallResponse(GET, buildResource(resourceFormat, ontologyId(1)), withServerError()); ResultActions response = mockMvc.perform( get(SEARCH_RESOURCE) .param(usageParam, SLIM_USAGE) .param(idParam, ontologyId(1))); response.andDo(print()) .andExpect(status().is5xxServerError()) .andExpect(contentTypeToBeJson()) .andExpect(valueStartingWithOccursInErrorMessage(FAILED_REST_FETCH_PREFIX)); } @Test public void badRequestForSlimFilteringCauses500() throws Exception { annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(1), ontologyId(1))); annotationRepository.save(createAnnotationDocWithId(IdGeneratorUtil.createGPId(2), ontologyId(2))); expectRestCallResponse(GET, buildResource(resourceFormat, ontologyId(1)), withBadRequest()); ResultActions response = mockMvc.perform( get(SEARCH_RESOURCE) .param(usageParam, SLIM_USAGE) .param(idParam, ontologyId(1))); response.andDo(print()) .andExpect(status().is5xxServerError()) .andExpect(contentTypeToBeJson()) .andExpect(valueStartingWithOccursInErrorMessage(FAILED_REST_FETCH_PREFIX)); } @Override protected AnnotationDocument createAnnotationDocWithId(String geneProductId, String goId) { AnnotationDocument doc = createAnnotationDoc(geneProductId); doc.goId = goId; return doc; } @Override protected String ontologyId(int id) { return IdGeneratorUtil.createGoId(id); } private void expectRestCallHasSlims( List<String> termIds, List<String> usageRelations, List<List<String>> slims) { // expectRestCallHasValues( // GO_SLIM_RESOURCE_FORMAT, // termIds, // usageRelations, // slims, // OntologyRelatives.Result::setSlimsTo); String slimTermsCSV = slims.stream() .filter(Objects::nonNull) .flatMap(Collection::stream) .filter(Objects::nonNull) .distinct() .collect(Collectors.joining(COMMA)); String relationsCSV = usageRelations.stream().collect(Collectors.joining(COMMA)); expectRestCallSuccess( GET, buildResource( GO_SLIM_RESOURCE_FORMAT, slimTermsCSV, relationsCSV), constructResponseObject(termIds, slims, OntologyRelatives.Result::setSlimsTo)); } }
package com.github.dynamicextensionsalfresco.quartz; import com.github.dynamicextensionsalfresco.jobs.ScheduledQuartzJob; import org.quartz.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.util.Assert; import java.text.ParseException; import java.util.ArrayList; import java.util.Map; import java.util.Properties; public class QuartzJobRegistrar implements ApplicationContextAware, InitializingBean, DisposableBean { private Logger logger = LoggerFactory.getLogger(QuartzJobRegistrar.class); @Autowired protected Scheduler scheduler; private ArrayList<ScheduledQuartzJob> registeredJobs = new ArrayList<ScheduledQuartzJob>(); private ApplicationContext applicationContext; @Override public void afterPropertiesSet() throws ParseException, SchedulerException { Map<String, Object> scheduledBeans = applicationContext.getBeansWithAnnotation(ScheduledQuartzJob.class); for (Map.Entry entry : scheduledBeans.entrySet()) { Object bean = entry.getValue(); Assert.isInstanceOf(Job.class, bean, "annotated Quartz job classes should implement org.quartz.Job"); ScheduledQuartzJob annotation = bean.getClass().getAnnotation(ScheduledQuartzJob.class); try { String cron = applicationContext.getBean("global-properties", Properties.class).getProperty(annotation.cronProp(), annotation.cron()); CronTrigger trigger = new CronTrigger(annotation.name(), annotation.group(), cron); JobDetail jobDetail = new JobDetail(annotation.name(), annotation.group(), GenericQuartzJob.class); jobDetail.getJobDataMap().put(GenericQuartzJob.Companion.getBEAN_ID(), bean); scheduler.scheduleJob(jobDetail, trigger); registeredJobs.add(annotation); logger.debug("scheduled job " + annotation.name() + " from group " + annotation.group() + " using cron " + annotation.cron()); } catch (Exception e) { logger.error("failed to register job " + annotation.name() + " using cron " + annotation.group(), e); } } } @Override public void destroy() throws SchedulerException { for (ScheduledQuartzJob job : registeredJobs) { try { scheduler.unscheduleJob(job.name(), job.group()); logger.debug("unscheduled job " + job.name() + " from group " + job.group()); } catch (SchedulerException e) { logger.error("failed to cleanup quartz job " + job, e); } } } public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } }
package org.ovirt.engine.core.bll.scheduling; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Singleton; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.ovirt.engine.core.bll.network.host.NetworkDeviceHelper; import org.ovirt.engine.core.bll.network.host.VfScheduler; import org.ovirt.engine.core.bll.scheduling.external.ExternalSchedulerDiscovery; import org.ovirt.engine.core.bll.scheduling.external.ExternalSchedulerFactory; import org.ovirt.engine.core.bll.scheduling.pending.PendingCpuCores; import org.ovirt.engine.core.bll.scheduling.pending.PendingMemory; import org.ovirt.engine.core.bll.scheduling.pending.PendingResourceManager; import org.ovirt.engine.core.bll.scheduling.pending.PendingVM; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.BackendService; import org.ovirt.engine.core.common.businessentities.Entities; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VDSStatus; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.scheduling.ClusterPolicy; import org.ovirt.engine.core.common.scheduling.OptimizationType; import org.ovirt.engine.core.common.scheduling.PerHostMessages; import org.ovirt.engine.core.common.scheduling.PolicyUnit; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AlertDirector; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase; import org.ovirt.engine.core.dao.VdsDao; import org.ovirt.engine.core.dao.VdsGroupDao; import org.ovirt.engine.core.dao.scheduling.ClusterPolicyDao; import org.ovirt.engine.core.dao.scheduling.PolicyUnitDao; import org.ovirt.engine.core.di.Injector; import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil; import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation; import org.ovirt.engine.core.utils.timer.SchedulerUtilQuartzImpl; import org.ovirt.engine.core.vdsbroker.ResourceManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class SchedulingManager implements BackendService { private static final Logger log = LoggerFactory.getLogger(SchedulingManager.class); private static final String HIGH_UTILIZATION = "HighUtilization"; private static final String LOW_UTILIZATION = "LowUtilization"; @Inject private AuditLogDirector auditLogDirector; @Inject private ResourceManager resourceManager; @Inject private MigrationHandler migrationHandler; @Inject private ExternalSchedulerDiscovery exSchedulerDiscovery; @Inject private DbFacade dbFacade; private PendingResourceManager pendingResourceManager; /** * <policy id, policy> map */ private final ConcurrentHashMap<Guid, ClusterPolicy> policyMap; /** * <policy unit id, policy unit> map */ private volatile ConcurrentHashMap<Guid, PolicyUnitImpl> policyUnits; private final Object policyUnitsLock = new Object(); private final ConcurrentHashMap<Guid, Semaphore> clusterLockMap = new ConcurrentHashMap<>(); private final VdsFreeMemoryChecker noWaitingMemoryChecker = new VdsFreeMemoryChecker(new NonWaitingDelayer()); private final Map<Guid, Boolean> clusterId2isHaReservationSafe = new HashMap<>(); private PendingResourceManager getPendingResourceManager() { return pendingResourceManager; } @Inject private SchedulingManager() { pendingResourceManager = new PendingResourceManager(resourceManager); policyMap = new ConcurrentHashMap<>(); policyUnits = new ConcurrentHashMap<>(); } @PostConstruct public void init() { log.info("Initializing Scheduling manager"); loadPolicyUnits(); loadClusterPolicies(); loadExternalScheduler(); enableLoadBalancer(); enableHaReservationCheck(); log.info("Initialized Scheduling manager"); } private void loadExternalScheduler() { if (Config.<Boolean>getValue(ConfigValues.ExternalSchedulerEnabled)) { log.info("Starting external scheduler discovery thread"); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { if (exSchedulerDiscovery.discover()) { reloadPolicyUnits(); } } }); } else { exSchedulerDiscovery.markAllExternalPoliciesAsDisabled(); log.info("External scheduler disabled, discovery skipped"); } } private void reloadPolicyUnits() { synchronized (policyUnitsLock) { policyUnits = new ConcurrentHashMap<>(); loadPolicyUnits(); } } public List<ClusterPolicy> getClusterPolicies() { return new ArrayList<>(policyMap.values()); } public ClusterPolicy getClusterPolicy(Guid clusterPolicyId) { return policyMap.get(clusterPolicyId); } public ClusterPolicy getClusterPolicy(String name) { if (name == null || name.isEmpty()) { return getDefaultClusterPolicy(); } for (ClusterPolicy clusterPolicy : policyMap.values()) { if (clusterPolicy.getName().toLowerCase().equals(name.toLowerCase())) { return clusterPolicy; } } return null; } private ClusterPolicy getDefaultClusterPolicy() { for (ClusterPolicy clusterPolicy : policyMap.values()) { if (clusterPolicy.isDefaultPolicy()) { return clusterPolicy; } } return null; } public Map<Guid, PolicyUnitImpl> getPolicyUnitsMap() { synchronized (policyUnitsLock) { return policyUnits; } } private void loadClusterPolicies() { List<ClusterPolicy> allClusterPolicies = getClusterPolicyDao().getAll(); for (ClusterPolicy clusterPolicy : allClusterPolicies) { policyMap.put(clusterPolicy.getId(), clusterPolicy); } } private void loadPolicyUnits() { List<PolicyUnit> allPolicyUnits = getPolicyUnitDao().getAll(); for (PolicyUnit policyUnit : allPolicyUnits) { if (policyUnit.isInternal()) { policyUnits.put(policyUnit.getId(), Injector.injectMembers(PolicyUnitImpl.getPolicyUnitImpl(policyUnit, getPendingResourceManager()))); } else { policyUnits.put(policyUnit.getId(), new PolicyUnitImpl(policyUnit, getPendingResourceManager())); } } } private static class SchedulingResult { Map<Guid, Pair<EngineMessage, String>> filteredOutReasons; Map<Guid, String> hostNames; PerHostMessages details; public SchedulingResult() { filteredOutReasons = new HashMap<>(); hostNames = new HashMap<>(); details = new PerHostMessages(); } public void addReason(Guid id, String hostName, EngineMessage filterType, String filterName) { filteredOutReasons.put(id, new Pair<>(filterType, filterName)); hostNames.put(id, hostName); } public Collection<String> getReasonMessages() { List<String> lines = new ArrayList<>(); for (Entry<Guid, Pair<EngineMessage, String>> line: filteredOutReasons.entrySet()) { lines.add(line.getValue().getFirst().name()); lines.add(String.format("$%1$s %2$s", "hostName", hostNames.get(line.getKey()))); lines.add(String.format("$%1$s %2$s", "filterName", line.getValue().getSecond())); final List<String> detailMessages = details.getMessages(line.getKey()); if (detailMessages == null || detailMessages.isEmpty()) { lines.add(EngineMessage.SCHEDULING_HOST_FILTERED_REASON.name()); } else { lines.addAll(detailMessages); lines.add(EngineMessage.SCHEDULING_HOST_FILTERED_REASON_WITH_DETAIL.name()); } } return lines; } private PerHostMessages getDetails() { return details; } } public Guid schedule(VDSGroup cluster, VM vm, List<Guid> hostBlackList, List<Guid> hostWhiteList, List<Guid> destHostIdList, List<String> messages, VdsFreeMemoryChecker memoryChecker, String correlationId) { prepareClusterLock(cluster.getId()); try { log.debug("Scheduling started, correlation Id: {}", correlationId); checkAllowOverbooking(cluster); lockCluster(cluster.getId()); List<VDS> vdsList = getVdsDao() .getAllForVdsGroupWithStatus(cluster.getId(), VDSStatus.Up); updateInitialHostList(vdsList, hostBlackList, true); updateInitialHostList(vdsList, hostWhiteList, false); refreshCachedPendingValues(vdsList); ClusterPolicy policy = policyMap.get(cluster.getClusterPolicyId()); Map<String, String> parameters = createClusterPolicyParameters(cluster); vdsList = runFilters(policy.getFilters(), vdsList, vm, parameters, policy.getFilterPositionMap(), messages, memoryChecker, true, correlationId); if (vdsList == null || vdsList.isEmpty()) { return null; } Guid bestHost = selectBestHost(cluster, vm, destHostIdList, vdsList, policy, parameters); if (bestHost != null) { getPendingResourceManager().addPending(new PendingCpuCores(bestHost, vm, vm.getNumOfCpus())); getPendingResourceManager().addPending(new PendingMemory(bestHost, vm, vm.getMinAllocatedMem())); getPendingResourceManager().addPending(new PendingVM(bestHost, vm)); getPendingResourceManager().notifyHostManagers(bestHost); VfScheduler vfScheduler = Injector.get(VfScheduler.class); Map<Guid, String> passthroughVnicToVfMap = vfScheduler.getVnicToVfMap(vm.getId(), bestHost); if (passthroughVnicToVfMap != null && !passthroughVnicToVfMap.isEmpty()) { markVfsAsUsedByVm(bestHost, vm.getId(), passthroughVnicToVfMap); } } return bestHost; } catch (InterruptedException e) { log.error("interrupted", e); return null; } finally { releaseCluster(cluster.getId()); log.debug("Scheduling ended, correlation Id: {}", correlationId); } } private void releaseCluster(Guid cluster) { // ensuring setting the semaphore permits to 1 synchronized (clusterLockMap.get(cluster)) { clusterLockMap.get(cluster).drainPermits(); clusterLockMap.get(cluster).release(); } } private void lockCluster(Guid cluster) throws InterruptedException { clusterLockMap.get(cluster).acquire(); } private void prepareClusterLock(Guid cluster) { clusterLockMap.putIfAbsent(cluster, new Semaphore(1)); } private void markVfsAsUsedByVm(Guid hostId, Guid vmId, Map<Guid, String> passthroughVnicToVfMap) { NetworkDeviceHelper networkDeviceHelper = Injector.get(NetworkDeviceHelper.class); networkDeviceHelper.setVmIdOnVfs(hostId, vmId, new HashSet<>(passthroughVnicToVfMap.values())); } /** * Refresh cached VDS pending fields with the current pending * values from PendingResourceManager. * @param vdsList - list of candidate hosts */ private void refreshCachedPendingValues(List<VDS> vdsList) { for (VDS vds: vdsList) { int pendingMemory = PendingMemory.collectForHost(getPendingResourceManager(), vds.getId()); int pendingCpuCount = PendingCpuCores.collectForHost(getPendingResourceManager(), vds.getId()); vds.setPendingVcpusCount(pendingCpuCount); vds.setPendingVmemSize(pendingMemory); } } /** * @param destHostIdList - used for RunAt preselection, overrides the ordering in vdsList * @param availableVdsList - presorted list of hosts (better hosts first) that are available */ private Guid selectBestHost(VDSGroup cluster, VM vm, List<Guid> destHostIdList, List<VDS> availableVdsList, ClusterPolicy policy, Map<String, String> parameters) { // in case a default destination host was specified and // it passed filters, return the first found List<VDS> runnableHosts = new LinkedList<>(); if (destHostIdList.size() > 0) { // there are dedicated hosts // intersect dedicated hosts list with available list for (VDS vds : availableVdsList) { for (Guid destHostId : destHostIdList) { if (destHostId.equals(vds.getId())) { runnableHosts.add(vds); } } } } if (runnableHosts.isEmpty()) { // no dedicated hosts found runnableHosts = availableVdsList; } switch (runnableHosts.size()){ case 0: // no runnable hosts found, nothing found return null; case 1: // found single available host, in available list return it return runnableHosts.get(0).getId(); default: // select best runnable host with scoring functions (from policy) List<Pair<Guid, Integer>> functions = policy.getFunctions(); if (functions != null && !functions.isEmpty() && shouldWeighClusterHosts(cluster, runnableHosts)) { Guid bestHostByFunctions = runFunctions(functions, runnableHosts, vm, parameters); if (bestHostByFunctions != null) { return bestHostByFunctions; } } } // failed select best runnable host using scoring functions, return the first return runnableHosts.get(0).getId(); } /** * Checks whether scheduler should schedule several requests in parallel: * Conditions: * * config option SchedulerAllowOverBooking should be enabled. * * cluster optimization type flag should allow over-booking. * * more than than X (config.SchedulerOverBookingThreshold) pending for scheduling. * In case all of the above conditions are met, we release all the pending scheduling * requests. */ private void checkAllowOverbooking(VDSGroup cluster) { if (OptimizationType.ALLOW_OVERBOOKING == cluster.getOptimizationType() && Config.<Boolean>getValue(ConfigValues.SchedulerAllowOverBooking) && clusterLockMap.get(cluster.getId()).getQueueLength() >= Config.<Integer>getValue(ConfigValues.SchedulerOverBookingThreshold)) { log.info("Scheduler: cluster '{}' lock is skipped (cluster is allowed to overbook)", cluster.getName()); // release pending threads (requests) and current one (+1) clusterLockMap.get(cluster.getId()) .release(Config.<Integer>getValue(ConfigValues.SchedulerOverBookingThreshold) + 1); } } /** * Checks whether scheduler should weigh hosts/or skip weighing: * * More than one host (it's trivial to weigh a single host). * * optimize for speed is enabled for the cluster, and there are less than configurable requests pending (skip * weighing in a loaded setup). * * @param cluster * @param vdsList * @return */ private boolean shouldWeighClusterHosts(VDSGroup cluster, List<VDS> vdsList) { Integer threshold = Config.<Integer>getValue(ConfigValues.SpeedOptimizationSchedulingThreshold); // threshold is crossed only when cluster is configured for optimized for speed boolean crossedThreshold = OptimizationType.OPTIMIZE_FOR_SPEED == cluster.getOptimizationType() && clusterLockMap.get(cluster.getId()).getQueueLength() > threshold; if (crossedThreshold) { log.info( "Scheduler: skipping whinging hosts in cluster '{}', since there are more than '{}' parallel requests", cluster.getName(), threshold); } return vdsList.size() > 1 && !crossedThreshold; } public boolean canSchedule(VDSGroup cluster, VM vm, List<Guid> vdsBlackList, List<Guid> vdsWhiteList, List<Guid> destVdsIdList, List<String> messages) { List<VDS> vdsList = getVdsDao() .getAllForVdsGroupWithStatus(cluster.getId(), VDSStatus.Up); updateInitialHostList(vdsList, vdsBlackList, true); updateInitialHostList(vdsList, vdsWhiteList, false); refreshCachedPendingValues(vdsList); ClusterPolicy policy = policyMap.get(cluster.getClusterPolicyId()); Map<String, String> parameters = createClusterPolicyParameters(cluster); vdsList = runFilters(policy.getFilters(), vdsList, vm, parameters, policy.getFilterPositionMap(), messages, noWaitingMemoryChecker, false, null); return vdsList != null && !vdsList.isEmpty(); } private Map<String, String> createClusterPolicyParameters(VDSGroup cluster) { Map<String, String> parameters = new HashMap<>(); if (cluster.getClusterPolicyProperties() != null) { parameters.putAll(cluster.getClusterPolicyProperties()); } return parameters; } private void updateInitialHostList(List<VDS> vdsList, List<Guid> list, boolean contains) { if (list != null && !list.isEmpty()) { List<VDS> toRemoveList = new ArrayList<>(); Set<Guid> listSet = new HashSet<>(list); for (VDS vds : vdsList) { if (listSet.contains(vds.getId()) == contains) { toRemoveList.add(vds); } } vdsList.removeAll(toRemoveList); } } private List<VDS> runFilters(ArrayList<Guid> filters, List<VDS> hostList, VM vm, Map<String, String> parameters, Map<Guid, Integer> filterPositionMap, List<String> messages, VdsFreeMemoryChecker memoryChecker, boolean shouldRunExternalFilters, String correlationId) { SchedulingResult result = new SchedulingResult(); ArrayList<PolicyUnitImpl> internalFilters = new ArrayList<>(); ArrayList<PolicyUnitImpl> externalFilters = new ArrayList<>(); filters = (filters != null) ? new ArrayList<>(filters) : new ArrayList<>(); sortFilters(filters, filterPositionMap); for (Guid filter : filters) { PolicyUnitImpl filterPolicyUnit = policyUnits.get(filter); if (filterPolicyUnit.getPolicyUnit().isInternal()) { internalFilters.add(filterPolicyUnit); } else { if (filterPolicyUnit.getPolicyUnit().isEnabled()) { externalFilters.add(filterPolicyUnit); } } } /* Short circuit filters if there are no hosts at all */ if (hostList == null || hostList.isEmpty()) { messages.add(EngineMessage.SCHEDULING_NO_HOSTS.name()); messages.addAll(result.getReasonMessages()); return hostList; } hostList = runInternalFilters(internalFilters, hostList, vm, parameters, filterPositionMap, memoryChecker, correlationId, result); if (shouldRunExternalFilters && Config.<Boolean>getValue(ConfigValues.ExternalSchedulerEnabled) && !externalFilters.isEmpty() && hostList != null && !hostList.isEmpty()) { hostList = runExternalFilters(externalFilters, hostList, vm, parameters, messages, correlationId, result); } if (hostList == null || hostList.isEmpty()) { messages.add(EngineMessage.SCHEDULING_ALL_HOSTS_FILTERED_OUT.name()); messages.addAll(result.getReasonMessages()); } return hostList; } private List<VDS> runInternalFilters(ArrayList<PolicyUnitImpl> filters, List<VDS> hostList, VM vm, Map<String, String> parameters, Map<Guid, Integer> filterPositionMap, VdsFreeMemoryChecker memoryChecker, String correlationId, SchedulingResult result) { if (filters != null) { for (PolicyUnitImpl filterPolicyUnit : filters) { if (hostList == null || hostList.isEmpty()) { break; } filterPolicyUnit.setMemoryChecker(memoryChecker); List<VDS> currentHostList = new ArrayList<>(hostList); hostList = filterPolicyUnit.filter(hostList, vm, parameters, result.getDetails()); logFilterActions(currentHostList, toIdSet(hostList), EngineMessage.VAR__FILTERTYPE__INTERNAL, filterPolicyUnit.getPolicyUnit().getName(), result, correlationId); } } return hostList; } private Set<Guid> toIdSet(List<VDS> hostList) { Set<Guid> set = new HashSet<>(); if (hostList != null) { for (VDS vds : hostList) { set.add(vds.getId()); } } return set; } private void logFilterActions(List<VDS> oldList, Set<Guid> newSet, EngineMessage actionName, String filterName, SchedulingResult result, String correlationId) { for (VDS host: oldList) { if (!newSet.contains(host.getId())) { result.addReason(host.getId(), host.getName(), actionName, filterName); log.info("Candidate host '{}' ('{}') was filtered out by '{}' filter '{}' (correlation id: {})", host.getName(), host.getId(), actionName.name(), filterName, correlationId); } } } private List<VDS> runExternalFilters(ArrayList<PolicyUnitImpl> filters, List<VDS> hostList, VM vm, Map<String, String> parameters, List<String> messages, String correlationId, SchedulingResult result) { List<Guid> filteredIDs = null; if (filters != null) { List<String> filterNames = new ArrayList<>(); for (PolicyUnitImpl filter : filters) { filterNames.add(filter.getPolicyUnit().getName()); } List<Guid> hostIDs = new ArrayList<>(); for (VDS host : hostList) { hostIDs.add(host.getId()); } filteredIDs = ExternalSchedulerFactory.getInstance().runFilters(filterNames, hostIDs, vm.getId(), parameters); if (filteredIDs != null) { logFilterActions(hostList, new HashSet<>(filteredIDs), EngineMessage.VAR__FILTERTYPE__EXTERNAL, Arrays.toString(filterNames.toArray()), result, correlationId); } } return intersectHosts(hostList, filteredIDs); } private List<VDS> intersectHosts(List<VDS> hosts, List<Guid> IDs) { if (IDs == null) { return hosts; } List<VDS> retList = new ArrayList<>(); for (VDS vds : hosts) { if (IDs.contains(vds.getId())) { retList.add(vds); } } return retList; } private void sortFilters(ArrayList<Guid> filters, final Map<Guid, Integer> filterPositionMap) { if (filterPositionMap == null) { return; } Collections.sort(filters, new Comparator<Guid>() { @Override public int compare(Guid filter1, Guid filter2) { Integer position1 = getPosition(filterPositionMap.get(filter1)); Integer position2 = getPosition(filterPositionMap.get(filter2)); return position1 - position2; } private Integer getPosition(Integer position) { if (position == null) { position = 0; } return position; } }); } private Guid runFunctions(List<Pair<Guid, Integer>> functions, List<VDS> hostList, VM vm, Map<String, String> parameters) { List<Pair<PolicyUnitImpl, Integer>> internalScoreFunctions = new ArrayList<>(); List<Pair<PolicyUnitImpl, Integer>> externalScoreFunctions = new ArrayList<>(); for (Pair<Guid, Integer> pair : functions) { PolicyUnitImpl currentPolicy = policyUnits.get(pair.getFirst()); if (currentPolicy.getPolicyUnit().isInternal()) { internalScoreFunctions.add(new Pair<>(currentPolicy, pair.getSecond())); } else { if (currentPolicy.getPolicyUnit().isEnabled()) { externalScoreFunctions.add(new Pair<>(currentPolicy, pair.getSecond())); } } } Map<Guid, Integer> hostCostTable = runInternalFunctions(internalScoreFunctions, hostList, vm, parameters); if (Config.<Boolean>getValue(ConfigValues.ExternalSchedulerEnabled) && !externalScoreFunctions.isEmpty()) { runExternalFunctions(externalScoreFunctions, hostList, vm, parameters, hostCostTable); } Entry<Guid, Integer> bestHostEntry = null; for (Entry<Guid, Integer> entry : hostCostTable.entrySet()) { if (bestHostEntry == null || bestHostEntry.getValue() > entry.getValue()) { bestHostEntry = entry; } } if (bestHostEntry == null) { return null; } return bestHostEntry.getKey(); } private Map<Guid, Integer> runInternalFunctions(List<Pair<PolicyUnitImpl, Integer>> functions, List<VDS> hostList, VM vm, Map<String, String> parameters) { Map<Guid, Integer> hostCostTable = new HashMap<>(); for (Pair<PolicyUnitImpl, Integer> pair : functions) { List<Pair<Guid, Integer>> scoreResult = pair.getFirst().score(hostList, vm, parameters); for (Pair<Guid, Integer> result : scoreResult) { Guid hostId = result.getFirst(); if (hostCostTable.get(hostId) == null) { hostCostTable.put(hostId, 0); } hostCostTable.put(hostId, hostCostTable.get(hostId) + pair.getSecond() * result.getSecond()); } } return hostCostTable; } private void runExternalFunctions(List<Pair<PolicyUnitImpl, Integer>> functions, List<VDS> hostList, VM vm, Map<String, String> parameters, Map<Guid, Integer> hostCostTable) { List<Pair<String, Integer>> scoreNameAndWeight = new ArrayList<>(); for (Pair<PolicyUnitImpl, Integer> pair : functions) { scoreNameAndWeight.add(new Pair<>(pair.getFirst().getPolicyUnit().getName(), pair.getSecond())); } List<Guid> hostIDs = new ArrayList<>(); for (VDS vds : hostList) { hostIDs.add(vds.getId()); } List<Pair<Guid, Integer>> externalScores = ExternalSchedulerFactory.getInstance().runScores(scoreNameAndWeight, hostIDs, vm.getId(), parameters); if (externalScores != null) { sumScoreResults(hostCostTable, externalScores); } } private void sumScoreResults(Map<Guid, Integer> hostCostTable, List<Pair<Guid, Integer>> externalScores) { if (externalScores == null) { // the external scheduler proxy may return null if error happens, in this case the external scores will // remain empty log.warn("External scheduler proxy returned null score"); } else { for (Pair<Guid, Integer> pair : externalScores) { Guid hostId = pair.getFirst(); if (hostCostTable.get(hostId) == null) { hostCostTable.put(hostId, 0); } hostCostTable.put(hostId, hostCostTable.get(hostId) + pair.getSecond()); } } } public Map<String, String> getCustomPropertiesRegexMap(ClusterPolicy clusterPolicy) { Set<Guid> usedPolicyUnits = new HashSet<>(); if (clusterPolicy.getFilters() != null) { usedPolicyUnits.addAll(clusterPolicy.getFilters()); } if (clusterPolicy.getFunctions() != null) { for (Pair<Guid, Integer> pair : clusterPolicy.getFunctions()) { usedPolicyUnits.add(pair.getFirst()); } } if (clusterPolicy.getBalance() != null) { usedPolicyUnits.add(clusterPolicy.getBalance()); } Map<String, String> map = new LinkedHashMap<>(); for (Guid policyUnitId : usedPolicyUnits) { map.putAll(policyUnits.get(policyUnitId).getPolicyUnit().getParameterRegExMap()); } return map; } public void addClusterPolicy(ClusterPolicy clusterPolicy) { getClusterPolicyDao().save(clusterPolicy); policyMap.put(clusterPolicy.getId(), clusterPolicy); } public void editClusterPolicy(ClusterPolicy clusterPolicy) { getClusterPolicyDao().update(clusterPolicy); policyMap.put(clusterPolicy.getId(), clusterPolicy); } public void removeClusterPolicy(Guid clusterPolicyId) { getClusterPolicyDao().remove(clusterPolicyId); policyMap.remove(clusterPolicyId); } private VdsDao getVdsDao() { return dbFacade.getVdsDao(); } private VdsGroupDao getVdsGroupDao() { return dbFacade.getVdsGroupDao(); } private PolicyUnitDao getPolicyUnitDao() { return dbFacade.getPolicyUnitDao(); } private ClusterPolicyDao getClusterPolicyDao() { return dbFacade.getClusterPolicyDao(); } private void enableLoadBalancer() { if (Config.<Boolean>getValue(ConfigValues.EnableVdsLoadBalancing)) { log.info("Start scheduling to enable vds load balancer"); Injector.get(SchedulerUtilQuartzImpl.class).scheduleAFixedDelayJob( this, "performLoadBalancing", new Class[] {}, new Object[] {}, Config.<Integer>getValue(ConfigValues.VdsLoadBalancingIntervalInMinutes), Config.<Integer>getValue(ConfigValues.VdsLoadBalancingIntervalInMinutes), TimeUnit.MINUTES); log.info("Finished scheduling to enable vds load balancer"); } } private void enableHaReservationCheck() { if (Config.<Boolean>getValue(ConfigValues.EnableVdsLoadBalancing)) { log.info("Start HA Reservation check"); Integer interval = Config.<Integer> getValue(ConfigValues.VdsHaReservationIntervalInMinutes); Injector.get(SchedulerUtilQuartzImpl.class).scheduleAFixedDelayJob( this, "performHaResevationCheck", new Class[] {}, new Object[] {}, interval, interval, TimeUnit.MINUTES); log.info("Finished HA Reservation check"); } } @OnTimerMethodAnnotation("performHaResevationCheck") public void performHaResevationCheck() { log.debug("HA Reservation check timer entered."); List<VDSGroup> clusters = getVdsGroupDao().getAll(); if (clusters != null) { HaReservationHandling haReservationHandling = new HaReservationHandling(getPendingResourceManager()); for (VDSGroup cluster : clusters) { if (cluster.supportsHaReservation()) { List<VDS> returnedFailedHosts = new ArrayList<>(); boolean clusterHaStatus = haReservationHandling.checkHaReservationStatusForCluster(cluster, returnedFailedHosts); if (!clusterHaStatus) { // create Alert using returnedFailedHosts AuditLogableBase logable = new AuditLogableBase(); logable.setVdsGroupId(cluster.getId()); logable.addCustomValue("ClusterName", cluster.getName()); String failedHostsStr = StringUtils.join(Entities.objectNames(returnedFailedHosts), ", "); logable.addCustomValue("Hosts", failedHostsStr); AlertDirector.alert(logable, AuditLogType.CLUSTER_ALERT_HA_RESERVATION, auditLogDirector); log.info("Cluster '{}' fail to pass HA reservation check.", cluster.getName()); } boolean clusterHaStatusFromPreviousCycle = clusterId2isHaReservationSafe.containsKey(cluster.getId()) ? clusterId2isHaReservationSafe.get(cluster.getId()) : true; // Update the status map with the new status clusterId2isHaReservationSafe.put(cluster.getId(), clusterHaStatus); // Create Alert if the status was changed from false to true if (!clusterHaStatusFromPreviousCycle && clusterHaStatus) { AuditLogableBase logable = new AuditLogableBase(); logable.setVdsGroupId(cluster.getId()); logable.addCustomValue("ClusterName", cluster.getName()); AlertDirector.alert(logable, AuditLogType.CLUSTER_ALERT_HA_RESERVATION_DOWN, auditLogDirector); } } } } log.debug("HA Reservation check timer finished."); } @OnTimerMethodAnnotation("performLoadBalancing") public void performLoadBalancing() { log.debug("Load Balancer timer entered."); List<VDSGroup> clusters = getVdsGroupDao().getAll(); for (VDSGroup cluster : clusters) { ClusterPolicy policy = policyMap.get(cluster.getClusterPolicyId()); PolicyUnitImpl policyUnit = policyUnits.get(policy.getBalance()); Pair<List<Guid>, Guid> balanceResult = null; if (policyUnit.getPolicyUnit().isEnabled()) { List<VDS> hosts = getVdsDao().getAllForVdsGroupWithoutMigrating(cluster.getId()); if (policyUnit.getPolicyUnit().isInternal()) { balanceResult = internalRunBalance(policyUnit, cluster, hosts); } else if (Config.<Boolean> getValue(ConfigValues.ExternalSchedulerEnabled)) { balanceResult = externalRunBalance(policyUnit, cluster, hosts); } } if (balanceResult != null && balanceResult.getSecond() != null) { migrationHandler.migrateVM(balanceResult.getFirst(), balanceResult.getSecond()); } } } private Pair<List<Guid>, Guid> internalRunBalance(PolicyUnitImpl policyUnit, VDSGroup cluster, List<VDS> hosts) { return policyUnit.balance(cluster, hosts, cluster.getClusterPolicyProperties(), new ArrayList<>()); } private Pair<List<Guid>, Guid> externalRunBalance(PolicyUnitImpl policyUnit, VDSGroup cluster, List<VDS> hosts) { List<Guid> hostIDs = new ArrayList<>(); for (VDS vds : hosts) { hostIDs.add(vds.getId()); } return ExternalSchedulerFactory.getInstance() .runBalance(policyUnit.getPolicyUnit().getName(), hostIDs, cluster.getClusterPolicyProperties()); } /** * returns all cluster policies names containing the specific policy unit. * @param policyUnitId * @return List of cluster policy names that use the referenced policyUnitId * or null if the policy unit is not available. */ public List<String> getClusterPoliciesNamesByPolicyUnitId(Guid policyUnitId) { List<String> list = new ArrayList<>(); final PolicyUnitImpl policyUnitImpl = policyUnits.get(policyUnitId); if (policyUnitImpl == null) { log.warn("Trying to find usages of non-existing policy unit '{}'", policyUnitId); return null; } PolicyUnit policyUnit = policyUnitImpl.getPolicyUnit(); if (policyUnit != null) { for (ClusterPolicy clusterPolicy : policyMap.values()) { switch (policyUnit.getPolicyUnitType()) { case FILTER: Collection<Guid> filters = clusterPolicy.getFilters(); if (filters != null && filters.contains(policyUnitId)) { list.add(clusterPolicy.getName()); } break; case WEIGHT: Collection<Pair<Guid, Integer>> functions = clusterPolicy.getFunctions(); if (functions == null) { break; } for (Pair<Guid, Integer> pair : functions) { if (pair.getFirst().equals(policyUnitId)) { list.add(clusterPolicy.getName()); break; } } break; case LOAD_BALANCING: if (policyUnitId.equals(clusterPolicy.getBalance())) { list.add(clusterPolicy.getName()); } break; default: break; } } } return list; } public void removeExternalPolicyUnit(Guid policyUnitId) { getPolicyUnitDao().remove(policyUnitId); policyUnits.remove(policyUnitId); } /** * update host scheduling statistics: * * CPU load duration interval over/under policy threshold * @param vds */ public void updateHostSchedulingStats(VDS vds) { if (vds.getUsageCpuPercent() != null) { VDSGroup vdsGroup = getVdsGroupDao().get(vds.getVdsGroupId()); if (vds.getUsageCpuPercent() >= NumberUtils.toInt(vdsGroup.getClusterPolicyProperties() .get(HIGH_UTILIZATION), Config.<Integer> getValue(ConfigValues.HighUtilizationForEvenlyDistribute)) || vds.getUsageCpuPercent() <= NumberUtils.toInt(vdsGroup.getClusterPolicyProperties() .get(LOW_UTILIZATION), Config.<Integer> getValue(ConfigValues.LowUtilizationForEvenlyDistribute))) { if (vds.getCpuOverCommitTimestamp() == null) { vds.setCpuOverCommitTimestamp(new Date()); } } else { vds.setCpuOverCommitTimestamp(null); } } } /** * Clear pending records for a VM. * This operation locks the cluster to make sure a possible scheduling operation is not under way. */ public void clearPendingVm(VmStatic vm) { prepareClusterLock(vm.getVdsGroupId()); try { lockCluster(vm.getVdsGroupId()); getPendingResourceManager().clearVm(vm); } catch (InterruptedException e) { log.warn("Interrupted.. pending counters can be out of sync"); } finally { releaseCluster(vm.getVdsGroupId()); } } /** * Clear pending records for a Host. * This operation locks the cluster to make sure a possible scheduling operation is not under way. */ public void clearPendingHost(VDS host) { prepareClusterLock(host.getVdsGroupId()); try { lockCluster(host.getVdsGroupId()); getPendingResourceManager().clearHost(host); } catch (InterruptedException e) { log.warn("Interrupted.. pending counters can be out of sync"); } finally { releaseCluster(host.getVdsGroupId()); } } /** * Get the host scheduled to receive a VM. * This is best effort only. */ public Guid getPendingHostForVm(VM vm) { return PendingVM.getScheduledHost(getPendingResourceManager(), vm); } }
package net.fortuna.ical4j.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.fortuna.ical4j.util.Strings; /** * Defines a list of iCalendar categories. * @author Ben Fortuna */ public class CategoryList implements Serializable { private static final long serialVersionUID = 4387692697196974638L; private List categories; /** * Default constructor. */ public CategoryList() { categories = new ArrayList(); } /** * Parses the specified string representation to create a list of categories. * @param aValue a string representation of a list of categories */ public CategoryList(final String aValue) { categories = new ArrayList(); Pattern pattern = Pattern.compile("([^\\\\](?:\\\\{2})),|([^\\\\]),"); Matcher matcher = pattern.matcher(aValue); String[] categoryValues = null; if (matcher.find()) { categoryValues = matcher.replaceAll("$1$2&quot;").split("&quot;"); } else { categoryValues = aValue.split(","); } for (int i = 0; i < categoryValues.length; i++) { categories.add(Strings.unescape(categoryValues[i])); } } /** * @param categoryStrings */ public CategoryList(String[] categoryValues) { categories = Arrays.asList(categoryValues); } /** * @see java.util.AbstractCollection#toString() */ public final String toString() { StringBuffer b = new StringBuffer(); for (Iterator i = categories.iterator(); i.hasNext();) { b.append(Strings.escape((String) i.next())); if (i.hasNext()) { b.append(','); } } return b.toString(); } /** * Add an address to the list. * @param category the category to add * @return true * @see List#add(java.lang.Object) */ public final boolean add(final String category) { return categories.add(category); } /** * @return boolean indicates if the list is empty * @see List#isEmpty() */ public final boolean isEmpty() { return categories.isEmpty(); } /** * @return an iterator * @see List#iterator() */ public final Iterator iterator() { return categories.iterator(); } /** * Remove a category from the list. * @param category the category to remove * @return true if the list contained the specified category * @see List#remove(java.lang.Object) */ public final boolean remove(final String category) { return categories.remove(category); } /** * @return the number of categories in the list * @see List#size() */ public final int size() { return categories.size(); } }
/* * (e-mail:zhongxunking@163.com) */ /* * : * @author 2017-09-16 15:12 */ package org.antframework.configcenter.test.facade.api; import org.antframework.common.util.facade.EmptyResult; import org.antframework.common.util.facade.Status; import org.antframework.configcenter.facade.api.RefreshService; import org.antframework.configcenter.facade.order.RefreshClientsOrder; import org.antframework.configcenter.test.AbstractTest; import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @Ignore public class RefreshServiceTest extends AbstractTest { @Autowired private RefreshService refreshService; @Test public void testRefreshClients() { String[] appIds = new String[]{null, "customer"}; String[] profileIds = new String[]{null, "dev"}; for (String appId : appIds) { for (String profileId : profileIds) { RefreshClientsOrder order = new RefreshClientsOrder(); order.setRootAppId(appId); order.setRootProfileId(profileId); EmptyResult result = refreshService.refreshClients(order); checkResult(result, Status.SUCCESS); } } } }
package com.athena.meerkat.controller.web.tomcat.services; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.persistence.EntityManagerFactory; import org.apache.catalina.startup.Tomcat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy; import com.athena.meerkat.controller.MeerkatConstants; import com.athena.meerkat.controller.common.SSHManager; import com.athena.meerkat.controller.tomcat.instance.domain.ConfigFileVersionRepository; import com.athena.meerkat.controller.web.common.code.CommonCodeRepository; import com.athena.meerkat.controller.web.entities.DataSource; import com.athena.meerkat.controller.web.entities.DomainTomcatConfiguration; import com.athena.meerkat.controller.web.entities.TomcatApplication; import com.athena.meerkat.controller.web.entities.TomcatInstConfig; import com.athena.meerkat.controller.web.entities.TomcatInstance; import com.athena.meerkat.controller.web.provisioning.TomcatProvisioningService; import com.athena.meerkat.controller.web.resources.repositories.DataSourceRepository; import com.athena.meerkat.controller.web.tomcat.repositories.ApplicationRepository; import com.athena.meerkat.controller.web.tomcat.repositories.TomcatConfigFileRepository; import com.athena.meerkat.controller.web.tomcat.repositories.TomcatInstConfigRepository; import com.athena.meerkat.controller.web.tomcat.repositories.TomcatInstanceRepository; /** * <pre> * * </pre> * * @author Bong-Jin Kwon * @author Tran Ho * @version 2.0 */ @Service public class TomcatInstanceService { static final Logger LOGGER = LoggerFactory .getLogger(TomcatInstanceService.class); @Autowired private TomcatInstanceRepository repo; @Autowired private DataSourceRepository datasourceRepo; @Autowired private ConfigFileVersionRepository configRepo; @Autowired private TomcatInstConfigRepository tomcatInstConfigRepo; @Autowired private EntityManagerFactory entityManagerFactory; @Autowired private CommonCodeRepository commonRepo; @Autowired private TomcatConfigFileRepository tomcatConfigFileRepo; @Autowired private ApplicationRepository appRepo; @Autowired private TomcatDomainService domainService; public TomcatInstanceService() { // TODO Auto-generated constructor stub } public Page<TomcatInstance> getList(Pageable pageable) { return repo.findAll(pageable); } public List<TomcatInstance> getTomcatListByDomainId(int domainId) { return repo.findByTomcatDomain_Id(domainId); } /** * insert or update * * @param inst */ public TomcatInstance save(TomcatInstance inst) { return repo.save(inst); } public void saveList(List<TomcatInstance> entities) { repo.save(entities); } public TomcatInstance findOne(int id) { return repo.findOne(id); } public DomainTomcatConfiguration getTomcatConfig(int instanceId) { TomcatInstance tomcat = findOne(instanceId); return getTomcatConfig(tomcat.getDomainId(), instanceId); } public DomainTomcatConfiguration getTomcatConfig(int domainId, int instanceId) { DomainTomcatConfiguration conf = domainService .getTomcatConfig(domainId); // get configurations that are different to domain tomcat config List<TomcatInstConfig> changedConfigs = getTomcatInstConfigs(instanceId); if (changedConfigs != null) { for (TomcatInstConfig changedConf : changedConfigs) { Method[] methods = DomainTomcatConfiguration.class.getMethods(); for (Method m : methods) { // check the setter method if (m.getName() .toLowerCase() .contains( "set" + changedConf.getConfigName() .toLowerCase())) { try { // run setter method to update value m.invoke(conf, changedConf.getConfigValue()); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } conf.setTomcatInstanceId(instanceId); return conf; } public List<TomcatInstance> findInstances(int serverId) { return repo.findByServer_Id(serverId); } public List<DomainTomcatConfiguration> findInstanceConfigs(int serverId) { List<DomainTomcatConfiguration> configs = new ArrayList<DomainTomcatConfiguration>(); List<TomcatInstance> list = repo.findByServer_Id(serverId); for (TomcatInstance tomcatInstance : list) { configs.add(getTomcatConfig(tomcatInstance.getDomainId(), tomcatInstance.getId())); } return configs; } public void delete(int id) { repo.delete(id); } public List<DataSource> getDataSourceListByTomcat(TomcatInstance tomcat) { // List<DataSource> list = (List<DataSource>) tomcat.getDataSources(); // return list; return null; } @Async public void loadTomcatConfig(TomcatInstance inst) { int state = 0; // SSHManager sshMng = new SSHManager(inst.getSshUsername(), // inst.getSshPassword(), inst.getIpAddr(), "", inst.getSshPort()); // String errorMsg = sshMng.connect(); // try { // if (errorMsg != null) { // inst.setErrMsg(errorMsg); // saveState(inst, 1); // } else { // state = DollyConstants.INSTANCE_STATE_PEND1; // loadEnvSH(sshMng, inst, state); // state = DollyConstants.INSTANCE_STATE_PEND2; // loadServerXML(sshMng, inst, state); // state = DollyConstants.INSTANCE_STATE_PEND3; // loadContextXML(sshMng, inst, state); // state = DollyConstants.INSTANCE_STATE_VALID; // saveState(inst, state); // } catch (Exception e) { // logger.error("", e); // state++; // inst.setErrMsg(e.toString()); // saveState(inst, state); // } finally { // sshMng.close(); } /** * env.sh & ?? * * @param inst */ public void loadEnvSH(SSHManager sshMng, TomcatInstance inst, int state) throws UnsupportedEncodingException { // String remoteFile = inst.getCatalinaBase() // + inst.getEnvScriptFile().replaceFirst("$CATALINA_BASE", ""); // // sshMng.scpDown(remoteFile, "D:/env.sh"); // byte[] fileByte = sshMng.scpDown(remoteFile); // String envStr = new String(fileByte, "UTF-8"); // QConfigFileVersion confVer = QConfigFileVersion.configFileVersion; // EntityManager entityManager = this.entityManagerFactory // .createEntityManager(); // JPAQuery query = new JPAQuery(entityManager); // Integer maxRevision = query // .from(confVer) // .where(confVer.tomcatInstanceId.eq(inst.getId()), // confVer.fileType.eq(1)) // .uniqueResult(confVer.revision.max()); // int revision = 0; // if (maxRevision != null) { // revision = maxRevision.intValue(); // ConfigFileVersion fileVer = new ConfigFileVersion(inst.getId(), 1, // remoteFile, envStr); // fileVer.setRevision(revision + 1); // configRepo.save(fileVer); // saveState(inst, state); } public void saveState(int instanceId, int state) { repo.setState(instanceId, state); LOGGER.debug("tomcat instance({}) state({}) saved.", instanceId, state); } public List<TomcatInstance> getAll() { return repo.findAll(); } /** * <pre> * * </pre> * * @param name * @param domainId * @return */ public List<TomcatInstance> findByNameAndDomain(String name, int domainId) { return repo.findByNameContainingAndTomcatDomain_Id(name, domainId); } public List<TomcatInstConfig> getTomcatInstConfigs(int tomcatId) { return tomcatInstConfigRepo.findByTomcatInstance_Id(tomcatId); } public List<TomcatApplication> getApplicationByTomcat(int id) { return appRepo.findByTomcatInstance_Id(id); } public void saveTomcatConfig(TomcatInstance tomcat, DomainTomcatConfiguration conf) { List<TomcatInstConfig> tomcatConfs = new ArrayList<>(); if (conf != null) { // get all fields in domain tomcat config Field[] fields = DomainTomcatConfiguration.class .getDeclaredFields(); for (Field field : fields) { // check whether the config property is exist in read-only // conf // list String name = field.getName(); if (Arrays.asList( MeerkatConstants.TOMCAT_INSTANCE_CONFIGS_CUSTOM) .contains(name)) { String value = ""; try { field.setAccessible(true); value = field.get(conf).toString(); field.setAccessible(false); } catch (IllegalArgumentException | IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } TomcatInstConfig tomcatConf = tomcatInstConfigRepo .findByConfigNameAndTomcatInstance(name, tomcat); if (tomcatConf != null) { tomcatConf.setConfigValue(value); } else { tomcatConf = new TomcatInstConfig(tomcat, name, value); } tomcatConfs.add(tomcatConf); } } tomcatInstConfigRepo.save(tomcatConfs); } } }
package org.csstudio.platform.simpledal; /** * The state of a connection to a PV. * * @author Sven Wende */ @Deprecated public enum ConnectionState { /** * If state is not a valid DAL-state. * Used as initial connection state. */ UNKNOWN(null), INITIAL(org.epics.css.dal.context.ConnectionState.INITIAL), /** * If connection is valid and connected. */ CONNECTED(org.epics.css.dal.context.ConnectionState.CONNECTED), /** * If the connection get lost in case of any problem. */ CONNECTION_LOST(org.epics.css.dal.context.ConnectionState.CONNECTION_LOST), /** * If the connection to the PV failed or failed in re-connect. */ CONNECTION_FAILED(org.epics.css.dal.context.ConnectionState.CONNECTION_FAILED), /** * If connection get disposed / disconnected. */ DISCONNECTED(org.epics.css.dal.context.ConnectionState.DISCONNECTED); private org.epics.css.dal.context.ConnectionState _dalState; /** * Constructor. * @param dalState */ private ConnectionState(org.epics.css.dal.context.ConnectionState dalState) { _dalState = dalState; } /** * Transfers this state into a DAL-state. * * @return The DAL-state of this state. */ public org.epics.css.dal.context.ConnectionState getDalState() { return _dalState; } /** * Translates a DAL-state to a matching value of this state-type. * * @param dalState * The DAL-state to be translated. * @return The matching state of this type, {@link ConnectionState.UNKNOWN} * if not avail. */ public static ConnectionState translate(org.epics.css.dal.context.ConnectionState dalState) { ConnectionState result = UNKNOWN; for (ConnectionState s : values()) { if(s.getDalState() == dalState) { result = s; } } // TODO: // If the incomming state is org.epics.css.dal.context.ConnectionState.OPERATIONAL, // the result value is always UNKNOWN // because the old ConnectionState enum does not contain such a state. // This causes always an error in the application DepartmentDecision (NAMS) if ((result == UNKNOWN) && (dalState == org.epics.css.dal.context.ConnectionState.OPERATIONAL)) { result = ConnectionState.CONNECTED; } return result; } }
package org.lemurproject.galago.core.retrieval.traversal; import java.io.IOException; import java.util.HashSet; import org.lemurproject.galago.core.index.AggregateReader.CollectionStatistics2; import org.lemurproject.galago.core.index.AggregateReader.NodeStatistics; import org.lemurproject.galago.core.retrieval.GroupRetrieval; import org.lemurproject.galago.core.retrieval.query.Node; import org.lemurproject.galago.core.retrieval.query.NodeType; import org.lemurproject.galago.core.retrieval.iterator.CountIterator; import org.lemurproject.galago.core.retrieval.Retrieval; import org.lemurproject.galago.core.retrieval.iterator.StructuredIterator; import org.lemurproject.galago.core.retrieval.query.NodeParameters; import org.lemurproject.galago.core.retrieval.structured.RequiredStatistics; import org.lemurproject.galago.tupleflow.Parameters; /** * Class collects collections statistics: - collectionLength : number of terms * in index part / collection - documentCount : number of documents in index * part / collection - vocabCount : number of unique terms in index part - * nodeFrequency : number of matching instances of node in index part / * collection - nodeDocumentCount : number of matching documents for node in * index part / collection - collectionProbability : nodeFrequency / * collectionLength * * @author sjh */ public class AnnotateCollectionStatistics extends Traversal { HashSet<String> availableStatistics; Parameters globalParameters; Retrieval retrieval; // featurefactory is necessary to get the correct class public AnnotateCollectionStatistics(Retrieval retrieval) throws IOException { this.globalParameters = retrieval.getGlobalParameters(); this.retrieval = retrieval; this.availableStatistics = new HashSet(); // field or document region statistics this.availableStatistics.add("collectionLength"); this.availableStatistics.add("documentCount"); this.availableStatistics.add("maxLength"); this.availableStatistics.add("minLength"); this.availableStatistics.add("avgLength"); // countable-node statistics this.availableStatistics.add("nodeFrequency"); this.availableStatistics.add("nodeDocumentCount"); } public void beforeNode(Node node) { } public Node afterNode(Node node) throws Exception { // need to get list of required statistics RequiredStatistics required = null; Class<? extends StructuredIterator> c = retrieval.getNodeType(node).getIteratorClass(); required = c.getAnnotation(RequiredStatistics.class); // then annotate the node with any of: // -- nodeFreq, nodeDocCount, collLen, docCount, collProb if (required != null) { HashSet<String> reqStats = new HashSet(); for (String stat : required.statistics()) { if (availableStatistics.contains(stat)) { reqStats.add(stat); } } if (!reqStats.isEmpty()) { annotate(node, reqStats); } } return node; } private void annotate(Node node, HashSet<String> reqStats) throws Exception { NodeParameters nodeParams = node.getNodeParameters(); if (reqStats.contains("collectionLength") || reqStats.contains("documentCount") || reqStats.contains("maxLength") || reqStats.contains("minLength") || reqStats.contains("avgLength")) { // extract field if possible: // use 'document' as the default context String field = node.getNodeParameters().get("lengths", "document"); CollectionStatistics2 stats = getCollectionStatistics(field); if (reqStats.contains("collectionLength") && !nodeParams.containsKey("collectionLength")) { nodeParams.set("collectionLength", stats.collectionLength); } if (reqStats.contains("documentCount") && !nodeParams.containsKey("documentCount")) { nodeParams.set("documentCount", stats.documentCount); } if (reqStats.contains("maxLength") && !nodeParams.containsKey("maxLength")) { nodeParams.set("maxLength", stats.maxLength); } if (reqStats.contains("minLength") && !nodeParams.containsKey("minLength")) { nodeParams.set("minLength", stats.minLength); } if (reqStats.contains("avgLength") && !nodeParams.containsKey("avgLength")) { nodeParams.set("avgLength", stats.avgLength); } } if (reqStats.contains("nodeFrequency") || reqStats.contains("nodeDocumentCount")) { NodeStatistics stats = getNodeStatistics(node); if (stats == null) { return; } if (reqStats.contains("nodeFrequency") && !nodeParams.containsKey("nodeFrequency")) { nodeParams.set("nodeFrequency", stats.nodeFrequency); } if (reqStats.contains("nodeDocumentCount") && !nodeParams.containsKey("nodeDocumentCount")) { nodeParams.set("nodeDocumentCount", stats.nodeDocumentCount); } } } private CollectionStatistics2 getCollectionStatistics(String field) throws Exception { if (globalParameters.isString("backgroundIndex")) { assert (GroupRetrieval.class.isAssignableFrom(retrieval.getClass())) : "Retrieval object must be a GroupRetrieval to use the backgroundIndex parameter."; return ((GroupRetrieval) retrieval).collectionStatistics("#lengths:"+field+":part=lengths()", globalParameters.getString("backgroundIndex")); } else { return retrieval.collectionStatistics("#lengths:"+field+":part=lengths()"); } } private NodeStatistics getNodeStatistics(Node node) throws Exception { // recurses down a stick (single children nodes only) if (isCountNode(node)) { return collectStatistics(node); } else if (node.getInternalNodes().size() == 1) { return getNodeStatistics(node.getInternalNodes().get(0)); } else if (node.getInternalNodes().size() == 2) { return getNodeStatistics(node.getInternalNodes().get(1)); } return null; } private NodeStatistics collectStatistics(Node countNode) throws Exception { // recursively check if any child nodes use a specific background part Node n = assignParts(countNode.clone()); if (globalParameters.isString("backgroundIndex")) { assert (GroupRetrieval.class.isAssignableFrom(retrieval.getClass())) : "Retrieval object must be a GroupRetrieval to use the backgroundIndex parameter."; return ((GroupRetrieval) retrieval).nodeStatistics(n, globalParameters.getString("backgroundIndex")); } else { return retrieval.nodeStatistics(n); } } private boolean isCountNode(Node node) throws Exception { NodeType nodeType = retrieval.getNodeType(node); if (nodeType == null) { return false; } Class outputClass = nodeType.getIteratorClass(); return CountIterator.class.isAssignableFrom(outputClass); } private Node assignParts(Node n) { if (n.getInternalNodes().isEmpty()) { // we should have a part by now. String part = n.getNodeParameters().getString("part"); // check if there is a new background part to assign if (n.getNodeParameters().isString("backgroundPart")) { n.getNodeParameters().set("part", n.getNodeParameters().getString("backgroundPart")); return n; } else if (globalParameters.isMap("backgroundPartMap") && globalParameters.getMap("backgroundPartMap").isString(part)) { n.getNodeParameters().set("part", globalParameters.getMap("backgroundPartMap").getString(part)); return n; } // otherwise no change. return n; } else { // has a child: assign parts to children: for (Node c : n.getInternalNodes()) { assignParts(c); } return n; } } }
package org.onosproject.store.consistent.impl; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.lang.math.RandomUtils; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onlab.util.KryoNamespace; import org.onosproject.cluster.ClusterEvent; import org.onosproject.cluster.ClusterEvent.Type; import org.onosproject.cluster.ClusterEventListener; import org.onosproject.cluster.ClusterService; import org.onosproject.cluster.Leadership; import org.onosproject.cluster.LeadershipEvent; import org.onosproject.cluster.LeadershipEventListener; import org.onosproject.cluster.LeadershipService; import org.onosproject.cluster.NodeId; import org.onosproject.event.ListenerRegistry; import org.onosproject.event.EventDeliveryService; import org.onosproject.store.cluster.messaging.ClusterCommunicationService; import org.onosproject.store.cluster.messaging.MessageSubject; import org.onosproject.store.serializers.KryoNamespaces; import org.onosproject.store.service.ConsistentMap; import org.onosproject.store.service.ConsistentMapException; import org.onosproject.store.service.Serializer; import org.onosproject.store.service.StorageService; import org.onosproject.store.service.Versioned; import org.slf4j.Logger; import java.util.ArrayList; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; import static org.onlab.util.Tools.groupedThreads; import static org.slf4j.LoggerFactory.getLogger; import static org.onosproject.cluster.ControllerNode.State.ACTIVE; import static org.onosproject.cluster.ControllerNode.State.INACTIVE; /** * Distributed Lock Manager implemented on top of ConsistentMap. * <p> * This implementation makes use of ClusterService's failure * detection capabilities to detect and purge stale locks. * TODO: Ensure lock safety and liveness. */ @Component(immediate = true, enabled = true) @Service public class DistributedLeadershipManager implements LeadershipService { @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected StorageService storageService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected ClusterService clusterService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected ClusterCommunicationService clusterCommunicator; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected EventDeliveryService eventDispatcher; private static final MessageSubject LEADERSHIP_EVENT_MESSAGE_SUBJECT = new MessageSubject("distributed-leadership-manager-events"); private final Logger log = getLogger(getClass()); private ExecutorService messageHandlingExecutor; private ScheduledExecutorService electionRunner; private ScheduledExecutorService lockExecutor; private ScheduledExecutorService staleLeadershipPurgeExecutor; private ScheduledExecutorService leadershipStatusBroadcaster; private ConsistentMap<String, NodeId> leaderMap; private ConsistentMap<String, List<NodeId>> candidateMap; private ListenerRegistry<LeadershipEvent, LeadershipEventListener> listenerRegistry; private final Map<String, Leadership> leaderBoard = Maps.newConcurrentMap(); private final Map<String, Leadership> candidateBoard = Maps.newConcurrentMap(); private final ClusterEventListener clusterEventListener = new InternalClusterEventListener(); private NodeId localNodeId; private Set<String> activeTopics = Sets.newConcurrentHashSet(); private Map<String, CompletableFuture<Leadership>> pendingFutures = Maps.newConcurrentMap(); // The actual delay is randomly chosen between the interval [0, WAIT_BEFORE_RETRY_MILLIS) private static final int WAIT_BEFORE_RETRY_MILLIS = 150; private static final int DELAY_BETWEEN_LEADER_LOCK_ATTEMPTS_SEC = 2; private static final int LEADERSHIP_STATUS_UPDATE_INTERVAL_SEC = 2; private static final int DELAY_BETWEEN_STALE_LEADERSHIP_PURGE_ATTEMPTS_SEC = 2; private final AtomicBoolean staleLeadershipPurgeScheduled = new AtomicBoolean(false); private static final Serializer SERIALIZER = Serializer.using( new KryoNamespace.Builder().register(KryoNamespaces.API).build()); @Activate public void activate() { leaderMap = storageService.<String, NodeId>consistentMapBuilder() .withName("onos-topic-leaders") .withSerializer(SERIALIZER) .withPartitionsDisabled().build(); candidateMap = storageService.<String, List<NodeId>>consistentMapBuilder() .withName("onos-topic-candidates") .withSerializer(SERIALIZER) .withPartitionsDisabled().build(); localNodeId = clusterService.getLocalNode().id(); messageHandlingExecutor = Executors.newSingleThreadExecutor( groupedThreads("onos/store/leadership", "message-handler")); electionRunner = Executors.newSingleThreadScheduledExecutor( groupedThreads("onos/store/leadership", "election-runner")); lockExecutor = Executors.newScheduledThreadPool( 4, groupedThreads("onos/store/leadership", "election-thread-%d")); staleLeadershipPurgeExecutor = Executors.newSingleThreadScheduledExecutor( groupedThreads("onos/store/leadership", "stale-leadership-evictor")); leadershipStatusBroadcaster = Executors.newSingleThreadScheduledExecutor( groupedThreads("onos/store/leadership", "peer-updater")); clusterCommunicator.addSubscriber( LEADERSHIP_EVENT_MESSAGE_SUBJECT, SERIALIZER::decode, this::onLeadershipEvent, messageHandlingExecutor); clusterService.addListener(clusterEventListener); electionRunner.scheduleWithFixedDelay( this::electLeaders, 0, DELAY_BETWEEN_LEADER_LOCK_ATTEMPTS_SEC, TimeUnit.SECONDS); leadershipStatusBroadcaster.scheduleWithFixedDelay( this::sendLeadershipStatus, 0, LEADERSHIP_STATUS_UPDATE_INTERVAL_SEC, TimeUnit.SECONDS); listenerRegistry = new ListenerRegistry<>(); eventDispatcher.addSink(LeadershipEvent.class, listenerRegistry); log.info("Started"); } @Deactivate public void deactivate() { leaderBoard.forEach((topic, leadership) -> { if (localNodeId.equals(leadership.leader())) { withdraw(topic); } }); clusterService.removeListener(clusterEventListener); eventDispatcher.removeSink(LeadershipEvent.class); clusterCommunicator.removeSubscriber(LEADERSHIP_EVENT_MESSAGE_SUBJECT); electionRunner.shutdown(); messageHandlingExecutor.shutdown(); lockExecutor.shutdown(); staleLeadershipPurgeExecutor.shutdown(); leadershipStatusBroadcaster.shutdown(); log.info("Stopped"); } @Override public Map<String, Leadership> getLeaderBoard() { return ImmutableMap.copyOf(leaderBoard); } @Override public Map<String, List<NodeId>> getCandidates() { return Maps.toMap(candidateBoard.keySet(), this::getCandidates); } @Override public List<NodeId> getCandidates(String path) { Leadership current = candidateBoard.get(path); return current == null ? ImmutableList.of() : ImmutableList.copyOf(current.candidates()); } @Override public NodeId getLeader(String path) { Leadership leadership = leaderBoard.get(path); return leadership != null ? leadership.leader() : null; } @Override public Leadership getLeadership(String path) { checkArgument(path != null); return leaderBoard.get(path); } @Override public Set<String> ownedTopics(NodeId nodeId) { checkArgument(nodeId != null); return leaderBoard.entrySet() .stream() .filter(entry -> nodeId.equals(entry.getValue().leader())) .map(Entry::getKey) .collect(Collectors.toSet()); } @Override public CompletableFuture<Leadership> runForLeadership(String path) { log.debug("Running for leadership for topic: {}", path); CompletableFuture<Leadership> resultFuture = new CompletableFuture<>(); doRunForLeadership(path, resultFuture); return resultFuture; } private void doRunForLeadership(String path, CompletableFuture<Leadership> future) { try { Versioned<List<NodeId>> candidates = candidateMap.computeIf(path, currentList -> currentList == null || !currentList.contains(localNodeId), (topic, currentList) -> { if (currentList == null) { return ImmutableList.of(localNodeId); } else { List<NodeId> newList = Lists.newLinkedList(); newList.addAll(currentList); newList.add(localNodeId); return newList; } }); publish(new LeadershipEvent( LeadershipEvent.Type.CANDIDATES_CHANGED, new Leadership(path, candidates.value(), candidates.version(), candidates.creationTime()))); log.debug("In the leadership race for topic {} with candidates {}", path, candidates); activeTopics.add(path); Leadership leadership = electLeader(path, candidates.value()); if (leadership == null) { pendingFutures.put(path, future); } else { future.complete(leadership); } } catch (ConsistentMapException e) { log.debug("Failed to enter topic leader race for {}. Retrying.", path, e); rerunForLeadership(path, future); } } @Override public CompletableFuture<Void> withdraw(String path) { activeTopics.remove(path); CompletableFuture<Void> resultFuture = new CompletableFuture<>(); doWithdraw(path, resultFuture); return resultFuture; } private void doWithdraw(String path, CompletableFuture<Void> future) { if (activeTopics.contains(path)) { future.completeExceptionally(new CancellationException(String.format("%s is now a active topic", path))); } try { Versioned<NodeId> leader = leaderMap.get(path); if (leader != null && Objects.equals(leader.value(), localNodeId)) { if (leaderMap.remove(path, leader.version())) { log.debug("Gave up leadership for {}", path); future.complete(null); publish(new LeadershipEvent( LeadershipEvent.Type.LEADER_BOOTED, new Leadership(path, localNodeId, leader.version(), leader.creationTime()))); } } // else we are not the current leader, can still be a candidate. Versioned<List<NodeId>> candidates = candidateMap.get(path); List<NodeId> candidateList = candidates != null ? Lists.newArrayList(candidates.value()) : Lists.newArrayList(); if (!candidateList.remove(localNodeId)) { future.complete(null); return; } if (candidateMap.replace(path, candidates.version(), candidateList)) { Versioned<List<NodeId>> newCandidates = candidateMap.get(path); future.complete(null); publish(new LeadershipEvent( LeadershipEvent.Type.CANDIDATES_CHANGED, new Leadership(path, newCandidates.value(), newCandidates.version(), newCandidates.creationTime()))); } else { log.debug("Failed to withdraw from candidates list for {}. Will retry", path); retryWithdraw(path, future); } } catch (Exception e) { log.debug("Failed to verify (and clear) any lock this node might be holding for {}", path, e); retryWithdraw(path, future); } } @Override public boolean stepdown(String path) { if (!activeTopics.contains(path) || !Objects.equals(localNodeId, getLeader(path))) { return false; } try { Versioned<NodeId> leader = leaderMap.get(path); if (leader != null && Objects.equals(leader.value(), localNodeId)) { if (leaderMap.remove(path, leader.version())) { log.debug("Stepped down from leadership for {}", path); publish(new LeadershipEvent( LeadershipEvent.Type.LEADER_BOOTED, new Leadership(path, localNodeId, leader.version(), leader.creationTime()))); return true; } } } catch (Exception e) { log.warn("Error executing stepdown for {}", path, e); } return false; } @Override public void addListener(LeadershipEventListener listener) { listenerRegistry.addListener(listener); } @Override public void removeListener(LeadershipEventListener listener) { listenerRegistry.removeListener(listener); } @Override public boolean makeTopCandidate(String path, NodeId nodeId) { Versioned<List<NodeId>> newCandidates = candidateMap.computeIf(path, candidates -> candidates != null && candidates.contains(nodeId) && !nodeId.equals(Iterables.getFirst(candidates, null)), (topic, candidates) -> { List<NodeId> updatedCandidates = new ArrayList<>(candidates.size()); updatedCandidates.add(nodeId); candidates.stream().filter(id -> !nodeId.equals(id)).forEach(updatedCandidates::add); return updatedCandidates; }); publish(new LeadershipEvent( LeadershipEvent.Type.CANDIDATES_CHANGED, new Leadership(path, newCandidates.value(), newCandidates.version(), newCandidates.creationTime()))); return true; } private Leadership electLeader(String path, List<NodeId> candidates) { Leadership currentLeadership = getLeadership(path); if (currentLeadership != null) { return currentLeadership; } else { NodeId topCandidate = candidates .stream() .filter(n -> clusterService.getState(n) == ACTIVE) .findFirst() .orElse(null); try { Versioned<NodeId> leader = localNodeId.equals(topCandidate) ? leaderMap.computeIfAbsent(path, p -> localNodeId) : leaderMap.get(path); if (leader != null) { Leadership newLeadership = new Leadership(path, leader.value(), leader.version(), leader.creationTime()); publish(new LeadershipEvent( LeadershipEvent.Type.LEADER_ELECTED, newLeadership)); return newLeadership; } } catch (Exception e) { log.debug("Failed to elect leader for {}", path, e); } } return null; } private void electLeaders() { try { candidateMap.entrySet().forEach(entry -> { String path = entry.getKey(); Versioned<List<NodeId>> candidates = entry.getValue(); // for active topics, check if this node can become a leader (if it isn't already) if (activeTopics.contains(path)) { lockExecutor.submit(() -> { Leadership leadership = electLeader(path, candidates.value()); if (leadership != null) { CompletableFuture<Leadership> future = pendingFutures.remove(path); if (future != null) { future.complete(leadership); } } }); } // Raise a CANDIDATES_CHANGED event to force refresh local candidate board // and also to update local listeners. // Don't worry about duplicate events as they will be suppressed. onLeadershipEvent(new LeadershipEvent(LeadershipEvent.Type.CANDIDATES_CHANGED, new Leadership(path, candidates.value(), candidates.version(), candidates.creationTime()))); }); } catch (Exception e) { log.debug("Failure electing leaders", e); } } private void publish(LeadershipEvent event) { onLeadershipEvent(event); clusterCommunicator.broadcast(event, LEADERSHIP_EVENT_MESSAGE_SUBJECT, SERIALIZER::encode); } private void onLeadershipEvent(LeadershipEvent leadershipEvent) { log.trace("Leadership Event: time = {} type = {} event = {}", leadershipEvent.time(), leadershipEvent.type(), leadershipEvent); Leadership leadershipUpdate = leadershipEvent.subject(); LeadershipEvent.Type eventType = leadershipEvent.type(); String topic = leadershipUpdate.topic(); AtomicBoolean updateAccepted = new AtomicBoolean(false); if (eventType.equals(LeadershipEvent.Type.LEADER_ELECTED)) { leaderBoard.compute(topic, (k, currentLeadership) -> { if (currentLeadership == null || currentLeadership.epoch() < leadershipUpdate.epoch()) { updateAccepted.set(true); return leadershipUpdate; } return currentLeadership; }); } else if (eventType.equals(LeadershipEvent.Type.LEADER_BOOTED)) { leaderBoard.compute(topic, (k, currentLeadership) -> { if (currentLeadership == null || currentLeadership.epoch() <= leadershipUpdate.epoch()) { updateAccepted.set(true); return null; } return currentLeadership; }); } else if (eventType.equals(LeadershipEvent.Type.CANDIDATES_CHANGED)) { candidateBoard.compute(topic, (k, currentInfo) -> { if (currentInfo == null || currentInfo.epoch() < leadershipUpdate.epoch()) { updateAccepted.set(true); return leadershipUpdate; } return currentInfo; }); } else { throw new IllegalStateException("Unknown event type."); } if (updateAccepted.get()) { eventDispatcher.post(leadershipEvent); } } private void rerunForLeadership(String path, CompletableFuture<Leadership> future) { lockExecutor.schedule( () -> doRunForLeadership(path, future), RandomUtils.nextInt(WAIT_BEFORE_RETRY_MILLIS), TimeUnit.MILLISECONDS); } private void retryWithdraw(String path, CompletableFuture<Void> future) { lockExecutor.schedule( () -> doWithdraw(path, future), RandomUtils.nextInt(WAIT_BEFORE_RETRY_MILLIS), TimeUnit.MILLISECONDS); } private void scheduleStaleLeadershipPurge(int afterDelaySec) { if (staleLeadershipPurgeScheduled.compareAndSet(false, true)) { staleLeadershipPurgeExecutor.schedule( this::purgeStaleLeadership, afterDelaySec, TimeUnit.SECONDS); } } /** * Purges locks held by inactive nodes and evicts inactive nodes from candidacy. */ private void purgeStaleLeadership() { AtomicBoolean rerunPurge = new AtomicBoolean(false); try { staleLeadershipPurgeScheduled.set(false); leaderMap.entrySet() .stream() .filter(e -> clusterService.getState(e.getValue().value()) == INACTIVE) .forEach(entry -> { String path = entry.getKey(); NodeId nodeId = entry.getValue().value(); long epoch = entry.getValue().version(); long creationTime = entry.getValue().creationTime(); try { if (leaderMap.remove(path, epoch)) { log.debug("Purged stale lock held by {} for {}", nodeId, path); publish(new LeadershipEvent( LeadershipEvent.Type.LEADER_BOOTED, new Leadership(path, nodeId, epoch, creationTime))); } } catch (Exception e) { log.debug("Failed to purge stale lock held by {} for {}", nodeId, path, e); rerunPurge.set(true); } }); candidateMap.entrySet() .forEach(entry -> { String path = entry.getKey(); Versioned<List<NodeId>> candidates = entry.getValue(); List<NodeId> candidatesList = candidates != null ? candidates.value() : Collections.emptyList(); List<NodeId> activeCandidatesList = candidatesList.stream() .filter(n -> clusterService.getState(n) == ACTIVE) .filter(n -> !localNodeId.equals(n) || activeTopics.contains(path)) .collect(Collectors.toList()); if (activeCandidatesList.size() < candidatesList.size()) { Set<NodeId> removedCandidates = Sets.difference(Sets.newHashSet(candidatesList), Sets.newHashSet(activeCandidatesList)); try { if (candidateMap.replace(path, entry.getValue().version(), activeCandidatesList)) { log.info("Evicted inactive candidates {} from " + "candidate list for {}", removedCandidates, path); Versioned<List<NodeId>> updatedCandidates = candidateMap.get(path); publish(new LeadershipEvent( LeadershipEvent.Type.CANDIDATES_CHANGED, new Leadership(path, updatedCandidates.value(), updatedCandidates.version(), updatedCandidates.creationTime()))); } else { // Conflicting update detected. Rerun purge to make sure // inactive candidates are evicted. rerunPurge.set(true); } } catch (Exception e) { log.debug("Failed to evict inactive candidates {} from " + "candidate list for {}", removedCandidates, path, e); rerunPurge.set(true); } } }); } catch (Exception e) { log.debug("Failure purging state leadership.", e); rerunPurge.set(true); } if (rerunPurge.get()) { log.debug("Rescheduling stale leadership purge due to errors encountered in previous run"); scheduleStaleLeadershipPurge(DELAY_BETWEEN_STALE_LEADERSHIP_PURGE_ATTEMPTS_SEC); } } private void sendLeadershipStatus() { try { leaderBoard.forEach((path, leadership) -> { if (leadership.leader().equals(localNodeId)) { LeadershipEvent event = new LeadershipEvent(LeadershipEvent.Type.LEADER_ELECTED, leadership); clusterCommunicator.broadcast(event, LEADERSHIP_EVENT_MESSAGE_SUBJECT, SERIALIZER::encode); } }); } catch (Exception e) { log.debug("Failed to send leadership updates", e); } } private class InternalClusterEventListener implements ClusterEventListener { @Override public void event(ClusterEvent event) { if (event.type() == Type.INSTANCE_DEACTIVATED || event.type() == Type.INSTANCE_REMOVED) { scheduleStaleLeadershipPurge(0); } } } }
package org.collectionspace.chain.csp.persistence.services; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import org.apache.commons.lang.StringUtils; import org.collectionspace.chain.csp.persistence.services.vocab.RefName; import org.collectionspace.chain.csp.schema.Field; import org.collectionspace.chain.csp.schema.FieldSet; import org.collectionspace.chain.csp.schema.Group; import org.collectionspace.chain.csp.schema.Instance; import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.chain.csp.schema.Repeat; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class XmlJsonConversion { private static final Logger log=LoggerFactory.getLogger(XmlJsonConversion.class); private static void addFieldToXml(Element root,Field field,JSONObject in, String permlevel) throws JSONException, UnderlyingStorageException { String value=in.optString(field.getID()); Element element=root.addElement(field.getServicesTag()); if(field.getUIType().startsWith("groupfield")){ if(in.has(field.getID())){ addSubRecordToXml(element,field,in.getJSONObject(field.getID()), permlevel); } } else{ element.addText(value); } } private static void addSubRecordToXml(Element root,Field field,JSONObject in, String permlevel) throws JSONException, UnderlyingStorageException{ String parts[] = field.getUIType().split("/"); Record subitems = field.getRecord().getSpec().getRecordByServicesUrl(parts[1]); if(subitems.getAllServiceFields(permlevel,"common").length >0){ for(FieldSet f : subitems.getAllServiceFields(permlevel,"common")) { addFieldSetToXml(root,f,in,"common",permlevel); } String test = root.asXML(); log.debug(root.asXML()); //return doc; } } //XXX could refactor this and addRepeatToXML as this is what happens in the middle of addRepeatToXML private static void addGroupToXml(Element root, Group group, JSONObject in, String section, String permlevel) throws JSONException, UnderlyingStorageException{ Element element=root; if(group.hasServicesParent()){ for(String path : group.getServicesParent()){ if(path !=null){ element=element.addElement(path); } } } Object value=null; value=in.opt(group.getID()); if(value==null || ((value instanceof String) && StringUtils.isBlank((String)value))) return; if(value instanceof String) { // And sometimes the services ahead of the UI JSONObject next=new JSONObject(); next.put(group.getID(),value); value=next; } if(!(value instanceof JSONObject)) throw new UnderlyingStorageException("Bad JSON in repeated field: must be string or object for group field not an array - that would a repeat field"); JSONObject object=(JSONObject)value; Element groupelement=element; groupelement=element.addElement(group.getServicesTag()); Object one_value=object; if(one_value==null || ((one_value instanceof String) && StringUtils.isBlank((String)one_value))) { //do nothing } else if(one_value instanceof String) { // Assume it's just the first entry (useful if there's only one) FieldSet[] fs=group.getChildren(permlevel); if(fs.length<1){ //do nothing } else{ JSONObject d1=new JSONObject(); d1.put(fs[0].getID(),one_value); addFieldSetToXml(groupelement,fs[0],d1,section,permlevel); } } else if(one_value instanceof JSONObject) { for(FieldSet fs : group.getChildren(permlevel)) addFieldSetToXml(groupelement,fs,(JSONObject)one_value,section,permlevel); } element=groupelement; } private static void addRepeatToXml(Element root,Repeat repeat,JSONObject in,String section, String permlevel) throws JSONException, UnderlyingStorageException { Element element=root; if(repeat.hasServicesParent()){ for(String path : repeat.getServicesParent()){ if(path !=null){ element=element.addElement(path); } } } else if(!repeat.getXxxServicesNoRepeat()) { // Sometimes the UI is ahead of the services layer element=root.addElement(repeat.getServicesTag()); } Object value=null; if(repeat.getXxxUiNoRepeat()) { // and sometimes the app ahead of the services FieldSet[] children=repeat.getChildren(permlevel); if(children.length==0) return; addFieldSetToXml(element,children[0],in,section,permlevel); return; } else { value=in.opt(repeat.getID()); } if(value==null || ((value instanceof String) && StringUtils.isBlank((String)value))) return; if(value instanceof String) { // And sometimes the services ahead of the UI JSONArray next=new JSONArray(); next.put(value); value=next; } if(!(value instanceof JSONArray)) throw new UnderlyingStorageException("Bad JSON in repeated field: must be string or array for repeatable field"+repeat.getID()); JSONArray array=(JSONArray)value; //reorder the list if it has a primary //XXX this will be changed when service layer accepts non-initial values as primary if(repeat.hasPrimary()){ Stack<Object> orderedarray = new Stack<Object>(); for(int i=0;i<array.length();i++) { Object one_value=array.get(i); if(one_value instanceof JSONObject) { if(((JSONObject) one_value).has("_primary")){ if(((JSONObject) one_value).getBoolean("_primary")){ orderedarray.add(0, one_value); continue; } } } orderedarray.add(one_value); } JSONArray newarray = new JSONArray(); int j=0; for(Object obj : orderedarray){ newarray.put(j, obj); j++; } array = newarray; } Element repeatelement=element; for(int i=0;i<array.length();i++) { if(repeat.hasServicesParent()){ repeatelement=element.addElement(repeat.getServicesTag()); } Object one_value=array.get(i); if(one_value==null || ((one_value instanceof String) && StringUtils.isBlank((String)one_value))) continue; if(one_value instanceof String) { // Assume it's just the first entry (useful if there's only one) FieldSet[] fs=repeat.getChildren(permlevel); if(fs.length<1) continue; JSONObject d1=new JSONObject(); d1.put(fs[0].getID(),one_value); addFieldSetToXml(repeatelement,fs[0],d1,section,permlevel); } else if(one_value instanceof JSONObject) { for(FieldSet fs : repeat.getChildren(permlevel)) addFieldSetToXml(repeatelement,fs,(JSONObject)one_value,section,permlevel); } } element=repeatelement; } private static void addFieldSetToXml(Element root,FieldSet fs,JSONObject in,String section, String permlevel) throws JSONException, UnderlyingStorageException { if(!section.equals(fs.getSection())) return; if(fs instanceof Field) addFieldToXml(root,(Field)fs,in,permlevel); else if(fs instanceof Group){ addGroupToXml(root,(Group)fs,in,section,permlevel); } else if(fs instanceof Repeat){ addRepeatToXml(root,(Repeat)fs,in,section,permlevel); } } public static Document getXMLSoftDelete(){ Document doc=DocumentFactory.getInstance().createDocument(); Element subroot = doc.addElement("document"); subroot.addAttribute("name", "workflow"); Element root=subroot.addElement(new QName("workflow_common",new Namespace("ns2","http://collectionspace.org/services/workflow"))); root.addNamespace("xsi", "http: Element element=root.addElement("lifeCyclePolicy"); element.addText("default"); Element element2=root.addElement("currentLifeCycleState"); element2.addText("deleted"); String test = doc.asXML(); log.debug(doc.asXML()); return doc; /**<document name="workflows"> <ns2:workflows_common> <lifeCyclePolicy>default</lifeCyclePolicy> <currentLifeCycleState>deleted</currentLifeCycleState> </ns2:workflows_common> </document> **/ } public static Document getXMLRelationship(Element[] listItems){ Document doc=DocumentFactory.getInstance().createDocument(); Element root=doc.addElement(new QName("relations-common-list",new Namespace("ns3","http://collectionspace.org/services/relation"))); root.addNamespace("ns2", "http://collectionspace.org/services/jaxb"); if(listItems != null){ for(Element bitdoc : listItems){ root.add(bitdoc); } } return doc; } public static Document convertToXml(Record r,JSONObject in,String section, String permtype, Boolean useInstance) throws JSONException, UnderlyingStorageException { if(!useInstance){ return convertToXml( r, in, section, permtype); } Document doc=DocumentFactory.getInstance().createDocument(); String[] parts=r.getServicesRecordPath(section).split(":",2); if(useInstance){ parts =r.getServicesInstancesPath(section).split(":",2); } String[] rootel=parts[1].split(","); Element root=doc.addElement(new QName(rootel[1],new Namespace("ns2",rootel[0]))); Element element=root.addElement("displayName"); element.addText(in.getString("displayName")); Element element2=root.addElement("shortIdentifier"); element2.addText(in.getString("shortIdentifier")); if(in.has("vocabType")){ Element element3=root.addElement("vocabType"); element3.addText(in.getString("vocabType")); } return doc; //yes I know hardcode is bad - but I need this out of the door today } public static Document convertToXml(Record r,JSONObject in,String section, String permtype) throws JSONException, UnderlyingStorageException { Document doc=DocumentFactory.getInstance().createDocument(); String[] parts=r.getServicesRecordPath(section).split(":",2); String[] rootel=parts[1].split(","); Element root=doc.addElement(new QName(rootel[1],new Namespace("ns2",rootel[0]))); if(r.getAllServiceFields(permtype,section).length >0){ for(FieldSet f : r.getAllServiceFields(permtype,section)) { addFieldSetToXml(root,f,in,section,permtype); } //log.info(doc.asXML()); return doc; } return null; } private static String getDeUrned(Element el, Field f) throws JSONException{ if(f.hasAutocompleteInstance()){ String deurned = getDeURNedValue(f, el.getText()); return deurned; } return ""; } private static List getComplexNodes(Element root,String context,String condition,String value,String extract) { List out=new ArrayList(); for(Object n : root.selectNodes(context)) { if(!(n instanceof Element)) continue; Element candidate=(Element)n; boolean match = false; for(Object n2 : candidate.selectNodes(condition)) { if(!(n2 instanceof Element)) continue; if(value.equals(((Element)n2).getText())) match=true; } if(!match) continue; for(Object n3 : candidate.selectNodes(extract)) { if(!(n3 instanceof Element)) continue; out.add(n3); } } return out; } private static List getNodes(Element root,String spec) { if(spec!=null && spec.length()>0 && spec.charAt(0)==';') { String[] parts=spec.split(";"); return getComplexNodes(root,parts[1],parts[2],parts[3],parts[4]); } else return root.selectNodes(spec); } private static Element getFieldNodeEl(Element root,Field f){ List nodes=getNodes(root,f.getServicesTag()); if(nodes.size()==0) return null; // XXX just add first Element el=(Element)nodes.get(0); return el; } private static String csid_value(String csid,String spec,String ims_url) { String[] parts = spec.split(";"); if(parts.length<2) parts = new String[]{spec,""}; if(parts.length<3) parts = new String[]{null,parts[0],parts[1]}; String prefix1=""; String prefix2=""; if("ims".equals(parts[0]) && ims_url!=null) prefix1=ims_url; return prefix1+parts[1]+csid+parts[2]; } @SuppressWarnings("unchecked") private static void addFieldToJson(JSONObject out,Element root,Field f, String permlevel, JSONObject tempSon,String csid,String ims_url) throws JSONException { String use_csid=f.useCsid(); if(use_csid!=null) { if(f.useCsidField()!=null){ csid = tempSon.getString(f.useCsidField()); } out.put(f.getID(),csid_value(csid,f.useCsid(),ims_url)); } else { Element el=getFieldNodeEl(root,f); if(el == null){ return; } addExtraToJson(out, el, f, tempSon); if(f.getUIType().startsWith("groupfield")){ String parts[] = f.getUIType().split("/"); Record subitems = f.getRecord().getSpec().getRecordByServicesUrl(parts[1]); JSONObject temp = new JSONObject(); for(FieldSet fs : subitems.getAllServiceFields(permlevel,"common")) { addFieldSetToJson(temp,el,fs,permlevel, tempSon,csid,ims_url); } out.put(f.getID(),temp); } else{ out.put(f.getID(),el.getText()); } tempSon = addtemp(tempSon, f.getID(), el.getText()); } } // Fields that have an autocomplete tag, should also have a sibling with the // de-urned version of the urn to display nicely private static void addExtraToJson(JSONObject out, Element el, Field f, JSONObject tempSon) throws JSONException { String deurned = getDeUrned(el, f); if (deurned != "") { tempSon = addtemp(tempSon, f.getID(), deurned); out.put("de-urned-" + f.getID(), deurned); } } private static String getDeURNedValue(Field f, String urn) throws JSONException { //add a field with the de-urned version of the urn if(urn.isEmpty() || urn == null){ return ""; } //support multiassign of autocomplete instances for ( Instance ins : f.getAllAutocompleteInstances() ){ if(ins !=null){ // this authority hasn't been implemented yet RefName.AuthorityItem itemParsed = RefName.AuthorityItem.parse(urn); if(itemParsed!=null){ return itemParsed.displayName; } } } return ""; } private static void buildFieldList(List<String> list,FieldSet f, String permlevel) { if(f instanceof Repeat){ list.add(f.getID()); for(FieldSet a : ((Repeat)f).getChildren(permlevel)){ //if(a instanceof Repeat) // list.add(a.getID()); if(a instanceof Field){ list.add(a.getID()); } buildFieldList(list,a,permlevel); } } if(f instanceof Field){ list.add(f.getID()); } } /* Repeat syntax is challenging for dom4j */ private static List<Map<String, List <Element> >> extractRepeats(Element container,FieldSet f, String permlevel) { List<Map<String,List<Element>>> out=new ArrayList<Map<String,List<Element>>>(); // Build index so that we can see when we return to the start List<String> fields=new ArrayList<String>(); List<Element> repeatdatatypestuff = new ArrayList<Element>(); buildFieldList(fields,f,permlevel); Map<String,Integer> field_index=new HashMap<String,Integer>(); for(int i=0;i<fields.size();i++){ field_index.put(fields.get(i),i); } // Iterate through Map<String, List <Element> > member=null; int prev=Integer.MAX_VALUE; for(Object node : container.selectNodes("*")) { if(!(node instanceof Element)) continue; Integer next=field_index.get(((Element)node).getName()); if(next==null) continue; if(next<prev) { // Must be a new instance if(member!=null) out.add(member); member=new HashMap<String, List <Element> >(); repeatdatatypestuff = new ArrayList<Element>(); } prev=next; repeatdatatypestuff.add((Element)node); member.put(((Element)node).getName(),repeatdatatypestuff); } if(member!=null) out.add(member); return out; } private static List<String> FieldListFROMConfig(FieldSet f, String permlevel) { List<String> children = new ArrayList<String>(); if(f instanceof Repeat){ for(FieldSet a : ((Repeat)f).getChildren(permlevel)){ if(a instanceof Repeat && ((Repeat)a).hasServicesParent()){ children.add(((Repeat)a).getServicesParent()[0]); } else{ children.add(a.getID()); } } } if(f instanceof Group){ for(FieldSet a : ((Group)f).getChildren(permlevel)){ children.add(a.getID()); } } if(f instanceof Field){ } return children; } /* Repeat syntax is challenging for dom4j */ private static JSONArray extractRepeatData(Element container,FieldSet f, String permlevel) throws JSONException { List<Map<String,List<Element>>> out=new ArrayList<Map<String,List<Element>>>(); JSONArray newout = new JSONArray(); // Build index so that we can see when we return to the start List<String> fields = FieldListFROMConfig(f,permlevel); Map<String,Integer> field_index=new HashMap<String,Integer>(); for(int i=0;i<fields.size();i++){ field_index.put(fields.get(i),i); } JSONObject test = new JSONObject(); JSONArray testarray = new JSONArray(); // Iterate through Integer prev=Integer.MAX_VALUE; for(Object node : container.selectNodes("*")) { if(!(node instanceof Element)) continue; Integer next=field_index.get(((Element)node).getName()); if(next==null) continue; if(next!=prev) { // Must be a new instance if(test.length()>0){ newout.put(test); } test = new JSONObject(); testarray = new JSONArray(); } prev=next; testarray.put((Element)node); test.put(((Element)node).getName(), testarray); } if(test.length()>0){ newout.put(test); } return newout; } private static JSONObject addtemp(JSONObject temp, String id, Object text) throws JSONException{ if(!temp.has(id)){ temp.put(id,text); } return temp; } @SuppressWarnings("unchecked") private static JSONArray addRepeatedNodeToJson(Element container,Repeat f, String permlevel, JSONObject tempSon) throws JSONException { JSONArray node = new JSONArray(); JSONArray elementlist=extractRepeatData(container,f,permlevel); JSONObject siblingitem = new JSONObject(); for(int i=0;i<elementlist.length();i++){ JSONObject element = elementlist.getJSONObject(i); for(FieldSet fs : f.getChildren(permlevel)) { Iterator rit=element.keys(); while(rit.hasNext()) { String key=(String)rit.next(); JSONArray arrvalue = new JSONArray(); if(fs instanceof Repeat && ((Repeat)fs).hasServicesParent()){ if(!((Repeat)fs).getServicesParent()[0].equals(key)){ continue; } Object value = element.get(key); arrvalue = (JSONArray)value; } else{ if(!fs.getID().equals(key)){ continue; } Object value = element.get(key); arrvalue = (JSONArray)value; } if(fs instanceof Field) { for(int j=0;j<arrvalue.length();j++){ JSONObject repeatitem = new JSONObject(); //XXX remove when service layer supports primary tags if(f.hasPrimary() && j==0){ repeatitem.put("_primary",true); } Element child = (Element)arrvalue.get(j); if(f.asSibling()){ addExtraToJson(siblingitem,child, (Field)fs, tempSon); siblingitem.put(fs.getID(), child.getText()); } else{ addExtraToJson(repeatitem,child, (Field)fs, tempSon); repeatitem.put(fs.getID(), child.getText()); node.put(repeatitem); } tempSon = addtemp(tempSon, fs.getID(), child.getText()); } } else if(fs instanceof Repeat){ JSONObject tout = new JSONObject(); JSONObject tempSon2 = new JSONObject(); Repeat rp = (Repeat)fs; addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", "") ; if(f.asSibling()){ siblingitem.put(fs.getID(), tout.getJSONArray(rp.getID())); } else{ JSONObject repeatitem = new JSONObject(); repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID())); node.put(repeatitem); } tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID())); //log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString()); } } } } if(f.asSibling()){ node.put(siblingitem); } return node; } private static void addGroupToJson(JSONObject out, Element root, Group f,String permlevel, JSONObject tempSon) throws JSONException{ String nodeName = f.getServicesTag(); if(f.hasServicesParent()){ nodeName = f.getfullID(); //XXX hack because of weird repeats in accountroles permroles etc if(f.getServicesParent().length==0){ nodeName = f.getID(); } } List nodes=root.selectNodes(nodeName); if(nodes.size()==0) return; JSONArray node = new JSONArray(); // Only first element is important in group container int pos = 0; for(Object repeatcontainer : nodes){ pos++; Element container=(Element)repeatcontainer; JSONArray repeatitem = addRepeatedNodeToJson(container,f,permlevel,tempSon); JSONObject repeated = repeatitem.getJSONObject(0); out.put(f.getID(), repeated); } } @SuppressWarnings("unchecked") private static void addRepeatToJson(JSONObject out,Element root,Repeat f,String permlevel, JSONObject tempSon,String csid,String ims_url) throws JSONException { if(f.getXxxServicesNoRepeat()) { //not a repeat in services yet but is a repeat in UI FieldSet[] fields=f.getChildren(permlevel); if(fields.length==0) return; JSONArray members=new JSONArray(); JSONObject data=new JSONObject(); addFieldSetToJson(data,root,fields[0],permlevel, tempSon,csid,ims_url); members.put(data); out.put(f.getID(),members); return; } String nodeName = f.getServicesTag(); if(f.hasServicesParent()){ nodeName = f.getfullID(); //XXX hack because of weird repeats in accountroles permroles etc if(f.getServicesParent().length==0){ nodeName = f.getID(); } } List nodes=root.selectNodes(nodeName); if(nodes.size()==0) return; JSONArray node = new JSONArray(); // Only first element is important in container //except when we have repeating items int pos = 0; for(Object repeatcontainer : nodes){ pos++; Element container=(Element)repeatcontainer; if(f.asSibling()){ JSONArray repeatitem = addRepeatedNodeToJson(container,f,permlevel,tempSon); JSONArray temp = new JSONArray(); if(!out.has(f.getID())){ out.put(f.getID(), temp); } for(int arraysize=0 ;arraysize< repeatitem.length(); arraysize++){ JSONObject repeated = repeatitem.getJSONObject(arraysize); if(f.hasPrimary() && pos==1){ repeated.put("_primary",true); } out.getJSONArray(f.getID()).put(repeated); } } else{ JSONArray repeatitem = addRepeatedNodeToJson(container,f,permlevel,tempSon); out.put(f.getID(), repeatitem); } } } private static void addFieldSetToJson(JSONObject out,Element root,FieldSet fs,String permlevel, JSONObject tempSon,String csid,String ims_url) throws JSONException { if(fs instanceof Field) addFieldToJson(out,root,(Field)fs,permlevel, tempSon,csid,ims_url); else if(fs instanceof Group) addGroupToJson(out,root,(Group)fs,permlevel,tempSon); else if(fs instanceof Repeat) addRepeatToJson(out,root,(Repeat)fs,permlevel, tempSon,csid,ims_url); } public static void convertToJson(JSONObject out,Record r,Document doc, String permlevel, String section,String csid,String ims_url) throws JSONException { Element root=doc.getRootElement(); JSONObject tempSon = new JSONObject(); for(FieldSet f : r.getAllServiceFields(permlevel,section)) { addFieldSetToJson(out,root,f,permlevel, tempSon,csid,ims_url); } if(r.hasMergeData()){ for(FieldSet f : r.getAllMergedFields()){ for(String fm : f.getAllMerge()){ if (fm != null) { if (r.getPerm(fm, permlevel)) { if (tempSon.has(fm)) { String data = tempSon.getString(fm); if (data != null && !data.equals("") && !out.has(f.getID())) { out.put(f.getID(), data); } } } } } } } } public static JSONObject convertToJson(Record r,Document doc, String permlevel, String section,String csid,String ims_url) throws JSONException { JSONObject out=new JSONObject(); convertToJson(out,r,doc,permlevel,section,csid,ims_url); return out; } }
package org.talend.dataprep.api.service.command.dataset; import static org.talend.dataprep.api.service.command.common.Defaults.asString; import static org.talend.dataprep.api.service.command.common.Defaults.emptyString; import java.io.InputStream; import java.net.URISyntaxException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.InputStreamEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.talend.dataprep.api.service.PreparationAPI; import org.talend.dataprep.api.service.command.common.GenericCommand; import org.talend.dataprep.cache.ContentCache; import org.talend.dataprep.cache.ContentCacheKey; import org.talend.dataprep.exception.TDPException; import org.talend.dataprep.exception.error.APIErrorCodes; import org.talend.dataprep.exception.error.CommonErrorCodes; /** * Command in charge of mostly updating a dataset content. */ @Component @Scope("request") public class CreateOrUpdateDataSet extends GenericCommand<String> { /** The content cache. */ @Autowired private ContentCache contentCache; /** * Private constructor. * * @param client the http client. * @param id the dataset id. * @param name the dataset name. * @param dataSetContent the new dataset content. */ private CreateOrUpdateDataSet(HttpClient client, String id, String name, InputStream dataSetContent) { super(PreparationAPI.DATASET_GROUP, client); execute(() -> { try { URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl + "/datasets/" + id + "/raw/") .addParameter( "name", name ); final HttpPut put = new HttpPut(uriBuilder.build()); // $NON-NLS-1$ //$NON-NLS-2$ put.setEntity(new InputStreamEntity(dataSetContent)); return put; } catch (URISyntaxException e) { throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e); } }); onError(e -> new TDPException(APIErrorCodes.UNABLE_TO_CREATE_OR_UPDATE_DATASET, e)); on(HttpStatus.NO_CONTENT, HttpStatus.ACCEPTED).then(emptyString()); on(HttpStatus.OK).then((req, res) -> { contentCache.evict(new ContentCacheKey(id)); // clear the cache (dataset and all its preparations) return asString().apply(req, res); // Return response as String }); } }
package gow.fcm.pantallas; import gow.fcm.basedatos.ConexionSQLite; import gow.fcm.popups.PopupPizarraDigital; import gow.fcm.sentencias.SentenciasSQLitePrincipal; import android.net.Uri; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.Window; import android.widget.ImageView; import android.widget.TextView; import gow.fcm.footballcoachmanager.R; public class PaginaPrincipal extends Activity{ private ImageView fotoEntrenador; //Imagen o foto del entrenador @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); //No mostramos la barra de la cabecera con el nombre de la aplicacin setContentView(R.layout.pagina_principal); //PRUEBAS DE NUEVO //Se crea la base de datos si no existe o se actualiza si fuera necesario ConexionSQLite.getCrearSQLite(this); //Mtodo que muestra el nombre del entrenador mostrarDatosEntreneador(); //Mtodo que muestra el nombre del equipo mostrarNombreEquipo(); //Mtodo que muestra las diferentes secciones de la aplicacin seccionesBotones(); } //Mtodo que muestra private void mostrarDatosEntreneador(){ //Decalaramos los TextView TextView nombreEntrenador=(TextView) findViewById(R.id.nombre_entrenador); TextView apellidosEntrenador=(TextView) findViewById(R.id.apellidos_entrenador); //Ejecutamos las sentencias SentenciasSQLitePrincipal.getDatosEntrenador(this); String nombreEnt=SentenciasSQLitePrincipal.getNombreEntrenador(); String apellidosEnt=SentenciasSQLitePrincipal.getApellidosEntrenador(); //Mostramos el contenido if(nombreEnt==null){ nombreEntrenador.setText(R.string.coach_name); apellidosEntrenador.setText(R.string.coach_surname); }else{ //Agregamos el valor o contenido a los elementos nombreEntrenador.setText(nombreEnt); apellidosEntrenador.setText(apellidosEnt); SentenciasSQLitePrincipal.setNombreEntrenador(); //Reseta a null el valor SentenciasSQLitePrincipal.setApellidosEntrenador(); //Reseta a null el valor } getFotoEntrenador(); //Mtodo que hace la funcin de botn de opciones opcionesEntrenador(); } //Mtodo que obtiene y muestra la foto actual del entrenador private void getFotoEntrenador(){ //Decalaramos el ImageView fotoEntrenador=(ImageView) findViewById(R.id.foto_entrenador); //Registramos la imagen del entrenador como men contextual registerForContextMenu(fotoEntrenador); //Ejecutamos las sentencias SentenciasSQLitePrincipal.getDatosEntrenador(this); String fotoEnt=SentenciasSQLitePrincipal.getFotoEntrenador(); //Mostramos la foto del entrenador si la hay o no if(fotoEnt==null){ fotoEntrenador.setImageResource(R.drawable.no_coach_photo); }else{ //Agregamos el valor o contenido a los elementos fotoEntrenador.setImageURI(Uri.parse(fotoEnt)); SentenciasSQLitePrincipal.setFotoEntrenador(); //Reseta a null el valor } } //Mtodo que carga y muestra en pantalla en nombre del equipo @SuppressLint("CutPasteId") private void mostrarNombreEquipo(){ //Declaramos las variables de texto que muestra el nombre del equipo TextView nombreEquipo=(TextView) findViewById(R.id.nombre_equipo); TextView efectoShadow=(TextView) findViewById(R.id.efectoShadow); //Llamamos a los mtodos para obtener el nombre del equipo SentenciasSQLitePrincipal.getNombreEquipo(this); String nombre=SentenciasSQLitePrincipal.getNombreEquipo(); //Creamos la animacin del texto AlphaAnimation blinkanimation=new AlphaAnimation(1,0); //Visible->Invisible blinkanimation.setDuration(1000); //Tiempo en milisegundos blinkanimation.setInterpolator(new LinearInterpolator()); //Tansicin linear blinkanimation.setRepeatCount(Animation.INFINITE); //Repetir la animacin infinitamente blinkanimation.setRepeatMode(Animation.REVERSE); //Vuelve a empezar View nombresEquipos=findViewById(R.id.nombre_equipo); //Objeto view del texto nombresEquipos.setAnimation(blinkanimation); //Asignamos el efecto if(nombre==null){ nombreEquipo.setText(R.string.team_name); efectoShadow.setText(R.string.team_name); }else{ nombreEquipo.setText(nombre); efectoShadow.setText(nombre); SentenciasSQLitePrincipal.setNombreEquipo(); //Reseta a null el valor } } //Mtodo que realiza una acciones al hacer clic sobre las diferentes opciones del entrenador private void opcionesEntrenador(){ //Declaramos como variable la imagen final View configuracionEntrenador=findViewById(R.id.boton_entrenador); //Accin a realizar configuracionEntrenador.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View arg0, MotionEvent arg1){ switch(arg1.getAction()){ case MotionEvent.ACTION_DOWN: { datosEntrenador(); //Mtodo para modificar los datos del entrenador o entrenadores y su equipo o equipos break; } } return true; } }); } //Mtodo que abre la pantalla con los datos del entrenador y su equipo private void datosEntrenador(){ Intent i=new Intent(this,PaginaPrincipal.class); startActivity(i); } //Mtodo que muestra los botones en los cuales puedes navegar en la aplicacin private void seccionesBotones(){ //Declaramos la variables que harn de botones View botonEquipo=findViewById(R.id.boton_equipo); View botonPizarra=findViewById(R.id.boton_pizarra); View botonEvento=findViewById(R.id.boton_evento); View botonCalendario=findViewById(R.id.boton_calendario); //Declaramos la variables que harn la animacin al pulsar el botn final ImageView imgEquipo=(ImageView) findViewById(R.id.equipo); final ImageView imgPizarra=(ImageView) findViewById(R.id.pizarra); final ImageView imgEvento=(ImageView) findViewById(R.id.evento); final ImageView imgCalendario=(ImageView) findViewById(R.id.calendario); //Mtodo que realiza la animacin botonEquipo.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View arg0, MotionEvent arg1){ switch(arg1.getAction()){ case MotionEvent.ACTION_DOWN: { imgEquipo.setImageResource(R.drawable.team_management_down); botonAdministrarEquipo(); //Mtodo para ir a la seccin break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { imgEquipo.setImageResource(R.drawable.team_management_up); break; } } return true; } }); //Mtodo que realiza la animacin botonPizarra.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View arg0, MotionEvent arg1){ switch(arg1.getAction()){ case MotionEvent.ACTION_DOWN: { imgPizarra.setImageResource(R.drawable.digital_board_down); botonPizarraDigital(); //Mtodo para ir a la seccin break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { imgPizarra.setImageResource(R.drawable.digital_board_up); break; } } return true; } }); //Mtodo que realiza la animacin botonEvento.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View arg0, MotionEvent arg1){ switch(arg1.getAction()){ case MotionEvent.ACTION_DOWN: { imgEvento.setImageResource(R.drawable.event_management_down); botonEvento(); //Mtodo para ir a la seccin break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { imgEvento.setImageResource(R.drawable.event_management_up); break; } } return true; } }); //Mtodo que realiza la animacin botonCalendario.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View arg0, MotionEvent arg1){ switch(arg1.getAction()){ case MotionEvent.ACTION_DOWN: { imgCalendario.setImageResource(R.drawable.team_calendar_down); botonCalendario(); //Mtodo para ir a la seccin break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { imgCalendario.setImageResource(R.drawable.team_calendar_up); break; } } return true; } }); } //Mtodo para acceder a la administracin del equipo private void botonAdministrarEquipo(){ Intent i=new Intent(this,PaginaPrincipal.class); startActivity(i); } //Mtodo para acceder a la pizarra digital private void botonPizarraDigital(){ Intent i=new Intent(this,PopupPizarraDigital.class); startActivity(i); } //Mtodo para acceder a los eventos private void botonEvento(){ Intent i=new Intent(this,PaginaPrincipal.class); startActivity(i); } //Mtodo para acceder al calendario private void botonCalendario(){ Intent i=new Intent(this,PaginaCalendario.class); startActivity(i); } }
package uk.gov.nationalarchives.droid.command.action; import java.io.PrintWriter; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.io.FilenameUtils; import uk.gov.nationalarchives.droid.command.i18n.I18N; import uk.gov.nationalarchives.droid.report.interfaces.ReportManager; import uk.gov.nationalarchives.droid.report.interfaces.ReportSpec; /** * @author a-mpalmer * */ public class ListReportsCommand implements DroidCommand { /** * SINGLE QUOTE string to be used in messages. */ public static final String SINGLE_QUOTE = "'"; private PrintWriter printWriter; private ReportManager reportManager; /** * {@inheritDoc} */ @Override public void execute() throws CommandExecutionException { List<ReportSpec> reports = reportManager.listReportSpecs(); if (reports.isEmpty()) { printWriter.println(I18N.getResource(I18N.NO_REPORTS_DEFINED)); } else { StringBuilder builder = new StringBuilder(); for (ReportSpec report : reports) { String reportDescription = String.format("\nReport:\t'%s'\n\tFormats:\t", report.getName()); builder.append(reportDescription); List<String> outputFormats = getReportOutputFormats(report); if (outputFormats != null) { builder.append(outputFormats.stream().map(s -> SINGLE_QUOTE + s + SINGLE_QUOTE).collect(Collectors.joining("\t"))); } builder.append("\t'Pdf'\t'DROID Report XML'"); builder.append("\n"); } printWriter.println(builder.toString()); } } private List<String> getReportOutputFormats(ReportSpec report) { final List<String> outputFormats = new ArrayList<>(); final List<Path> xslFiles = report.getXslTransforms(); for (final Path xslFile : xslFiles) { final String baseName = FilenameUtils.getBaseName(xslFile.getFileName().toString()); final int stop = baseName.indexOf('.'); if (stop > -1) { final String description = baseName.substring(0, stop); outputFormats.add(description); } } return outputFormats; } /** * @param printWriter the printWriter to set */ public void setPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } /** * @param reportManager * the reportManager to set */ public void setReportManager(ReportManager reportManager) { this.reportManager = reportManager; } }
package hudson; import com.google.common.collect.Lists; import com.thoughtworks.xstream.XStream; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.Saveable; import hudson.model.listeners.SaveableListener; import hudson.util.FormValidation; import hudson.util.Scrambler; import hudson.util.Secret; import hudson.util.XStream2; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import jenkins.model.Jenkins; import jenkins.security.stapler.StaplerAccessibleType; import jenkins.util.JenkinsJVM; import jenkins.util.SystemProperties; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NTCredentials; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.jenkinsci.Symbol; import org.jvnet.robust_http_client.RetryableHttpStream; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.interceptor.RequirePOST; @StaplerAccessibleType public final class ProxyConfiguration extends AbstractDescribableImpl<ProxyConfiguration> implements Saveable, Serializable { /** * Holds a default TCP connect timeout set on all connections returned from this class, * note this is value is in milliseconds, it's passed directly to {@link URLConnection#setConnectTimeout(int)} */ private static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = SystemProperties.getInteger("hudson.ProxyConfiguration.DEFAULT_CONNECT_TIMEOUT_MILLIS", (int)TimeUnit.SECONDS.toMillis(20)); public final String name; public final int port; /** * Possibly null proxy user name. */ private final String userName; /** * List of host names that shouldn't use proxy, as typed by users. * * @see #getNoProxyHostPatterns() */ public final String noProxyHost; @Deprecated private String password; /** * encrypted password */ private Secret secretPassword; private String testUrl; private transient Authenticator authenticator; private transient boolean authCacheSeeded; public ProxyConfiguration(String name, int port) { this(name,port,null,null); } public ProxyConfiguration(String name, int port, String userName, String password) { this(name,port,userName,password,null); } public ProxyConfiguration(String name, int port, String userName, String password, String noProxyHost) { this(name,port,userName,password,noProxyHost,null); } @DataBoundConstructor public ProxyConfiguration(String name, int port, String userName, String password, String noProxyHost, String testUrl) { this.name = Util.fixEmptyAndTrim(name); this.port = port; this.userName = Util.fixEmptyAndTrim(userName); this.secretPassword = Secret.fromString(password); this.noProxyHost = Util.fixEmptyAndTrim(noProxyHost); this.testUrl = Util.fixEmptyAndTrim(testUrl); this.authenticator = newAuthenticator(); } private Authenticator newAuthenticator() { return new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { String userName = getUserName(); if (getRequestorType() == RequestorType.PROXY && userName != null) { return new PasswordAuthentication(userName, getPassword().toCharArray()); } return null; } }; } public String getUserName() { return userName; } // This method is public, if it was public only for jelly, then should make it private (or inline contents) // Have left public, as can't tell if anyone else is using from plugins /** * @return the password in plain text */ public String getPassword() { return Secret.toString(secretPassword); } public String getEncryptedPassword() { return (secretPassword == null) ? null : secretPassword.getEncryptedValue(); } public String getTestUrl() { return testUrl; } /** * Returns the list of properly formatted no proxy host names. */ public List<Pattern> getNoProxyHostPatterns() { return getNoProxyHostPatterns(noProxyHost); } /** * Returns the list of properly formatted no proxy host names. */ public static List<Pattern> getNoProxyHostPatterns(String noProxyHost) { if (noProxyHost==null) return Collections.emptyList(); List<Pattern> r = Lists.newArrayList(); for (String s : noProxyHost.split("[ \t\n,|]+")) { if (s.length()==0) continue; r.add(Pattern.compile(s.replace(".", "\\.").replace("*", ".*"))); } return r; } /** * @deprecated * Use {@link #createProxy(String)} */ @Deprecated public Proxy createProxy() { return createProxy(null); } public Proxy createProxy(String host) { return createProxy(host, name, port, noProxyHost); } public static Proxy createProxy(String host, String name, int port, String noProxyHost) { if (host!=null && noProxyHost!=null) { for (Pattern p : getNoProxyHostPatterns(noProxyHost)) { if (p.matcher(host).matches()) return Proxy.NO_PROXY; } } return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(name,port)); } public void save() throws IOException { if(BulkChange.contains(this)) return; XmlFile config = getXmlFile(); config.write(this); SaveableListener.fireOnChange(this, config); } private Object readResolve() { if (secretPassword == null) // backward compatibility : get scrambled password and store it encrypted secretPassword = Secret.fromString(Scrambler.descramble(password)); password = null; authenticator = newAuthenticator(); return this; } public static XmlFile getXmlFile() { return new XmlFile(XSTREAM, new File(Jenkins.get().getRootDir(), "proxy.xml")); } public static ProxyConfiguration load() throws IOException { XmlFile f = getXmlFile(); if(f.exists()) return (ProxyConfiguration) f.read(); else return null; } /** * This method should be used wherever {@link URL#openConnection()} to internet URLs is invoked directly. */ public static URLConnection open(URL url) throws IOException { final ProxyConfiguration p = get(); URLConnection con; if(p==null) { con = url.openConnection(); } else { Proxy proxy = p.createProxy(url.getHost()); con = url.openConnection(proxy); if(p.getUserName()!=null) { // Add an authenticator which provides the credentials for proxy authentication Authenticator.setDefault(p.authenticator); p.jenkins48775workaround(proxy, url); } } if(DEFAULT_CONNECT_TIMEOUT_MILLIS > 0) { con.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS); } if (JenkinsJVM.isJenkinsJVM()) { // this code may run on a slave decorate(con); } return con; } public static InputStream getInputStream(URL url) throws IOException { final ProxyConfiguration p = get(); if (p == null) return new RetryableHttpStream(url); Proxy proxy = p.createProxy(url.getHost()); InputStream is = new RetryableHttpStream(url, proxy); if (p.getUserName() != null) { // Add an authenticator which provides the credentials for proxy authentication Authenticator.setDefault(p.authenticator); p.jenkins48775workaround(proxy, url); } return is; } /** * If the first URL we try to access with a HTTP proxy is HTTPS then the authentication cache will not have been * pre-populated, so we try to access at least one HTTP URL before the very first HTTPS url. * @param proxy * @param url the actual URL being opened. */ private void jenkins48775workaround(Proxy proxy, URL url) { if ("https".equals(url.getProtocol()) && !authCacheSeeded && proxy != Proxy.NO_PROXY) { HttpURLConnection preAuth = null; try { // We do not care if there is anything at this URL, all we care is that it is using the proxy preAuth = (HttpURLConnection) new URL("http", url.getHost(), -1, "/").openConnection(proxy); preAuth.setRequestMethod("HEAD"); preAuth.connect(); } catch (IOException e) { // ignore, this is just a probe we don't care at all } finally { if (preAuth != null) { preAuth.disconnect(); } } authCacheSeeded = true; } else if ("https".equals(url.getProtocol())){ // if we access any http url using a proxy then the auth cache will have been seeded authCacheSeeded = authCacheSeeded || proxy != Proxy.NO_PROXY; } } @CheckForNull private static ProxyConfiguration get() { if (JenkinsJVM.isJenkinsJVM()) { return _get(); } return null; } @CheckForNull private static ProxyConfiguration _get() { JenkinsJVM.checkJenkinsJVM(); // this code could be called between the JVM flag being set and theInstance initialized Jenkins jenkins = Jenkins.get(); return jenkins == null ? null : jenkins.proxy; } private static void decorate(URLConnection con) throws IOException { for (URLConnectionDecorator d : URLConnectionDecorator.all()) d.decorate(con); } private static final XStream XSTREAM = new XStream2(); private static final long serialVersionUID = 1L; static { XSTREAM.alias("proxy", ProxyConfiguration.class); } @Extension @Symbol("proxy") public static class DescriptorImpl extends Descriptor<ProxyConfiguration> { @Override public String getDisplayName() { return "Proxy Configuration"; } public FormValidation doCheckPort(@QueryParameter String value) { value = Util.fixEmptyAndTrim(value); if (value == null) { return FormValidation.ok(); } int port; try { port = Integer.parseInt(value); } catch (NumberFormatException e) { return FormValidation.error(Messages.PluginManager_PortNotANumber()); } if (port < 0 || port > 65535) { return FormValidation.error(Messages.PluginManager_PortNotInRange(0, 65535)); } return FormValidation.ok(); } @RequirePOST public FormValidation doValidateProxy( @QueryParameter("testUrl") String testUrl, @QueryParameter("name") String name, @QueryParameter("port") int port, @QueryParameter("userName") String userName, @QueryParameter("password") String password, @QueryParameter("noProxyHost") String noProxyHost) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); if (Util.fixEmptyAndTrim(testUrl) == null) { return FormValidation.error(Messages.ProxyConfiguration_TestUrlRequired()); } String host; try { URL url = new URL(testUrl); host = url.getHost(); } catch (MalformedURLException e) { return FormValidation.error(Messages.ProxyConfiguration_MalformedTestUrl(testUrl)); } GetMethod method = null; try { method = new GetMethod(testUrl); method.getParams().setParameter("http.socket.timeout", DEFAULT_CONNECT_TIMEOUT_MILLIS > 0 ? DEFAULT_CONNECT_TIMEOUT_MILLIS : (int)TimeUnit.SECONDS.toMillis(30)); HttpClient client = new HttpClient(); if (Util.fixEmptyAndTrim(name) != null && !isNoProxyHost(host, noProxyHost)) { client.getHostConfiguration().setProxy(name, port); Credentials credentials = createCredentials(userName, password); AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); client.getState().setProxyCredentials(scope, credentials); } int code = client.executeMethod(method); if (code != HttpURLConnection.HTTP_OK) { return FormValidation.error(Messages.ProxyConfiguration_FailedToConnect(testUrl, code)); } } catch (IOException e) { return FormValidation.error(e, Messages.ProxyConfiguration_FailedToConnectViaProxy(testUrl)); } finally { if (method != null) { method.releaseConnection(); } } return FormValidation.ok(Messages.ProxyConfiguration_Success()); } private boolean isNoProxyHost(String host, String noProxyHost) { if (host!=null && noProxyHost!=null) { for (Pattern p : getNoProxyHostPatterns(noProxyHost)) { if (p.matcher(host).matches()) { return true; } } } return false; } private Credentials createCredentials(String userName, String password) { if (userName.indexOf('\\') >= 0){ final String domain = userName.substring(0, userName.indexOf('\\')); final String user = userName.substring(userName.indexOf('\\') + 1); return new NTCredentials(user, Secret.fromString(password).getPlainText(), "", domain); } else { return new UsernamePasswordCredentials(userName, Secret.fromString(password).getPlainText()); } } } }
package edu.oregonstate.cope.eclipse.listeners; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IExecutionListener; import org.eclipse.core.commands.NotHandledException; import org.eclipse.ui.IWorkbenchCommandConstants; public class CommandExecutionListener implements IExecutionListener { private static boolean saveInProgress = false; @Override public void preExecute(String commandId, ExecutionEvent event) { if (isFileSave(commandId)) saveInProgress = true; } private boolean isFileSave(String commandId) { return commandId.equals(IWorkbenchCommandConstants.FILE_SAVE) || commandId.equalsIgnoreCase(IWorkbenchCommandConstants.FILE_SAVE_ALL); } @Override public void postExecuteSuccess(String commandId, Object returnValue) { if (isFileSave(commandId)) saveInProgress = false; } @Override public void postExecuteFailure(String commandId, ExecutionException exception) { if (isFileSave(commandId)) saveInProgress = false; } @Override public void notHandled(String commandId, NotHandledException exception) { } public static boolean isSaveInProgress() { return saveInProgress; } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.anim; import java.util.Random; import pythagoras.f.XY; import playn.core.ImageLayer; import playn.core.Layer; import tripleplay.util.Interpolator; /** * Represents a single component of an animation. */ public abstract class Animation { /** Used by animations to update a target value. */ public interface Value { /** Returns the initial value. */ float initial (); /** Updates the value. */ void set (float value); } /** Used to cancel animations after they've been started. See {@link #handle}. */ public interface Handle { /** Cancels this animation. It will remove itself from its animator the next frame. * @return true if this animation was actually running and was canceled, false if it had * already completed. */ boolean cancel (); } /** Processes a {@link Flipbook}. */ public static class Flip extends Animation { public Flip (ImageLayer target, Flipbook book) { _target = target; _book = book; } @Override protected void init (float time) { super.init(time); setFrame(0); } protected float apply (float time) { float dt = time - _start; int newIdx = _curIdx; float[] frameEnds = _book.frameEnds; float remain = frameEnds[frameEnds.length-1] - dt; if (remain < 0) return remain; while (frameEnds[newIdx] < dt) newIdx++; if (newIdx != _curIdx) setFrame(newIdx); return remain; } protected void setFrame (int idx) { _book.frames.apply(_book.frameIndexes[idx], _target); _curIdx = idx; } protected final ImageLayer _target; protected final Flipbook _book; protected int _curIdx; } /** A base class for animations that interpolate values. */ public static abstract class Interped<R> extends Animation { /** Uses the supplied interpolator for this animation. */ public R using (Interpolator interp) { _interp = interp; @SuppressWarnings("unchecked") R tthis = (R)this; return tthis; } /** Uses a linear interpolator for this animation. */ public R linear () { return using(Interpolator.LINEAR); } /** Uses an ease-in interpolator for this animation. */ public R easeIn () { return using(Interpolator.EASE_IN); } /** Uses an ease-out interpolator for this animation. */ public R easeOut () { return using(Interpolator.EASE_OUT); } /** Uses an ease-inout interpolator for this animation. */ public R easeInOut () { return using(Interpolator.EASE_INOUT); } /** Configures the duration for this animation (in seconds). Default: 1. */ public R in (float duration) { _duration = duration; @SuppressWarnings("unchecked") R tthis = (R)this; return tthis; } protected Interpolator _interp = Interpolator.LINEAR; protected float _duration = 1; } /** Animates a single scalar value. */ public static class One extends Interped<One> { public One (Value target) { _target = target; } /** Configures the starting value. Default: the value of the scalar at the time that the * animation begins. */ public One from (float value) { _from = value; return this; } /** Configures the ending value. Default: 0. */ public One to (float value) { _to = value; return this; } @Override protected void init (float time) { super.init(time); if (_from == Float.MIN_VALUE) _from = _target.initial(); } @Override protected float apply (float time) { float dt = time-_start; _target.set((dt < _duration) ? _interp.apply(_from, _to-_from, dt, _duration) : _to); return _duration - dt; } @Override public String toString () { return getClass().getName() + " start:" + _start + " to " + _to; } protected final Value _target; protected float _from = Float.MIN_VALUE; protected float _to; } /** Animates a pair of scalar values (usually a position). */ public static class Two extends Interped<Two> { public Two (Value x, Value y) { _x = x; _y = y; } /** Configures the starting values. Default: the values of the scalar at the time that the * animation begins. */ public Two from (float fromx, float fromy) { _fromx = fromx; _fromy = fromy; return this; } /** Configures the starting values. Default: the values of the scalar at the time that the * animation begins. */ public Two from (XY pos) { return from(pos.x(), pos.y()); } /** Configures the ending values. Default: (0, 0). */ public Two to (float tox, float toy) { _tox = tox; _toy = toy; return this; } /** Configures the ending values. Default: (0, 0). */ public Two to (XY pos) { return to(pos.x(), pos.y()); } @Override protected void init (float time) { super.init(time); if (_fromx == Float.MIN_VALUE) _fromx = _x.initial(); if (_fromy == Float.MIN_VALUE) _fromy = _y.initial(); } @Override protected float apply (float time) { float dt = time-_start; if (dt < _duration) { _x.set(_interp.apply(_fromx, _tox-_fromx, dt, _duration)); _y.set(_interp.apply(_fromy, _toy-_fromy, dt, _duration)); } else { _x.set(_tox); _y.set(_toy); } return _duration - dt; } protected final Value _x, _y; protected float _fromx = Float.MIN_VALUE, _fromy = Float.MIN_VALUE; protected float _tox, _toy; } /** Delays a specified number of seconds. */ public static class Delay extends Animation { public Delay (float duration) { _duration = duration; } @Override protected float apply (float time) { return _start + _duration - time; } protected final float _duration; } /** Executes an action and completes immediately. */ public static class Action extends Animation { public Action (Runnable action) { _action = action; } @Override protected float apply (float time) { _action.run(); return _start - time; } protected Runnable _action; } /** Repeats its underlying animation over and over again (until removed). */ public static class Repeat extends Animation { public Repeat (Layer layer) { _layer = layer; } @Override public Animator then () { return new Animator() { @Override public <T extends Animation> T add (T anim) { anim._root = _root; // set ourselves as the repeat target of this added animation anim._next = Repeat.this; _next = anim; return anim; } }; } @Override protected float apply (float time) { return _start - time; // immediately move to our next animation } @Override protected Animation next () { // if our target layer is no longer active, we're done return (_layer.parent() == null) ? null : _next; } protected Layer _layer; } /** An animation that shakes a layer randomly in the x and y directions. */ public static class Shake extends Animation.Interped<Shake> { public Shake (Layer layer) { _layer = layer; } /** Configures the amount under and over the starting x and y allowed when shaking. The * animation will shake the layer in the range {@code x + underX} to {@code x + overX} and * similarly for y, thus {@code underX} (and {@code underY}) should be negative. */ public Shake bounds (float underX, float overX, float underY, float overY) { _underX = underX; _overX = overX; _underY = underY; _overY = overY; return this; } /** Configures the shake cycle time in the x and y directions. */ public Shake cycleTime (float millis) { return cycleTime(millis, millis); } /** Configures the shake cycle time in the x and y directions. */ public Shake cycleTime (float millisX, float millisY) { _cycleTimeX = millisX; _cycleTimeY = millisY; return this; } @Override protected void init (float time) { super.init(time); _startX = _layer.tx(); _startY = _layer.ty(); // start our X/Y shaking randomly in one direction or the other _curMinX = _startX; if (_overX == 0) _curRangeX = _underX; else if (_underX == 0) _curRangeX = _overX; else _curRangeX = RANDS.nextBoolean() ? _overX : _underX; _curMinY = _startY; if (_overY == 0) _curRangeY = _underY; else if (_underY == 0) _curRangeY = _overY; else _curRangeY = RANDS.nextBoolean() ? _overY : _underY; } @Override protected float apply (float time) { float dt = time-_start, nx, ny; if (dt < _duration) { float dtx = time-_timeX, dty = time-_timeY; if (dtx < _cycleTimeX) nx = _interp.apply(_curMinX, _curRangeX, dtx, _cycleTimeX); else { nx = _curMinX + _curRangeX; _curMinX = nx; float rangeX = _startX + (_curRangeX < 0 ? _overX : _underX) - nx; _curRangeX = rangeX/2 + RANDS.nextFloat() * rangeX/2; _timeX = time; } if (dty < _cycleTimeY) ny = _interp.apply(_curMinY, _curRangeY, dty, _cycleTimeY); else { ny = _curMinY + _curRangeY; _curMinY = ny; float rangeY = _startY + (_curRangeY < 0 ? _overY : _underY) - ny; _curRangeY = rangeY/2 + RANDS.nextFloat() * rangeY/2; _timeY = time; } } else { nx = _startX; ny = _startY; } _layer.setTranslation(nx, ny); return _duration - dt; } protected final Layer _layer; // parameters initialized by setters or in init() protected float _underX = -2, _overX = 2, _underY = -2, _overY = 2; protected float _cycleTimeX = 100, _cycleTimeY = 100; protected float _startX, _startY; // parameters used during animation protected float _timeX, _timeY; protected float _curMinX, _curRangeX, _curMinY, _curRangeY; } /** * Returns an animation factory for constructing an animation that will be queued up for * execution when the current animation is completes. */ public Animator then () { return new Animator() { @Override public <T extends Animation> T add (T anim) { // our _next is either null, or it points to the animation to which we should // repeat when we reach the end of this chain; so pass the null or the repeat // target down to our new next animation anim._root = _root; anim._next = _next; _next = anim; return anim; } }; } /** * Returns a handle on this collection of animations which can be used to cancel the animation. * This handle references the root animation in this chain of animations, and will cancel all * (as yet uncompleted) animations in the chain. */ public Handle handle () { return new Handle() { @Override public boolean cancel () { return _root.cancel(); } }; } protected Animation () { } protected void init (float time) { _start = time; } protected float apply (Animator animator, float time) { // if we're cancelled, abandon ship now if (_current == null) return 0; // if the current animation has completed, move the next one in our chain float remain = _current.apply(time); if (remain > 0) return remain; while (remain <= 0) { // if we've been canceled, return 0 to indicate that we're done if (_current == null) return 0; // if we have no next animation, return our overflow _current = _current.next(); if (_current == null) return remain; // otherwise init and apply our next animation (accounting for overflow) _current.init(time+remain); remain = _current.apply(time); } return remain; } protected boolean cancel () { if (_current == null) return false; _current = null; return true; } protected abstract float apply (float time); protected Animation next () { return _next; } @Override public String toString () { return getClass().getName() + " start:" + _start; } protected float _start; protected Animation _root = this; protected Animation _current = this; protected Animation _next; protected static final Random RANDS = new Random(); }
package de.lmu.ifi.dbs.elki.algorithm.timeseries; import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm; import de.lmu.ifi.dbs.elki.data.DoubleVector; import de.lmu.ifi.dbs.elki.data.LabelList; import de.lmu.ifi.dbs.elki.data.type.TypeInformation; import de.lmu.ifi.dbs.elki.data.type.TypeUtil; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.ids.DBIDIter; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.math.Mean; import de.lmu.ifi.dbs.elki.math.linearalgebra.VMath; import de.lmu.ifi.dbs.elki.result.ChangePointDetectionResult; import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.CommonConstraints; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import java.util.*; public class OfflineChangePointDetectionAlgorithm extends AbstractAlgorithm<ChangePointDetectionResult> { private int confidence, bootstrapSteps; public OfflineChangePointDetectionAlgorithm(int confidence, int bootstrapSteps) { this.confidence = confidence; this.bootstrapSteps = bootstrapSteps; } public ChangePointDetectionResult run(Database database, Relation<DoubleVector> relation, Relation<LabelList> labellist) { List<ChangePoints> result = new ArrayList<>(); for(DBIDIter realtion_iter = relation.getDBIDs().iter(); realtion_iter.valid(); realtion_iter.advance()) { result.add(new ChangePoints( multipleChangepointsWithConfidence(relation.get(realtion_iter).getValues(), confidence, bootstrapSteps))); } return new ChangePointDetectionResult("Change Point List", "changepoints", result, labellist); } private double[] likelihoodRatioChangeInMean(double[] values){ double[] result = new double[values.length]; // vector containing means for all different vector lengths, last index contains mean over all elements double[] meansLeft = new double[values.length]; Mean currentMeanLeft = new Mean(); for(int i = 0; i < meansLeft.length; i++){ currentMeanLeft.put(values[i]); meansLeft[i] = currentMeanLeft.getMean(); } // first index contains mean over all elements coming from the other side double[] meansRight = new double[values.length]; Mean currentMeanRight = new Mean(); for(int i = meansRight.length-1; i >= 0; i currentMeanRight.put(values[i]); meansRight[i] = currentMeanRight.getMean(); } result[0] = -(VMath.sumElements(VMath.square(VMath.minus(values, meansRight[0])))); for(int i = 1; i < values.length; i++){ result[i] = -( (VMath.squareSum(VMath.minus(Arrays.copyOfRange(values, 0, i), meansLeft[i-1]))) + (VMath.squareSum(VMath.minus(Arrays.copyOfRange(values, i, values.length), meansRight[i]))) ); } return result; } // DOES NOT WORK - REASON NOT YET INVESTIGATED private double[] likelihoodRatioChangeInMeanOptimised(double[] values){ double[] result = new double[values.length]; // vector containing means for all different vector lengths, last index contains mean over all elements double[] meansLeft = new double[values.length]; Mean currentMeanLeft = new Mean(); for(int i = 0; i < meansLeft.length; i++){ currentMeanLeft.put(values[i]); meansLeft[i] = currentMeanLeft.getMean(); } // first index contains mean over all elements coming from the other side double[] meansRight = new double[values.length]; Mean currentMeanRight = new Mean(); for(int i = meansRight.length-1; i >= 0; i currentMeanRight.put(values[i]); meansRight[i] = currentMeanRight.getMean(); } result[0]=0; double tmpMeanDif; for(int i = 1; i < values.length; i++) { tmpMeanDif = meansLeft[i-1] - meansRight[i]; result[i]= -i*(values.length - i)*tmpMeanDif*tmpMeanDif; } return result; } private List<ChangePoint> multipleChangepointsWithConfidence(double[] values, int confidence, int bootstrapSteps){ List<ChangePoint> result = new ArrayList<>(); result = multipleChangepointsWithConfidence(result, values, confidence, bootstrapSteps, 0); return result; } private List<ChangePoint> multipleChangepointsWithConfidence(List<ChangePoint> result, double[] values, int confidence, int bootstrapSteps, int tmpArraryStartIndex){ double tmpConf = confidenceLevel(values, bootstrapSteps); int tmpMaxPos = tmpArraryStartIndex + getMaximumIndex(likelihoodRatioChangeInMean(values)); // return the detected changepoint if(!(tmpConf < confidence || values.length <=3 || (tmpMaxPos - tmpArraryStartIndex + 1 == values.length))){ // cannot split up arrays of size 3, that would make every element a change poin multipleChangepointsWithConfidence(result , Arrays.copyOfRange(values, 0, tmpMaxPos - tmpArraryStartIndex) , confidence , bootstrapSteps , tmpArraryStartIndex); multipleChangepointsWithConfidence(result , Arrays.copyOfRange(values, tmpMaxPos - tmpArraryStartIndex + 1, values.length) , confidence , bootstrapSteps , tmpMaxPos); result.add(new ChangePoint(tmpMaxPos, tmpConf)); } return result; } //TRY OUT RESULT HANDLING private ChangePoint singleChangepointWithConfidence(double[] values, int bootstrapSteps){ double conf = confidenceLevel(values, bootstrapSteps); double index = getMaximumIndex(likelihoodRatioChangeInMean(values)); return new ChangePoint(index, conf); } private double confidenceLevel(double[] values, int steps){ double estimator = getBootstrapEstimator(likelihoodRatioChangeInMean(values)); int x = 0; for(int i=0; i < steps; i++){ double[] tmpValues = shuffleVector(values); double tmpEstimator = getBootstrapEstimator(likelihoodRatioChangeInMean(tmpValues)); if (tmpEstimator < estimator){ x += 1; } } return 100 * ((double)x/(double)steps); } private double getBootstrapEstimator(double[] values){ return getMaximum(values)- getMinimum(values); } // move to VMath?? private double[] shuffleVector(double[] values) { double[] result= VMath.copy(values); Random rnd = new Random(); for (int i = result.length - 1; i > 0; i { int index = rnd.nextInt(i + 1); double tmp = result[index]; result[index] = result[i]; result[i] = tmp; } return result; } // move to VMath?? private int getMaximumIndex(double[] values){ int result = 0; for (int i = 0; i < values.length; i++){ if ((values[i] >= values[result])){ result = i; } } return result; } // move to VMath?? private double getMaximum(double[] values){ double result = values[0]; for(double value : values){ if(value > result){ result = value; } } return result; } // move to VMath?? private double getMinimum(double[] values){ double result = values[0]; for(double value : values){ if(value < result){ result = value; } } return result; } @Override public TypeInformation[] getInputTypeRestriction() { return TypeUtil.array(TypeUtil.NUMBER_VECTOR_VARIABLE_LENGTH, TypeUtil.LABELLIST); } @Override protected Logging getLogger() { return null; } public static class Parameterizer extends AbstractParameterizer { public static final OptionID CONFIDENCE_ID = new OptionID("changepointdetection.confidence", "Confidence level for terminating"); public static final OptionID BOOTSTRAP_ID = new OptionID("changepointdetection.bootstrapsteps", "Steps for bootstrapping"); private int confidence, bootstrap_steps; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); IntParameter confidence_parameter = new IntParameter(CONFIDENCE_ID) .addConstraint(CommonConstraints.GREATER_EQUAL_ONE_INT); if(config.grab(confidence_parameter)) { confidence = confidence_parameter.getValue(); } IntParameter bootstrap_steps_parameter = new IntParameter(BOOTSTRAP_ID) .addConstraint(CommonConstraints.GREATER_EQUAL_ONE_INT); if(config.grab(bootstrap_steps_parameter)) { bootstrap_steps = bootstrap_steps_parameter.getValue(); } } @Override protected OfflineChangePointDetectionAlgorithm makeInstance() { return new OfflineChangePointDetectionAlgorithm(confidence, bootstrap_steps); } } }
package org.jasig.portal; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import java.util.HashSet; import java.util.Random; import java.util.Set; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jasig.portal.channels.portlet.CPortletAdapter; import org.jasig.portal.container.services.information.PortletStateManager; import org.jasig.portal.jndi.JNDIManager; import org.jasig.portal.properties.PropertiesManager; import org.jasig.portal.utils.ResourceLoader; /** * This is an entry point into the uPortal. * @author Peter Kharchenko <pkharchenko@interactivebusiness.com> * @version $Revision$ */ public class PortalSessionManager extends HttpServlet { private static final Log log = LogFactory.getLog(PortalSessionManager.class); public static final String INTERNAL_TAG_VALUE=Long.toHexString((new Random()).nextLong()); public static final String IDEMPOTENT_URL_TAG="idempotent"; private static boolean initialized = false; private static ServletContext servletContext = null; private static PortalSessionManager instance = null; private static boolean fatalError = false; public static final ErrorID initPortalContext = new ErrorID("config","JNDI","Cannot initialize JNDI context"); /** * Provides access to the servlet instance ultimately to provide access * to the servlet context of the portal. * @return instance, the PortalSessionManager servlet instance */ public static final PortalSessionManager getInstance() { return instance; } // Following flag allows to disable features that prevent // repeated requests from going through. This is useful // when debugging and typing things in on a command line. // Otherwise, the flag should be set to false. private static final boolean ALLOW_REPEATED_REQUESTS = getAllowRepeatedRequestsValue(); // random number generator private static final Random randomGenerator = new Random(); private static boolean getAllowRepeatedRequestsValue() { try { return PropertiesManager.getPropertyAsBoolean("org.jasig.portal.PortalSessionManager.allow_repeated_requests"); } catch ( RuntimeException re ) { return false; } } static { log.info( "uPortal started"); } /** * Initialize the PortalSessionManager servlet * @throws ServletException */ public void init() throws ServletException { if(!initialized) { instance = this; // Retrieve the servlet configuration object from the servlet container // and make sure it's available ServletConfig sc = getServletConfig(); if (sc == null) { throw new ServletException("PortalSessionManager.init(): ServletConfig object was returned as null"); } // Supply PortletContainer with ServletConfig CPortletAdapter.setServletConfig(sc); servletContext = sc.getServletContext(); try { JNDIManager.initializePortalContext(); } catch (Exception pe) { ExceptionHelper.genericTopHandler(initPortalContext,pe); fatalError=true; } // Turn off URL caching if it has been requested if (!PropertiesManager.getPropertyAsBoolean("org.jasig.portal.PortalSessionManager.url_caching")) { // strangely, we have to instantiate a URLConnection to turn off caching, so we'll get something we know is there try { URL url = ResourceLoader.getResourceAsURL(PortalSessionManager.class, "/properties/portal.properties"); URLConnection conn = url.openConnection(); conn.setDefaultUseCaches(false); } catch (Exception e) { log.warn("PortalSessionManager.init(): Caught Exception trying to disable URL Caching", e); } } // Log orderly shutdown time Runtime.getRuntime().addShutdownHook(new Thread("uPortal shutdown hook") { public void run() { log.info( "uPortal stopped"); } }); // Flag that the portal has been initialized initialized = true; // Get the SAX implementation if (System.getProperty("org.xml.sax.driver") == null) { System.setProperty("org.xml.sax.driver", PropertiesManager.getProperty("org.xml.sax.driver")); } } } /** * Process HTTP POST request * * @param req an incoming <code>HttpServletRequest</code> value * @param res an outgoing <code>HttpServletResponse</code> value */ public void doPost(HttpServletRequest req, HttpServletResponse res) { doGet(req, res); } /** * Process HTTP GET request. * * @param req an incoming <code>HttpServletRequest</code> * @param res an outgoing <code>HttpServletResponse</code> */ public void doGet(HttpServletRequest req, HttpServletResponse res) { // Send the uPortal version in a header res.setHeader("uPortal-version", Version.getProduct() + "_" + Version.getReleaseTag()); if (fatalError) { try { res.sendRedirect("error/fatal.htm"); } catch (IOException e) { ExceptionHelper.genericTopHandler(Errors.bug,e); } return; } // Call to setCharacterEncoding method should be done before any call to req.getParameter() method. try { req.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException uee) { log.error("Unable to set UTF-8 character encoding!", uee); } HttpSession session = req.getSession(false); if (session != null) { Set requestTags=null; boolean request_verified=false; if(!ALLOW_REPEATED_REQUESTS) { // obtain a tag table synchronized(session) { requestTags=(Set)session.getAttribute("uP_requestTags"); if(requestTags==null) { requestTags=Collections.synchronizedSet(new HashSet()); session.setAttribute("uP_requestTags",requestTags); } } // determine current tag UPFileSpec upfs=new UPFileSpec(req); String tag=upfs.getTagId(); // see if the tag was registered if ( tag != null ) { request_verified = true; requestTags.remove(tag); } log.debug("PortalSessionManager::doGet() : request verified: "+request_verified); } try { UserInstance userInstance = null; try { // Retrieve the user's UserInstance object userInstance = UserInstanceManager.getUserInstance(req); } catch(Exception e) { ExceptionHelper.genericTopHandler(Errors.bug,e); ExceptionHelper.generateErrorPage(res,e); return; } // fire away if(ALLOW_REPEATED_REQUESTS) { userInstance.writeContent(new RequestParamWrapper(req,true),res); } else { // generate and register a new tag String newTag=Long.toHexString(randomGenerator.nextLong()); log.debug("PortalSessionManager::doGet() : generated new tag \""+newTag+"\" for the session "+session.getId()); // no need to check for duplicates :) we'd have to wait a lifetime of a universe for this time happen if(!requestTags.add(newTag)) { log.error("PortalSessionManager::doGet() : a duplicate tag has been generated ! Time's up !"); } RequestParamWrapper wrappedRequest = new RequestParamWrapper(req,request_verified); wrappedRequest.getParameterMap().putAll(PortletStateManager.getURLDecodedParameters(wrappedRequest)); userInstance.writeContent(wrappedRequest, new ResponseSubstitutionWrapper(res,INTERNAL_TAG_VALUE,newTag)); } } catch (Exception e) { ExceptionHelper.genericTopHandler(Errors.bug,e); ExceptionHelper.generateErrorPage(res,e); return; } } else { try { //throw new ServletException("Session object is null !"); res.sendRedirect(req.getContextPath() + "/Login" ); } catch (Exception e) { ExceptionHelper.genericTopHandler(Errors.bug,e); ExceptionHelper.generateErrorPage(res,e); return; } } } /** * Gets a URL associated with the named resource. * Call this to access files with paths relative to the * document root. Paths should begin with a "/". * @param resource relative to the document root * @return a URL associated with the named resource or null if the URL isn't accessible */ public static URL getResourceAsURL(String resource) { //Make sure resource string starts with a "/" if (!resource.startsWith("/")) resource = "/" + resource; URL url = null; try { url = servletContext.getResource(resource); } catch (java.net.MalformedURLException murle) { // if the URL is bad, just return null } return url; } /** * Gets an input stream associated with the named resource. * Call this to access files with paths relative to the * document root. Paths should begin with a "/". * @param resource relative to the document root * @return an input stream assosiated with the named resource */ public static java.io.InputStream getResourceAsStream(String resource) { //Make sure resource string starts with a "/" if (!resource.startsWith("/")) resource = "/" + resource; return servletContext.getResourceAsStream(resource); } }
package org.eclipse.birt.report.engine.api.impl; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import org.eclipse.birt.core.data.DataType; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.IResultMetaData; public class ResultMetaData implements IResultMetaData { protected IResultMetaData parentMetaData; protected String[] selectedColumns; public ResultMetaData( IBaseQueryDefinition query, String[] selectedColumns ) { initializeMetaData( query ); this.selectedColumns = selectedColumns; } public ResultMetaData( IBaseQueryDefinition query ) { initializeMetaData( query ); this.selectedColumns = null; } public ResultMetaData( IResultMetaData parentMetaData, String[] selectedColumns ) { this.parentMetaData = parentMetaData; this.selectedColumns = selectedColumns; } protected void initializeMetaData( IBaseQueryDefinition query ) { appendMetaData( query ); } private ArrayList metaEntries = new ArrayList( ); private class MetaDataEntry { String name; String displayName; int type; MetaDataEntry( String name, String displayName, int type ) { this.name = name; this.displayName = displayName; this.type = type; } } protected void appendMetaData( IBaseQueryDefinition query ) { Map bindings = query.getBindings( ); Iterator iter = bindings.entrySet( ).iterator( ); while ( iter.hasNext( ) ) { Map.Entry entry = (Map.Entry) iter.next( ); String name = (String) entry.getKey( ); IBinding binding = (IBinding) entry.getValue( ); try { metaEntries.add( new MetaDataEntry( name, binding .getDisplayName( ), binding.getDataType( ) ) ); } catch ( DataException ex ) { // FIXME: process exception. } } } public int getColumnCount( ) { if ( selectedColumns != null ) { return selectedColumns.length; } if( null != parentMetaData ) { return parentMetaData.getColumnCount( ); } return metaEntries.size( ); } public String getColumnName( int index ) throws BirtException { index = getColumnIndex( index ); if( null != parentMetaData ) { return parentMetaData.getColumnName( index ); } else { MetaDataEntry entry = (MetaDataEntry) metaEntries.get( index ); return entry.name; } } public String getColumnAlias( int index ) throws BirtException { return getColumnName( index ); } public int getColumnType( int index ) throws BirtException { index = getColumnIndex( index ); if( null != parentMetaData ) { return parentMetaData.getColumnType( index ); } else { MetaDataEntry entry = (MetaDataEntry) metaEntries.get( index ); return entry.type; } } public String getColumnTypeName( int index ) throws BirtException { int type = getColumnType( index ); return DataType.getName( type ); } public String getColumnLabel( int index ) throws BirtException { index = getColumnIndex( index ); if( null != parentMetaData ) { return parentMetaData.getColumnLabel( index ); } else { MetaDataEntry entry = (MetaDataEntry) metaEntries.get( index ); return entry.displayName; } } private int getColumnIndex( int index ) throws BirtException { if ( selectedColumns == null ) { return index; } String name = selectedColumns[index]; if( null != parentMetaData ) { for ( int i = 0; i < parentMetaData.getColumnCount( ); i++ ) { String columnName = parentMetaData.getColumnName( i ); if ( columnName.equals( name ) ) { return i; } } } else { for ( int i = 0; i < metaEntries.size( ); i++ ) { MetaDataEntry entry = (MetaDataEntry) metaEntries.get( i ); if ( entry.name.equals( name ) ) { return i; } } } throw new EngineException( "Invalid Column Index" ); } }
package org.eclipse.birt.report.engine.layout.html; import org.eclipse.birt.report.engine.content.IBandContent; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.ITableContent; import org.eclipse.birt.report.engine.emitter.IContentEmitter; import org.eclipse.birt.report.engine.executor.IReportItemExecutor; public class HTMLTableLM extends HTMLBlockStackingLM { /** * emitter used to layout the table */ protected HTMLTableLayoutNoNestEmitter tableEmitter; public HTMLTableLM( HTMLLayoutManagerFactory factory ) { super( factory ); } public int getType( ) { return LAYOUT_MANAGER_TABLE; } boolean isFirstLayout = true; public void initialize( HTMLAbstractLM parent, IContent content, IReportItemExecutor executor, IContentEmitter emitter ) { tableEmitter = new HTMLTableLayoutNoNestEmitter( emitter ); super.initialize( parent, content, executor, tableEmitter ); isFirstLayout = true; } protected void repeatHeader( ) { if ( !isFirstLayout ) { ITableContent table = (ITableContent) content; if ( table.isHeaderRepeat( ) ) { IBandContent header = table.getHeader( ); if ( header != null ) { boolean pageBreak = context.allowPageBreak( ); boolean skipPageHint = context.getSkipPageHint( ); context.setAllowPageBreak( pageBreak ); context.setSkipPageHint( true ); engine.layout(this, header, emitter ); context.setAllowPageBreak( pageBreak ); context.setSkipPageHint( skipPageHint ); } } } isFirstLayout = false; } protected boolean layoutChildren( ) { repeatHeader( ); boolean hasNext = super.layoutChildren( ); if ( !isOutput ) { startContent( ); } tableEmitter.resolveAll( ); tableEmitter.flush( ); return hasNext; } public void updateDropCells( int groupLevel, boolean dropAll ) { tableEmitter.resolveCellsOfDrop( groupLevel, dropAll ); } }
package org.openrdf.query.algebra.evaluation.function.spatial; import java.util.ArrayList; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.algebra.evaluation.util.JTSWrapper; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryCollection; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.LinearRing; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPoint; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.geom.impl.CoordinateArraySequence; import com.vividsolutions.jts.io.ParseException; /** * A {@link StrabonPolyhedron} is a @{link Value} that is used to represent geometries. * Therefore, a {@link StrabonPolyhedron} wraps around the construct of an RDF @{link Value} * the notion of geometry. This geometry can be expressed in different kinds of * representations, such as linear constraints over the reals with addition * (Semi-linear point sets), Well-Known Text (WKT), or Geography Markup Language (GML). * * The former kind of representation, i.e., Semi-linear point sets, was the first * representation to be supported by StrabonPolyhedron and now has been deprecated and * not supported any more. It can be enabled by setting the value for variable * {@link #EnableConstraintRepresentation} to <tt>true</tt>. However, this is hardly * suggested and it is discouraged. * * The other two kinds of representation is WKT and GML which are representations * standardized by the Open Geospatial Consortium (OGC). Both representations can be * used to represent a geometry and they are enabled by default. * * {@link StrabonPolyhedron} does not store a specific representation for a geometry. In * contrast, it stores the plain geometry as a byte array using a {@link Geometry} object. * However, {@link StrabonPolyhedron} offers constructors and methods for getting a * {@link StrabonPolyhedron} instance through any kind of representation and of course * getting a {@link StrabonPolyhedron} instance in a specific representation. * * @author Manos Karpathiotakis <mk@di.uoa.gr> * @author Kostis Kyzirakos <kk@di.uoa.gr> * */ public class StrabonPolyhedron implements Value { private static final long serialVersionUID = 894529468109904724L; public static String CACHEPATH = ""; public static String TABLE_COUNTS = "counts.bin"; public static String TABLE_SUBJ_OBJ_TYPES = "tableProperties.bin"; public static String TABLE_SHIFTING = "groupbys.bin"; public static final boolean EnableConstraintRepresentation = false; private static int MAX_POINTS = Integer.MAX_VALUE;//40000;//Integer.MAX_VALUE;//10000; /** * Get the Java Topology Suite wrapper instance. */ private static JTSWrapper jts = JTSWrapper.getInstance(); /** * The underlying geometry */ private Geometry geometry; /** * Creates a {@link StrabonPolyhedron} instance with an empty geometry. */ public StrabonPolyhedron() { this.geometry = null; } /** * Creates a {@link StrabonPolyhedron} instance with the given geometry. * * @param geo * @throws Exception */ public StrabonPolyhedron(Geometry geo) throws Exception { this.geometry = new StrabonPolyhedron(geo, 1).geometry; this.geometry.setSRID(geo.getSRID()); } /** * Creates a {@link StrabonPolyhedron} instance with a geometry given * in the representation of the argument. The representation could be * either in WKT or in GML. * * @param representation * @throws Exception */ public StrabonPolyhedron(String representation) { try { // try first as WKT geometry = jts.WKTread(representation); } catch (ParseException e) { try { // try as GML geometry = jts.GMLread(representation); } catch (Exception e1) { throw new IllegalArgumentException(e1); } } } /** * Creates a {@link StrabonPolyhedron} instance with a geometry represented * by the given byte array. * * @param byteArray * @throws ParseException */ public StrabonPolyhedron(byte[] byteArray) throws ParseException { this.geometry = jts.WKBread(byteArray); } /** * Creates a {@link StrabonPolyhedron} instance with a geometry represented * by the given byte array and sets the SRID of the geometry to the given one. * * @param byteArray * @param srid * @throws ParseException */ public StrabonPolyhedron(byte[] byteArray, int srid) throws ParseException { this(byteArray); this.geometry.setSRID(srid); } /** * Returns the string representation of the geometry of this * {@link StrabonPolyhedron} instance. The result of this method * is the same to the one of method {@link #toWKT()}. */ public String stringValue() { return toWKT(); } @Override public boolean equals(Object other) { if (this == other) { return true; } if(other instanceof StrabonPolyhedron) { if (((StrabonPolyhedron) other).geometry.equals(this.getGeometry())) { return true; } } return false; } @Deprecated public StrabonPolyhedron(String WKT, int algorithm) throws Exception { if(WKT.contains("gml")) { Geometry geo = jts.GMLread(WKT); this.geometry = new StrabonPolyhedron(geo).geometry; } else { Geometry geo = jts.WKTread(WKT); this.geometry = new StrabonPolyhedron(geo, algorithm).geometry; } } @Deprecated public StrabonPolyhedron(Geometry geo, int algorithm) throws Exception { this.geometry = new StrabonPolyhedron(geo, algorithm, MAX_POINTS).geometry; } @SuppressWarnings("unused") public StrabonPolyhedron(Geometry geo, int algorithm, int maxPoints) throws Exception { if (geo.isEmpty()) { this.geometry = geo; return; } if (!EnableConstraintRepresentation) { this.geometry = geo; return; } //always returns true... //if (!geo.isSimple()) // throw new Exception("The polygon is not simple. Only simple polygons are supported."); if (Point.class.isInstance(geo)) { this.geometry = geo; } else if (LineString.class.isInstance(geo)) { this.geometry = geo; } else if (Polygon.class.isInstance(geo)) { //if (!geo.isValid()) { // System.out.println("Non valid " + FindGeoType(geo) + " found. ("+ geo.toString() +")"); // geo = geo.buffer(0.0); // System.out.println("Converted to a "+FindGeoType(geo)+" that is "+(geo.isValid() ? "" : "not ")+"valid. ("+geo.toString()+")"); // this.geometry = new StrabonPolyhedron(geo, algorithm, maxPoints).geometry; //} else { this.geometry = new StrabonPolyhedron((Polygon) geo, algorithm, maxPoints).geometry; } else if (MultiPoint.class.isInstance(geo)) { this.geometry = geo; } else if (MultiLineString.class.isInstance(geo)) { //throw new Exception("MultiLineString not implemented yet."); MultiLineString mline = (MultiLineString)geo; ArrayList<LineString> collection = new ArrayList<LineString>(mline.getNumGeometries()); for (int i = 0; i < mline.getNumGeometries(); i++) { System.out.println("[1] " + mline.getNumGeometries()); StrabonPolyhedron line = new StrabonPolyhedron(mline.getGeometryN(i), algorithm, maxPoints); System.out.println("[2] " + line.geometry.getNumGeometries()); for (int j = 0; j < line.geometry.getNumGeometries(); j++) { collection.add((LineString)line.geometry.getGeometryN(j)); } } LineString[] linecollection = new LineString[collection.size()]; int k = 0; for (LineString line : collection) { linecollection[k] = line; k++; assert (!line.isEmpty()); } this.geometry = new MultiLineString(linecollection, new GeometryFactory()); } else if (MultiPolygon.class.isInstance(geo)) { // if (!geo.isValid()) { //// System.out.println("Non valid " + FindGeoType(geo) + " found."); //// geo = geo.buffer(0.0); //// Geometry[] geometries = new Geometry[geo.getNumGeometries()]; //// for (int i = 0; i < geo.getNumGeometries(); i++) { //// boolean before = geo.getGeometryN(i).isValid(); //// geometries[i] = geo.getGeometryN(i).buffer(0.0); //// boolean after = geometries[i].isValid(); //// //System.out.println("Geometry " + i + " was " + (before ? "" : "not ") + "valid and now it is " + (after ? "still " : "not ") + "valid."); //// Geometry col = new GeometryCollection(geometries, new GeometryFactory()).buffer(0.0); //// System.out.println("Converted to a "+FindGeoType(col)+" that is "+(col.isValid() ? "" : "not ")+"valid."); //// this.geometry = new StrabonPolyhedron(col, algorithm, maxPoints).geometry; //// System.out.println("Non valid " + FindGeoType(geo) + " found."); //// System.out.println("Number of geometries: " + geo.getNumGeometries()); //// MultiPolygon multipoly = (MultiPolygon)geo; //// Geometry newPoly = multipoly.getGeometryN(0); //// for (int i = 1; i < geo.getNumGeometries(); i++) { //// newPoly = newPoly.union(geo.getGeometryN(i)); //// newPoly.buffer(0.0); //// //Geometry col = new GeometryCollection(geometries, new GeometryFactory()).buffer(0.0); //// System.out.println("Converted to a "+FindGeoType(newPoly)+" that is "+(newPoly.isValid() ? "" : "not ")+"valid."); //// this.geometry = new StrabonPolyhedron(newPoly, algorithm, maxPoints).geometry; // //System.out.println("Non valid " + FindGeoType(geo) + " found. (coordinates:"+geo.getCoordinates().length+")"); // //geo = TopologyPreservingSimplifier.simplify(geo, 0.2); // while (true) { // if (geo.getCoordinates().length > 300000) { // geo = TopologyPreservingSimplifier.simplify(geo, 0.1); // System.out.println("Simplified to a "+FindGeoType(geo)+" that is "+(geo.isValid() ? "" : "not ")+"valid (coordinates:"+geo.getCoordinates().length+")."); // geo = geo.buffer(0.0); // System.out.println("Buffered to a "+FindGeoType(geo)+" that is "+(geo.isValid() ? "" : "not ")+"valid (coordinates:"+geo.getCoordinates().length+")."); // if (geo.isValid() && (geo.getCoordinates().length < 300000)) // break; // this.geometry = new StrabonPolyhedron(geo, algorithm, maxPoints).geometry; // //System.out.println("Are the geometries the same? Answer: " + (geo.equals(this.geometry) ? "true" : "false")); // } else { MultiPolygon mpoly = (MultiPolygon)geo; ArrayList<Polygon> collection = new ArrayList<Polygon>(mpoly.getNumGeometries()); for (int i = 0; i < mpoly.getNumGeometries(); i++) { System.out.println("[1] " + mpoly.getNumGeometries()); StrabonPolyhedron poly = new StrabonPolyhedron(mpoly.getGeometryN(i), algorithm, maxPoints); System.out.println("[2] " + poly.geometry.getNumGeometries()); for (int j = 0; j < poly.geometry.getNumGeometries(); j++) { collection.add((Polygon)poly.geometry.getGeometryN(j)); } } Polygon[] polycollection = new Polygon[collection.size()]; int k = 0; for (Polygon polygon : collection) { polycollection[k] = polygon; k++; assert (!polygon.isEmpty()); } this.geometry = new MultiPolygon(polycollection, new GeometryFactory()); } else { // if (!geo.isValid()) { // System.out.println("Non valid " + FindGeoType(geo) + " found."); // geo = geo.buffer(0.0); // System.out.println("Converted to a "+FindGeoType(geo)+" that is "+(geo.isValid() ? "" : "not ")+"valid+."); // this.geometry = new StrabonPolyhedron(geo, algorithm, maxPoints).geometry; // } else { for (int i = 0; i < geo.getNumGeometries(); i++) { StrabonPolyhedron smallGeo = new StrabonPolyhedron(geo.getGeometryN(i), algorithm, maxPoints); if (this.geometry == null) { this.geometry = smallGeo.geometry; } else { this.geometry.union(smallGeo.geometry); } } } } /** * Sets the geometry of this {@link StrabonPolyhedron} instance to * the given one. * * @param geometry */ public void setGeometry(Geometry geometry) { this.geometry = geometry; } /** * Returns the string representation of the geometry. */ public String toString() { return geometry.toString(); } /** * Returns the representation of the geometry in WKT (assumed * as the default representation in {@link StrabonPolyhedron}). * * @return */ public String toText() { return geometry.toText(); } /** * Return the geometry of {@link StrabonPolyhedron} in Well-Known * Binary (WKB). * * This method is equivalent to {@link #toByteArray()}. * * @return */ public byte[] toWKB() { return jts.WKBwrite(this.geometry); } /** * Return the geometry of {@link StrabonPolyhedron} as WKT. * * @return */ public String toWKT() { return jts.WKTwrite(this.geometry); } /** * Return the geometry of {@link StrabonPolyhedron} as a byte array. * * This method is equivalent to {@link #toWKB()}. * * @return */ public byte[] toByteArray() { return jts.WKBwrite(this.geometry); } /** * Returns the geometry of this {@link StrabonPolyhedron} instance. * * @return */ public Geometry getGeometry() { return this.geometry; } public static StrabonPolyhedron ParseBigPolyhedron(Geometry polygon, int algorithm, boolean horizontal, int maxPoints) throws Exception { assert (Polygon.class.isInstance(polygon) || (MultiPolygon.class.isInstance(polygon))); if (polygon.getCoordinates().length > maxPoints) { // if (polygon.isValid()){ // System.out.println("Found big polyhedron. Coordinates: " + polygon.getCoordinates().length + " (valid="+polygon.isValid()+")."); // } else { // System.out.println("Found invalid big polyhedron. Coordinates: " + polygon.getCoordinates().length + "."); // //IsValidOp err = new IsValidOp(polygon); // //System.out.println("Validation error: " + err.getValidationError()); // //new Point(new CoordinateArraySequence(new Coordinate[] {polygon.getCoordinates()[0]}), new GeometryFactory()); // //polygon = polygon.union(onePoint); // polygon = polygon.buffer(0.0); // System.out.println("After conversion, coordinates: " + polygon.getCoordinates().length + " (valid="+polygon.isValid()+")."); double minx = Double.MAX_VALUE, miny = Double.MAX_VALUE, maxx = Double.MIN_VALUE, maxy = Double.MIN_VALUE; Geometry bbox = polygon.getEnvelope(); for (int i = 0; i < bbox.getCoordinates().length; i++) { Coordinate c = bbox.getCoordinates()[i]; if (c.x > maxx) maxx = c.x; if (c.x < minx) minx = c.x; if (c.y > maxy) maxy = c.y; if (c.y < miny) miny = c.y; } Polygon firsthalf = new Polygon(new LinearRing(new CoordinateArraySequence( new Coordinate[] { new Coordinate(minx, miny), new Coordinate(horizontal ? (minx + (maxx-minx)/2) : maxx, miny), new Coordinate(horizontal ? (minx + (maxx-minx)/2) : maxx, horizontal ? maxy : (miny + (maxy-miny)/2)), new Coordinate(minx, horizontal ? maxy : (miny + (maxy-miny)/2)), new Coordinate(minx, miny)} ), new GeometryFactory()), null, new GeometryFactory()); firsthalf.normalize(); Polygon secondhalf = (Polygon) bbox.difference(firsthalf); secondhalf.normalize(); // double a = polygon.getArea(); // double b = polygon.getEnvelope().getArea(); // double c = firsthalf.getArea(); // double d = bbox.difference(firsthalf).getArea(); // double e = b-c-d; // double f = c-d; // double kk = firsthalf.difference(bbox).difference(firsthalf).getArea(); // boolean g = firsthalf.equals(bbox.difference(firsthalf)); // boolean h = firsthalf.disjoint(bbox.difference(firsthalf)); // boolean i = bbox.equals(firsthalf.union(bbox.difference(firsthalf))); // boolean j = firsthalf.intersects(polygon); // boolean k = bbox.difference(firsthalf).intersects(polygon); Geometry A = polygon.intersection(firsthalf); System.out.println("First half : " + A.getCoordinates().length + " coordinates."); //Geometry B = polygon.intersection(bbox.difference(firsthalf)); Geometry B = polygon.intersection(secondhalf); System.out.println("Second half : " + B.getCoordinates().length + " coordinates."); StrabonPolyhedron polyA = ParseBigPolyhedron(A, algorithm, !horizontal, maxPoints); StrabonPolyhedron polyB = ParseBigPolyhedron(B, algorithm, !horizontal, maxPoints); return StrabonPolyhedron.quickUnion(polyA, polyB); } else { System.out.println("Found small polyhedron. Coordinates: " + polygon.getCoordinates().length); return new StrabonPolyhedron(polygon, algorithm, maxPoints); } } @Deprecated public StrabonPolyhedron(Polygon polygon, int algorithm, int maxPoints) throws Exception { // if (!polygon.isSimple()) // throw new Exception( // "The polygon is not simple. Only simple polygons are supported"); Coordinate[] coordinates = polygon.getCoordinates(); if (coordinates.length > maxPoints) { this.geometry = ParseBigPolyhedron(polygon, algorithm, true, maxPoints).geometry; return; } int distinctCoordinates = 0; boolean fix = false; for (int i = 0; i <= coordinates.length - 1; i++) { Coordinate c1 = coordinates[i]; if (i == (coordinates.length - 1)) { // eimaste sto teleutaio simeio if ((c1.x != coordinates[0].x) || (c1.y != coordinates[0].y)) { // and den einai to idio me to 1o error //throw new Exception("Problem in geometry. First and last point (i="+i+") do not match (coordinates: "+coordinates.length+", isValid:"+polygon.isValid()+")."); distinctCoordinates++; fix = true; } else if ((c1.x == coordinates[i-1].x) && (c1.y == coordinates[i-1].y)) { //einai to idio me to proigoumeno opote den kanoume tipota giati //exoun hdh auksithei ta dinstinct } else { // den einai to idio me to proigoumeno opote auksise ta distinct distinctCoordinates++; } continue; } Coordinate c2 = coordinates[i+1]; if ((c1.x != c2.x) || (c1.y != c2.y)) { distinctCoordinates++; } } // cgal wants counter clockwise order //double[][] c = new double[coordinates.length - 1][2]; int counter = 0; double[][] c = new double[(fix ? distinctCoordinates : (distinctCoordinates - 1))][2]; for (int i = 0; i <= coordinates.length - 2; i++) { Coordinate c1 = coordinates[i]; Coordinate c2 = coordinates[i+1]; if ((c1.x != c2.x) || (c1.y != c2.y)) { c[counter][0] = c1.x; c[counter][1] = c1.y; counter++; } } if (fix) { c[distinctCoordinates-1][0] = coordinates[coordinates.length-1].x; c[distinctCoordinates-1][1] = coordinates[coordinates.length-1].y; } double start = System.nanoTime(); // double[][][] convexified = Polyhedron.ConvexifyPolygon(c, algorithm); double[][][] convexified = new double[1][2][3]; // if (convexified == null) { // throw new ParseGeometryException("Invalid geometry. Only simple geometries are supported."); System.out.println("ConvexifyTime " + (System.nanoTime()-start)); double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; for (int i = 0; i < convexified.length; i++) { double[][] convexCoordinates = convexified[i]; for (int j = 0; j < convexCoordinates.length; j++) { if (convexCoordinates[j][0] > max) max = convexCoordinates[j][0]; if (convexCoordinates[j][0] < min) min = convexCoordinates[j][0]; } } // String gnuPlotScript = ""; // for (int i = 0; i < convexified.length; i++) { // double[][] convexCoordinates = convexified[i]; // sizes[convexCoordinates.length]++; // BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/home/kkyzir/Desktop/Spatial data/ssg4env/geometries/gnuplot/data-" + i + ".dat"))); // bw2 = new BufferedWriter(new FileWriter(new File("/home/kkyzir/Desktop/Spatial data/ssg4env/geometries/gnuplot/script-" + i + ".gnuplot"))); // for (int j = 0; j < convexCoordinates.length; j++) { // bw.write(new Double(convexCoordinates[j][0]).toString()); // bw.write(" "); // bw.write(new Double(convexCoordinates[j][1]).toString()); // bw.write("\n"); // bw.flush(); // bw.close(); // gnuPlotScript += "'data-" + i + ".dat' with lines,"; // bw2.write("set terminal postscript eps color\n"); // bw2.write("set out '/home/kkyzir/Desktop/Spatial data/ssg4env/geometries/gnuplot/geo-"+i+".eps'\n"); // bw2.write("set key bmargin left horizontal Right noreverse enhanced autotitles box linetype -1 linewidth 1.000\n"); // bw2.write("plot ["+0.95*min+":"+1.05*max+"] 'data-" + i +".dat' with lines, 'original.dat' with lines\n"); // bw2.flush(); // bw2.close(); // gnuPlotScript = "plot ["+0.95*min+":"+1.05*max+"] " + gnuPlotScript.substring(0, gnuPlotScript.length()-1); // gnuPlotScript = "set terminal postscript eps color\n" + // "set out '/home/kkyzir/Desktop/Spatial data/ssg4env/geometries/gnuplot/all.eps'\n" + // "set key bmargin left horizontal Right noreverse enhanced autotitles box linetype -1 linewidth 1.000\n" + // gnuPlotScript; // BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/home/kkyzir/Desktop/Spatial data/ssg4env/geometries/gnuplot/script-all.gnuplot"))); // bw.write(gnuPlotScript); // bw.flush(); // bw.close(); // for (int i = 0; i < convexified.length; i++) { // Runtime.getRuntime().exec("gnuplot /home/kkyzir/Desktop/Spatial\\ data/ssg4env/geometries/gnuplot/script-"+i+".gnuplot"); // Runtime.getRuntime().exec("gnuplot /home/kkyzir/Desktop/Spatial\\ data/ssg4env/geometries/gnuplot/script-all.gnuplot"); //Geometry[] collection = new Geometry[convexified.length]; Polygon[] collection = new Polygon[convexified.length]; System.out.println("Convex parts: " + convexified.length); for (int i = 0; i < convexified.length; i++) { GeometryFactory factory = new GeometryFactory(); double[][] convexCoordinates = convexified[i]; Coordinate[] jtsCoordinates = new Coordinate[convexCoordinates.length]; for (int j = 0; j < convexCoordinates.length; j++) { Coordinate co = new Coordinate(convexCoordinates[j][0], convexCoordinates[j][1]); jtsCoordinates[j] = co; } CoordinateSequence points = new CoordinateArraySequence( jtsCoordinates); //System.out.println("Points: " + points.size()); LinearRing ring = new LinearRing(points, factory); Polygon poly = new Polygon(ring, null, factory); collection[i] = poly; // if (this.geometry == null) { // this.geometry = poly; // } else { // this.geometry = this.geometry.union(poly); } //this.geometry = new GeometryCollection(collection, new GeometryFactory()); //this.geometry.normalize(); this.geometry = new MultiPolygon(collection, new GeometryFactory()); this.geometry.normalize(); } public String toConstraints() //throws ConversionException { if (this.geometry.isEmpty()) return ""; if (!EnableConstraintRepresentation) { return "Constraint representation is disabled."; } //Polyhedron poly = new Polyhedron(this.geometry); //return poly.toConstraints(); return ""; } public static StrabonPolyhedron union(StrabonPolyhedron A, StrabonPolyhedron B) throws Exception { StrabonPolyhedron poly = new StrabonPolyhedron(); int targetSRID = A.getGeometry().getSRID(); int sourceSRID = B.getGeometry().getSRID(); Geometry x = JTSWrapper.getInstance().transform(B.getGeometry(), sourceSRID, targetSRID); poly.geometry = A.geometry.union(x); poly.geometry.setSRID(targetSRID); return poly; } public static StrabonPolyhedron buffer(StrabonPolyhedron A, double B) throws Exception { StrabonPolyhedron poly = new StrabonPolyhedron(); poly.geometry = A.geometry.buffer(B); return poly; } public static StrabonPolyhedron envelope(StrabonPolyhedron A) throws Exception { StrabonPolyhedron poly = new StrabonPolyhedron(); poly.geometry = A.geometry.getEnvelope(); return poly; } public static StrabonPolyhedron convexHull(StrabonPolyhedron A) throws Exception { StrabonPolyhedron poly = new StrabonPolyhedron(); poly.geometry = A.geometry.convexHull(); return poly; } public static StrabonPolyhedron boundary(StrabonPolyhedron A) throws Exception { StrabonPolyhedron poly = new StrabonPolyhedron(); poly.geometry = A.geometry.getBoundary(); return poly; } public static StrabonPolyhedron intersection(StrabonPolyhedron A, StrabonPolyhedron B) throws Exception { int targetSRID = A.getGeometry().getSRID(); int sourceSRID = B.getGeometry().getSRID(); Geometry x = JTSWrapper.getInstance().transform(B.getGeometry(), sourceSRID, targetSRID); Geometry geo = A.geometry.intersection(x); geo.setSRID(targetSRID); return new StrabonPolyhedron(geo); } public static StrabonPolyhedron difference(StrabonPolyhedron A, StrabonPolyhedron B) throws Exception { StrabonPolyhedron poly = new StrabonPolyhedron(); int targetSRID = A.getGeometry().getSRID(); int sourceSRID = B.getGeometry().getSRID(); Geometry x = JTSWrapper.getInstance().transform(B.getGeometry(), sourceSRID, targetSRID); poly.geometry = A.geometry.difference(x); poly.geometry.setSRID(targetSRID); return poly; } public static StrabonPolyhedron symDifference(StrabonPolyhedron A, StrabonPolyhedron B) throws Exception { StrabonPolyhedron poly = new StrabonPolyhedron(); int targetSRID = A.getGeometry().getSRID(); int sourceSRID = B.getGeometry().getSRID(); Geometry x = JTSWrapper.getInstance().transform(B.getGeometry(), sourceSRID, targetSRID); poly.geometry = A.geometry.symDifference(x); poly.geometry.setSRID(targetSRID); return poly; } public static double area(StrabonPolyhedron A) throws Exception { return A.geometry.getArea(); } public static double distance(StrabonPolyhedron A, StrabonPolyhedron B) throws Exception { int targetSRID = A.getGeometry().getSRID(); int sourceSRID = B.getGeometry().getSRID(); Geometry x = JTSWrapper.getInstance().transform(B.getGeometry(), sourceSRID, targetSRID); return A.geometry.distance(x); } public static StrabonPolyhedron project(StrabonPolyhedron A, int[] dims) throws Exception { StrabonPolyhedron poly = new StrabonPolyhedron(); ProjectionsFilter filter = new ProjectionsFilter(dims); A.geometry.apply(filter); A.geometry.geometryChanged(); poly.geometry = A.geometry; return poly; } public static StrabonPolyhedron transform(StrabonPolyhedron A, URI srid) throws Exception { int parsedSRID = Integer.parseInt(srid.toString().substring(srid.toString().lastIndexOf('/')+1)); Geometry converted = JTSWrapper.getInstance().transform(A.getGeometry(), A.getGeometry().getSRID(), parsedSRID); return new StrabonPolyhedron(converted); } /** * Performs quick union between polygons or multipolygons. * * @param A * @param B * @return * @throws Exception */ public static StrabonPolyhedron quickUnion(StrabonPolyhedron A, StrabonPolyhedron B) throws Exception { System.out.println("Merging polyhedrons: A.coordinates=" + A.getGeometry().getCoordinates().length + ", B.coordinates=" + B.getGeometry().getCoordinates().length); StrabonPolyhedron poly = new StrabonPolyhedron(); int polygons = 0; if (Polygon.class.isInstance(A.geometry)) { polygons++; } else if (MultiPolygon.class.isInstance(A.geometry)) { polygons += ((MultiPolygon)(A.geometry)).getNumGeometries(); } if (Polygon.class.isInstance(B.geometry)) { polygons++; } else if (MultiPolygon.class.isInstance(B.geometry)) { polygons += ((MultiPolygon)(B.geometry)).getNumGeometries(); } assert (polygons >= 2); int index = 0; Polygon[] polys = new Polygon[polygons]; if (Polygon.class.isInstance(A.geometry)) { polys[index] = (Polygon)(A.geometry); index++; } if (Polygon.class.isInstance(B.geometry)) { polys[index] = (Polygon)(B.geometry); index++; } if (MultiPolygon.class.isInstance(A.geometry)) { MultiPolygon multi = (MultiPolygon)(A.geometry); for (int i = 0; i < multi.getNumGeometries(); i++) { polys[index] = (Polygon)multi.getGeometryN(i); index++; } } if (MultiPolygon.class.isInstance(B.geometry)) { MultiPolygon multi = (MultiPolygon)(B.geometry); for (int i = 0; i < multi.getNumGeometries(); i++) { polys[index] = (Polygon)multi.getGeometryN(i); index++; } } poly.geometry = new MultiPolygon(polys, new GeometryFactory()); return poly; } public StrabonPolyhedron getBuffer(double distance) throws Exception { Geometry geo = this.geometry.buffer(distance); return new StrabonPolyhedron(geo); } public StrabonPolyhedron getBoundary() throws Exception { Geometry geo = this.geometry.getBoundary(); return new StrabonPolyhedron(geo); } public StrabonPolyhedron getEnvelope() throws Exception { Geometry geo = this.geometry.getEnvelope(); return new StrabonPolyhedron(geo); } public double getArea() throws Exception { return this.getArea(); } public int getNumPoints() { return this.geometry.getNumPoints(); } private static String FindGeoType(Geometry geo) { return Point.class.isInstance(geo) ? "Point" : MultiPoint.class.isInstance(geo) ? "MultiPoint" : LineString.class.isInstance(geo) ? "LineString" : MultiLineString.class.isInstance(geo) ? "MultiLineString" : Polygon.class.isInstance(geo) ? "Polygon" : MultiPolygon.class.isInstance(geo) ? "MultiPolygon" : GeometryCollection.class.isInstance(geo) ? "GeometryCollection" : "Unknown"; } }
package org.xbill.DNS; import java.io.*; import java.text.*; import java.lang.reflect.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A generic DNS resource record. The specific record types extend this class. * A record contains a name, type, class, and rdata. * * @author Brian Wellington */ public abstract class Record implements Cloneable, Comparable { protected Name name; protected int type, dclass; protected long ttl; private boolean empty; private static final Record [] knownRecords = new Record[256]; private static final Record unknownRecord = new UNKRecord(); private static final Class [] emptyClassArray = new Class[0]; private static final Object [] emptyObjectArray = new Object[0]; private static final DecimalFormat byteFormat = new DecimalFormat(); static { byteFormat.setMinimumIntegerDigits(3); } protected Record() {} Record(Name name, int type, int dclass, long ttl) { if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); TTL.check(ttl); this.name = name; this.type = type; this.dclass = dclass; this.ttl = ttl; } /** * Creates an empty record of the correct type; must be overriden */ abstract Record getObject(); private static final Record getTypedObject(int type) { if (type < 0 || type > knownRecords.length) return unknownRecord.getObject(); if (knownRecords[type] != null) return knownRecords[type]; /* Construct the class name by putting the type before "Record". */ String s = Record.class.getPackage().getName() + "." + Type.string(type).replace('-', '_') + "Record"; try { Class c = Class.forName(s); Constructor m = c.getDeclaredConstructor(emptyClassArray); knownRecords[type] = (Record) m.newInstance(emptyObjectArray); } catch (ClassNotFoundException e) { /* This is normal; do nothing */ } catch (Exception e) { if (Options.check("verbose")) System.err.println(e); } if (knownRecords[type] == null) knownRecords[type] = unknownRecord.getObject(); return knownRecords[type]; } private static final Record getEmptyRecord(Name name, int type, int dclass, long ttl) { Record rec = getTypedObject(type); rec = rec.getObject(); rec.name = name; rec.type = type; rec.dclass = dclass; rec.ttl = ttl; return rec; } /** * Converts the type-specific RR to wire format - must be overriden */ abstract void rrFromWire(DNSInput in) throws IOException; private static Record newRecord(Name name, int type, int dclass, long ttl, int length, DNSInput in) throws IOException { Record rec; int recstart; rec = getEmptyRecord(name, type, dclass, ttl); if (in != null) { if (in.remaining() < length) throw new WireParseException("truncated record"); in.setActive(length); } else rec.empty = true; rec.rrFromWire(in); if (in != null) { if (in.remaining() > 0) throw new WireParseException("invalid record length"); in.clearActive(); } return rec; } /** * Creates a new record, with the given parameters. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param length The length of the record's data. * @param data The rdata of the record, in uncompressed DNS wire format. Only * the first length bytes are used. */ public static Record newRecord(Name name, int type, int dclass, long ttl, int length, byte [] data) { if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); TTL.check(ttl); DNSInput in; if (data != null) in = new DNSInput(data); else in = null; try { return newRecord(name, type, dclass, ttl, length, in); } catch (IOException e) { return null; } } /** * Creates a new record, with the given parameters. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param data The complete rdata of the record, in uncompressed DNS wire * format. */ public static Record newRecord(Name name, int type, int dclass, long ttl, byte [] data) { return newRecord(name, type, dclass, ttl, data.length, data); } /** * Creates a new empty record, with the given parameters. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @return An object of a subclass of Record */ public static Record newRecord(Name name, int type, int dclass, long ttl) { if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); TTL.check(ttl); Record rec = getEmptyRecord(name, type, dclass, ttl); rec.empty = true; return rec; } /** * Creates a new empty record, with the given parameters. This method is * designed to create records that will be added to the QUERY section * of a message. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @return An object of a subclass of Record */ public static Record newRecord(Name name, int type, int dclass) { return newRecord(name, type, dclass, 0); } static Record fromWire(DNSInput in, int section, boolean isUpdate) throws IOException { int type, dclass; long ttl; int length; Name name; Record rec; name = new Name(in); type = in.readU16(); dclass = in.readU16(); if (section == Section.QUESTION) return newRecord(name, type, dclass); ttl = in.readU32(); length = in.readU16(); if (length == 0 && isUpdate) return newRecord(name, type, dclass, ttl); rec = newRecord(name, type, dclass, ttl, length, in); return rec; } static Record fromWire(DNSInput in, int section) throws IOException { return fromWire(in, section, false); } /** * Builds a Record from DNS uncompressed wire format. */ public static Record fromWire(byte [] b, int section) throws IOException { return fromWire(new DNSInput(b), section, false); } void toWire(DNSOutput out, int section, Compression c) { int start = out.current(); name.toWire(out, c); out.writeU16(type); out.writeU16(dclass); if (section == Section.QUESTION) return; out.writeU32(ttl); int lengthPosition = out.current(); out.writeU16(0); /* until we know better */ if (!empty) rrToWire(out, c, false); int rrlength = out.current() - lengthPosition - 2; out.save(); out.jump(lengthPosition); out.writeU16(rrlength); out.restore(); } /** * Converts a Record into DNS uncompressed wire format. */ public byte [] toWire(int section) { DNSOutput out = new DNSOutput(); toWire(out, section, null); return out.toByteArray(); } private void toWireCanonical(DNSOutput out, boolean noTTL) { name.toWireCanonical(out); out.writeU16(type); out.writeU16(dclass); if (noTTL) { out.writeU32(0); } else { out.writeU32(ttl); } int lengthPosition = out.current(); out.writeU16(0); /* until we know better */ if (!empty) rrToWire(out, null, true); int rrlength = out.current() - lengthPosition - 2; out.save(); out.jump(lengthPosition); out.writeU16(rrlength); out.restore(); } /* * Converts a Record into canonical DNS uncompressed wire format (all names are * converted to lowercase), optionally ignoring the TTL. */ private byte [] toWireCanonical(boolean noTTL) { DNSOutput out = new DNSOutput(); toWireCanonical(out, noTTL); return out.toByteArray(); } /** * Converts a Record into canonical DNS uncompressed wire format (all names are * converted to lowercase). */ public byte [] toWireCanonical() { return toWireCanonical(false); } /** * Converts the rdata in a Record into canonical DNS uncompressed wire format * (all names are converted to lowercase). */ public byte [] rdataToWireCanonical() { if (empty) return new byte[0]; DNSOutput out = new DNSOutput(); rrToWire(out, null, true); return out.toByteArray(); } /** * Converts the type-specific RR to text format - must be overriden */ abstract String rrToString(); /** * Converts the rdata portion of a Record into a String representation */ public String rdataToString() { if (empty) return ""; return rrToString(); } /** * Converts a Record into a String representation */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append(name); if (sb.length() < 8) sb.append("\t"); if (sb.length() < 16) sb.append("\t"); sb.append("\t"); if (Options.check("BINDTTL")) sb.append(TTL.format(ttl)); else sb.append(ttl); sb.append("\t"); if (dclass != DClass.IN || !Options.check("noPrintIN")) { sb.append(DClass.string(dclass)); sb.append("\t"); } sb.append(Type.string(type)); if (!empty) { sb.append("\t"); sb.append(rrToString()); } return sb.toString(); } /** * Converts the text format of an RR to the internal format - must be overriden */ abstract void rdataFromString(Tokenizer st, Name origin) throws IOException; /** * Converts a String into a byte array. */ protected static byte [] byteArrayFromString(String s) throws TextParseException { byte [] array = s.getBytes(); boolean escaped = false; boolean hasEscapes = false; for (int i = 0; i < array.length; i++) { if (array[i] == '\\') { hasEscapes = true; break; } } if (!hasEscapes) { if (array.length > 255) { throw new TextParseException("text string too long"); } return array; } ByteArrayOutputStream os = new ByteArrayOutputStream(); int digits = 0; int intval = 0; for (int i = 0; i < array.length; i++) { byte b = array[i]; if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw new TextParseException ("bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); os.write(b); escaped = false; } else if (array[i] == '\\') { escaped = true; digits = 0; intval = 0; } else os.write(array[i]); } if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); array = os.toByteArray(); if (array.length > 255) { throw new TextParseException("text string too long"); } return os.toByteArray(); } /** * Converts a byte array into a String. */ protected static String byteArrayToString(byte [] array, boolean quote) { StringBuffer sb = new StringBuffer(); if (quote) sb.append('"'); for (int i = 0; i < array.length; i++) { short b = (short)(array[i] & 0xFF); if (b < 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == ';' || b == '\\') { sb.append('\\'); sb.append((char)b); } else sb.append((char)b); } if (quote) sb.append('"'); return sb.toString(); } /** * Converts a byte array into the unknown RR format. */ protected static String unknownToString(byte [] data) { StringBuffer sb = new StringBuffer(); sb.append("\\ sb.append(data.length); sb.append(" "); sb.append(base16.toString(data)); return sb.toString(); } /** * Builds a new Record from its textual representation * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param st A tokenizer containing the textual representation of the rdata. * @param origin The default origin to be appended to relative domain names. * @return The new record * @throws IOException The text format was invalid. */ public static Record fromString(Name name, int type, int dclass, long ttl, Tokenizer st, Name origin) throws IOException { Record rec; if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); TTL.check(ttl); Tokenizer.Token t = st.get(); if (t.type == Tokenizer.IDENTIFIER && t.value.equals("\\ int length = st.getUInt16(); byte [] data = st.getHex(); if (data == null) { data = new byte[0]; } if (length != data.length) throw st.exception("invalid unknown RR encoding: " + "length mismatch"); DNSInput in = new DNSInput(data); return newRecord(name, type, dclass, ttl, length, in); } st.unget(); rec = getEmptyRecord(name, type, dclass, ttl); rec.rdataFromString(st, origin); t = st.get(); if (t.type != Tokenizer.EOL && t.type != Tokenizer.EOF) { throw st.exception("unexpected tokens at end of record"); } return rec; } /** * Builds a new Record from its textual representation * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param s The textual representation of the rdata. * @param origin The default origin to be appended to relative domain names. * @return The new record * @throws IOException The text format was invalid. */ public static Record fromString(Name name, int type, int dclass, long ttl, String s, Name origin) throws IOException { return fromString(name, type, dclass, ttl, new Tokenizer(s), origin); } /** * Returns the record's name * @see Name */ public Name getName() { return name; } /** * Returns the record's type * @see Type */ public int getType() { return type; } /** * Returns the type of RRset that this record would belong to. For all types * except SIGRecord, this is equivalent to getType(). * @return The type of record, if not SIGRecord. If the type is SIGRecord, * the type covered is returned. * @see Type * @see RRset * @see SIGRecord */ public int getRRsetType() { if (type == Type.SIG || type == Type.RRSIG) { SIGBase sig = (SIGBase) this; return sig.getTypeCovered(); } return type; } /** * Returns the record's class */ public int getDClass() { return dclass; } /** * Returns the record's TTL */ public long getTTL() { return ttl; } /** * Converts the type-specific RR to wire format - must be overriden */ abstract void rrToWire(DNSOutput out, Compression c, boolean canonical); /** * Determines if two Records are identical. This compares the name, type, * class, and rdata (with names canonicalized). The TTLs are not compared. * @param arg The record to compare to * @return true if the records are equal, false otherwise. */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Record)) return false; Record r = (Record) arg; if (type != r.type || dclass != r.dclass || !name.equals(r.name)) return false; if (empty && r.empty) return true; else if (empty || r.empty) return false; byte [] array1 = rdataToWireCanonical(); byte [] array2 = r.rdataToWireCanonical(); return Arrays.equals(array1, array2); } /** * Generates a hash code based on the Record's data. */ public int hashCode() { byte [] array = toWireCanonical(true); int code = 0; for (int i = 0; i < array.length; i++) code += ((code << 3) + (array[i] & 0xFF)); return code; } private Record cloneRecord() { try { return (Record) clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(); } } /** * Creates a new record identical to the current record, but with a different * name. This is most useful for replacing the name of a wildcard record. */ public Record withName(Name name) { if (!name.isAbsolute()) throw new RelativeNameException(name); Record rec = cloneRecord(); rec.name = name; return rec; } /** * Creates a new record identical to the current record, but with a different * class and ttl. This is most useful for dynamic update. */ Record withDClass(int dclass, long ttl) { Record rec = cloneRecord(); rec.dclass = dclass; rec.ttl = ttl; return rec; } /** * Compares this Record to another Object. * @param o The Object to be compared. * @return The value 0 if the argument is a record equivalent to this record; * a value less than 0 if the argument is less than this record in the * canonical ordering, and a value greater than 0 if the argument is greater * than this record in the canonical ordering. The canonical ordering * is defined to compare by name, class, type, and rdata. * @throws ClassCastException if the argument is not a Record. */ public int compareTo(Object o) { Record arg = (Record) o; if (this == arg) return (0); int n = name.compareTo(arg.name); if (n != 0) return (n); n = dclass - arg.dclass; if (n != 0) return (n); n = type - arg.type; if (n != 0) return (n); if (empty && arg.empty) return 0; else if (empty) return -1; else if (arg.empty) return 1; byte [] rdata1 = rdataToWireCanonical(); byte [] rdata2 = arg.rdataToWireCanonical(); for (int i = 0; i < rdata1.length && i < rdata2.length; i++) { n = (rdata1[i] & 0xFF) - (rdata2[i] & 0xFF); if (n != 0) return (n); } return (rdata1.length - rdata2.length); } /** * Returns the name for which additional data processing should be done * for this record. This can be used both for building responses and * parsing responses. * @return The name to used for additional data processing, or null if this * record type does not require additional data processing. */ public Name getAdditionalName() { return null; } /* Checks that an int contains an unsigned 8 bit value */ static int checkU8(String field, int val) { if (val < 0 || val > 0xFF) throw new IllegalArgumentException("\"" + field + "\" " + val + "must be an unsigned 8 " + "bit value"); return val; } /* Checks that an int contains an unsigned 16 bit value */ static int checkU16(String field, int val) { if (val < 0 || val > 0xFFFF) throw new IllegalArgumentException("\"" + field + "\" " + val + "must be an unsigned 16 " + "bit value"); return val; } /* Checks that a long contains an unsigned 32 bit value */ static long checkU32(String field, long val) { if (val < 0 || val > 0xFFFFFFFFL) throw new IllegalArgumentException("\"" + field + "\" " + val + "must be an unsigned 32 " + "bit value"); return val; } /* Checks that a name is absolute */ static Name checkName(String field, Name name) { if (!name.isAbsolute()) throw new RelativeNameException(name); return name; } }
package applets; import javacard.framework.*; import javacard.security.*; /** * The applet for secure key storage on a smart card. * @author Manoja Kumar Das * @author Ondrej Mosnacek &lt;omosnacek@gmail.com&gt; */ public class KeyStorageApplet extends Applet { public static final byte[] AID = new byte[] { (byte)0x4a, (byte)0x43, (byte)0x4b, (byte)0x65, (byte)0x79, (byte)0x53, (byte)0x74, (byte)0x6f, (byte)0x72, (byte)0x61, (byte)0x67, (byte)0x65 }; public static final byte CLA_KEYSTORAGEAPPLET = (byte)0xB0; public void process(APDU apdu) throws ISOException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package urteam; import java.sql.Date; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import urteam.event.Event; import urteam.event.EventRepository; import urteam.community.*; import urteam.event.*; import urteam.user.*; @Controller public class urteamController { @Autowired private UserRepository userRepo; @Autowired private EventRepository eventRepo; @Autowired private CommunityRepository communityRepo; @PostConstruct public void init (){ for (int i = 0; i < 10; i++) { String name = String.valueOf(i); String surname = String.valueOf(i); userRepo.save(new User(name, surname)); } for (int i = 0; i < 10; i++) { eventRepo.save(new Event()); } for (int i = 0; i < 10; i++) { communityRepo.save(new Community()); } } }
package uk.ac.ebi.quickgo.index.annotation.coterms; import uk.ac.ebi.quickgo.index.annotation.Annotation; import java.io.File; import java.util.List; import java.util.function.Predicate; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.file.FlatFileHeaderCallback; import org.springframework.batch.item.file.FlatFileItemWriter; import org.springframework.batch.item.file.transform.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; @Configuration public class Co_occurringTermsConfiguration { private static final String[] FF_COL_NAMES = {"target", "comparedTerm", "probabilityRatio", "similarityRatio", "together", "compared"}; private static final String DELIMITER = "\t"; @Value("${indexing.coterms.dir}") private String path; public static final String COSTATS_MANUAL_COMPLETION_STEP_NAME = "costatsManualSummarizationStep"; public static final String COSTATS_ALL_COMPLETION_STEP_NAME = "costatsAllSummarizationStep"; @Bean AnnotationCo_occurringTermsAggregator annotationCo_occurringTermsAggregatorMan() { return new AnnotationCo_occurringTermsAggregator(); } @Bean AnnotationCo_occurringTermsAggregator annotationCo_occurringTermsAggregatorAll() { return new AnnotationCo_occurringTermsAggregator(); } @Bean public ItemProcessor<Annotation, Annotation> co_occurringGoTermsFromAnnotationsManual( AnnotationCo_occurringTermsAggregator annotationCo_occurringTermsAggregatorMan) { Predicate<Annotation> toBeProcessed = t -> !"IEA".equals(t.evidenceCode); return new Co_occurringGoTermsFromAnnotations(annotationCo_occurringTermsAggregatorMan, toBeProcessed); } @Bean public ItemProcessor<Annotation, Annotation> co_occurringGoTermsFromAnnotationsAll( AnnotationCo_occurringTermsAggregator annotationCo_occurringTermsAggregatorAll) { Predicate<Annotation> toBeProcessed = t -> true; return new Co_occurringGoTermsFromAnnotations(annotationCo_occurringTermsAggregatorAll, toBeProcessed); } @Bean public Co_occurringTermsStepExecutionListener coTermsEndOfAggregationListener( AnnotationCo_occurringTermsAggregator annotationCo_occurringTermsAggregatorAll, AnnotationCo_occurringTermsAggregator annotationCo_occurringTermsAggregatorMan, Co_occurringTermsStatsCalculator co_occurringTermsStatsCalculatorManual, Co_occurringTermsStatsCalculator co_occurringTermsStatsCalculatorAll) { return new Co_occurringTermsStepExecutionListener(annotationCo_occurringTermsAggregatorAll, annotationCo_occurringTermsAggregatorMan, co_occurringTermsStatsCalculatorManual, co_occurringTermsStatsCalculatorAll); } @Bean public Co_occurringTermsStatsCalculator co_occurringTermsStatsCalculatorManual( AnnotationCo_occurringTermsAggregator annotationCo_occurringTermsAggregatorMan) { return new Co_occurringTermsStatsCalculator(annotationCo_occurringTermsAggregatorMan); } @Bean public Co_occurringTermsStatsCalculator co_occurringTermsStatsCalculatorAll( AnnotationCo_occurringTermsAggregator annotationCo_occurringTermsAggregatorAll) { return new Co_occurringTermsStatsCalculator(annotationCo_occurringTermsAggregatorAll); } @Bean public ItemReader<String> coStatsManualItemReader(AnnotationCo_occurringTermsAggregator annotationCo_occurringTermsAggregatorMan) { return new Co_occurringTermItemReader(annotationCo_occurringTermsAggregatorMan); } @Bean public ItemReader<String> coStatsAllItemReader(AnnotationCo_occurringTermsAggregator annotationCo_occurringTermsAggregatorAll) { return new Co_occurringTermItemReader(annotationCo_occurringTermsAggregatorAll); } @Bean ItemWriter<List<Co_occurringTerm>> coStatManualFlatFileWriter() { return listItemFlatFileWriter("CoStatsManual"); } @Bean ItemWriter<List<Co_occurringTerm>> coStatsAllFlatFileWriter() { return listItemFlatFileWriter("CoStatsAll"); } private File getFilePath() { File file = new File(path); if (!file.exists()) { file.mkdir(); } return file; } private ListItemWriter<Co_occurringTerm> listItemFlatFileWriter(String fileName) { ListItemWriter<Co_occurringTerm> listWriter = new ListItemWriter<>(flatFileWriter(fileName)); listWriter.setLineAggregator(new PassThroughLineAggregator<>()); //this shouldn't do anything return listWriter; } private FlatFileItemWriter<Co_occurringTerm> flatFileWriter(String fileName) { FlatFileItemWriter<Co_occurringTerm> ffw = new FlatFileItemWriter<>(); ffw.setLineAggregator(lineAggregator()); Resource outputFile = new FileSystemResource(new File(getFilePath(), fileName)); ffw.setResource(outputFile); FlatFileHeaderCallback headerCallBack = new Co_occurringTermsFlatFileHeaderCallBack(); ffw.setHeaderCallback(headerCallBack); return ffw; } private LineAggregator<Co_occurringTerm> lineAggregator() { DelimitedLineAggregator<Co_occurringTerm> delimitedLineAggregator = new DelimitedLineAggregator<>(); delimitedLineAggregator.setDelimiter(DELIMITER); delimitedLineAggregator.setFieldExtractor(beanWrapperFieldExtractor()); return delimitedLineAggregator; } private BeanWrapperFieldExtractor<Co_occurringTerm> beanWrapperFieldExtractor() { BeanWrapperFieldExtractor<Co_occurringTerm> beanWrapperFieldExtractor = new BeanWrapperFieldExtractor<>(); beanWrapperFieldExtractor.setNames(FF_COL_NAMES); return beanWrapperFieldExtractor; } }
package com.lab.test; import static org.junit.Assert.*; import org.junit.Assert; import org.junit.Test; import com.lab.bll.UserBLL; public class TestEntry { @Test public void loginTest() { String username = "java.gdb@gmail.com"; String password = "123456789"; UserBLL userBLL = new UserBLL(true); boolean result = userBLL.validUserNamePassword(username, password); Assert.assertEquals(result, true); } }
package com.parc.ccn.security.access; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedList; import java.util.TreeSet; import javax.xml.stream.XMLStreamException; import com.parc.ccn.Library; import com.parc.ccn.config.ConfigurationException; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.content.CollectionData; import com.parc.ccn.data.content.Link; import com.parc.ccn.data.content.LinkReference; import com.parc.ccn.data.security.PublisherPublicKeyDigest; import com.parc.ccn.data.util.CCNEncodableObject; import com.parc.ccn.library.CCNLibrary; import com.parc.ccn.library.profiles.VersioningProfile; public class ACL extends CollectionData { public static final String LABEL_READER = "r"; public static final String LABEL_WRITER = "rw"; public static final String LABEL_MANAGER = "rw+"; public static final String [] ROLE_LABELS = {LABEL_READER, LABEL_WRITER, LABEL_MANAGER}; // maintain a set of index structures. want to match on unversioned link target name only, // not label and potentially not signer if specified. Use a set class that can // allow us to specify a comparator; use one that ignores labels and versions on names. public static class SuperficialLinkComparator implements Comparator<LinkReference> { public int compare(LinkReference o1, LinkReference o2) { int result = 0; if (null != o1) { if (null == o2) { return 1; } } else if (null != o2) { return -1; } else { return 0; } result = VersioningProfile.versionRoot(o1.targetName()).compareTo(VersioningProfile.versionRoot(o2.targetName())); if (result != 0) return result; if (null != o1.targetAuthenticator()) { if (null != o2.targetAuthenticator()) { return o1.targetAuthenticator().compareTo(o2.targetAuthenticator()); } else { return 1; } } else if (null != o2.targetAuthenticator()) { return -1; } else { return 0; } } } static SuperficialLinkComparator _comparator = new SuperficialLinkComparator(); protected TreeSet<LinkReference> _readers = new TreeSet<LinkReference>(_comparator); protected TreeSet<LinkReference> _writers = new TreeSet<LinkReference>(_comparator); protected TreeSet<LinkReference> _managers = new TreeSet<LinkReference>(_comparator); public static class ACLObject extends CCNEncodableObject<ACL> { public ACLObject(ContentName name, ACL data, CCNLibrary library) throws ConfigurationException, IOException { super(ACL.class, name, data, library); } public ACLObject(ContentName name, PublisherPublicKeyDigest publisher, CCNLibrary library) throws ConfigurationException, IOException, XMLStreamException { super(ACL.class, name, publisher, library); } /** * Read constructor -- opens existing object. * @param type * @param name * @param library * @throws XMLStreamException * @throws IOException * @throws ClassNotFoundException */ public ACLObject(ContentName name, CCNLibrary library) throws ConfigurationException, IOException, XMLStreamException { super(ACL.class, name, (PublisherPublicKeyDigest)null, library); } public ACLObject(ContentObject firstBlock, CCNLibrary library) throws ConfigurationException, IOException, XMLStreamException { super(ACL.class, firstBlock, library); } public ACL acl() { return data(); } } public ACL() { super(); } public ACL(ArrayList<LinkReference> contents) { super(contents); if (!validate()) { throw new IllegalArgumentException("Invalid contents for ACL."); } } public boolean validLabel(LinkReference lr) { return LABEL_MANAGER.contains(lr.targetLabel()); } @Override public boolean validate() { if (!super.validate()) return false; for (LinkReference lr : contents()) { if ((null == lr.targetLabel()) || (!validLabel(lr))) { return false; } } return true; } public void addReader(LinkReference reader) { addLabeledLink(reader, LABEL_READER); } public void addWriter(LinkReference writer) { addLabeledLink(writer, LABEL_WRITER); } public void addManager(LinkReference manager) { addLabeledLink(manager, LABEL_MANAGER); } /** * If we are performing a set of simultaneous modifications to an ACL, we need to * handle them in parallel, in order to resolve interdependencies and derive the * minimal necessary changes to the underlying cryptographic data. * @param addReaders * @param removeReaders * @param addWriters * @param removeWriters * @param addManagers * @param removeManagers * @return We return a LinkedList<LinkReference> of the principals newly granted read * access on this ACL. If no individuals are granted read access, we return a 0-length * LinkedList. If any individuals are completely removed, requiring the caller to generate * a new node key or otherwise update cryptographic data, we return null. * (We could return the removed principals, but it's a little weird -- some people are * removed from a role and added to others. For now, we just return the thing we need * for our current implementation, which is whether anyone lost read access entirely.) */ public LinkedList<LinkReference> update(ArrayList<LinkReference> addReadersIn, ArrayList<LinkReference> removeReadersIn, ArrayList<LinkReference> addWritersIn, ArrayList<LinkReference> removeWritersIn, ArrayList<LinkReference> addManagersIn, ArrayList<LinkReference> removeManagersIn) { // Need copies we can modifiy, caller might want these back. TreeSet<LinkReference> addReaders = new TreeSet<LinkReference>(_comparator); addReaders.addAll(addReadersIn); TreeSet<LinkReference> removeReaders = new TreeSet<LinkReference>(_comparator); removeReaders.addAll(removeReadersIn); TreeSet<LinkReference> addWriters = new TreeSet<LinkReference>(_comparator); addWriters.addAll(addWritersIn); TreeSet<LinkReference> removeWriters = new TreeSet<LinkReference>(_comparator); removeWriters.addAll(removeWritersIn); TreeSet<LinkReference> addManagers = new TreeSet<LinkReference>(_comparator); addManagers.addAll(addManagersIn); TreeSet<LinkReference> removeManagers = new TreeSet<LinkReference>(_comparator); removeManagers.addAll(removeManagersIn); // Add then remove, so that removes override adds. Want to come up in the end with: // a) do we need a new node key // b) if not, who are the net new readers (requiring new node key blocks)? LinkedList<LinkReference> newReaders = new LinkedList<LinkReference>(); boolean newNodeKeyRequired = false; if (null != addManagers) { for (LinkReference manager : addManagers) { if (_managers.contains(manager)) { // if it's already a manager, do nothing continue; } // test if it's already a writer or a reader // if so, it's not a new reader // and remove it from those other roles // and add it to manager if (_writers.contains(manager)) { removeLabeledLink(manager, LABEL_WRITER); } else if (_readers.contains(manager)) { removeLabeledLink(manager, LABEL_READER); } else { // otherwise, add to new readers list newReaders.add(manager); } addManager(manager); } } if (null != addWriters) { for (LinkReference writer : addWriters) { // if it's already a writer, do nothing if (_writers.contains(writer)) { // if it's already a manager, do nothing continue; } // test if it's already a manager or a reader // if so, it's not a new reader if (_managers.contains(writer)) { // if it's already a manager, check if it's on the manager to be removed list // if it isn't, it's probably an error. just leave it as a manager. if (!removeManagers.contains(writer)) { continue; } // if it is, it's being downgraded to a writer. removeLabeledLink(writer, LABEL_MANAGER); } else if (_readers.contains(writer)) { // upgrading to a writer, remove reader entry removeLabeledLink(writer, LABEL_READER); } else { // otherwise, add to new readers list newReaders.add(writer); } addWriter(writer); } } if (null != addReaders) { for (LinkReference reader : addReaders) { // if it is already a reader, do nothing // Tricky -- if it's in the writers or manager list it will have a different label. // test if it's already a writer or a manager // if so, it's not a new reader // if it's already a manager or writer, check if it's on the manager or writer to be removed list // if it is, remove it as a manager or writer and add it as a reader // if not, just skip -- already better than a reader // otherwise, add to new readers list // if it's already a writer, do nothing if (_readers.contains(reader)) { // if it's already a reader, do nothing continue; } // test if it's already a manager or a writer // if so, it's not a new reader if (_managers.contains(reader)) { // if it's already a manager, check if it's on the manager to be removed list // if it isn't, it's probably an error. just leave it as a manager. if (!removeManagers.contains(reader)) { continue; } // if it is, it's being downgraded to a reader. removeLabeledLink(reader, LABEL_MANAGER); } else if (_writers.contains(reader)) { // if it's already a manager, check if it's on the manager to be removed list // if it isn't, it's probably an error. just leave it as a manager. if (!removeWriters.contains(reader)) { continue; } // if it is, it's being downgraded to a writer. removeLabeledLink(reader, LABEL_WRITER); } else { // otherwise, add to new readers list newReaders.add(reader); } addReader(reader); } } // We've already handled the cases of changed access, rather than revoking // all read rights; we've already removed those objects. // Changed access (retained read access) will show up as // requests to remove with no matching data. if (null != removeReaders) { for (LinkReference reader : removeReaders) { if (_readers.contains(reader)) { removeLabeledLink(reader, LABEL_READER); newNodeKeyRequired = true; } } } if (null != removeWriters) { for (LinkReference writer : removeWriters) { if (_writers.contains(writer)) { removeLabeledLink(writer, LABEL_WRITER); newNodeKeyRequired = true; } } } if (null != removeManagers) { for (LinkReference manager : removeManagers) { if (_managers.contains(manager)) { removeLabeledLink(manager, LABEL_MANAGER); newNodeKeyRequired = true; } } } // If we need a new node key, we don't care who the new readers are. // If we don't need a new node key, we do. // Want a dual return -- new node key required, // no new node key required but new readers and here they are, // and the really unusual case -- no new node key required and no new readers (no change). if (newNodeKeyRequired) { return null; } return newReaders; } protected void addLabeledLink(LinkReference link, String desiredLabel) { // assume that the reference has link's name and authentication information, // but possibly not the right label. Also assume that the link object might // be used in multiple places, and we can't modify it. if (((null == desiredLabel) && (null != link.targetLabel())) || (!desiredLabel.equals(link.targetLabel()))) { link = new LinkReference(link.targetName(), desiredLabel, link.targetAuthenticator()); } add(link); } protected void removeLabeledLink(LinkReference link, String desiredLabel) { // assume that the reference has link's name and authentication information, // but possibly not the right label. Also assume that the link object might // be used in multiple places, and we can't modify it. if (((null == desiredLabel) && (null != link.targetLabel())) || (!desiredLabel.equals(link.targetLabel()))) { link = new LinkReference(link.targetName(), desiredLabel, link.targetAuthenticator()); } remove(link); } @Override public void add(LinkReference link) { if (validLabel(link)) { super.add(link); index(link); } throw new IllegalArgumentException("Invalid label: " + link.targetLabel()); } @Override public void add(ArrayList<LinkReference> contents) { for (LinkReference link : contents) { add(link); // break them out for validation and indexing } } @Override public LinkReference remove(int i) { LinkReference link = _contents.remove(i); deindex(link); return link; } @Override public boolean remove(LinkReference content) { if (_contents.remove(content)) { deindex(content); return true; } return false; } @Override public boolean remove(Link content) { return remove(content.getReference()); } @Override public void removeAll() { super.removeAll(); clearIndices(); } protected void clearIndices() { _readers.clear(); _writers.clear(); _managers.clear(); } protected void index(LinkReference link) { if (LABEL_READER.equals(link.targetLabel())) { _readers.add(link); } else if (LABEL_WRITER.equals(link.targetLabel())) { _writers.add(link); } else if (LABEL_MANAGER.equals(link.targetLabel())) { _managers.add(link); } else { Library.logger().info("Unexpected: attempt to index ACL entry with unknown label: " + link.targetLabel()); } } protected void deindex(String label, LinkReference link) { if (LABEL_READER.equals(label)) { _readers.remove(link); } else if (LABEL_WRITER.equals(label)) { _writers.remove(link); } else if (LABEL_MANAGER.equals(label)) { _managers.remove(link); } else { Library.logger().info("Unexpected: attempt to index ACL entry with unknown label: " + label); } } protected void deindex(LinkReference link) { deindex(link.targetLabel(), link); } }
import java.util.Random; import bwapi.Color; import bwapi.Game; import bwapi.Player; import bwapi.Position; import bwapi.TilePosition; import bwapi.Unit; import bwapi.UnitCommandType; import bwapi.UnitType; public class Builder extends AbstractUnitEntity { private boolean reserved = false; private Base base; private Random r = new Random(); private EconomyService economyService; private Unit building = null; private UnitType typeToBuild = null; private TilePosition buildLocation; private int currentSpread = 0; public Builder(Unit unit, EconomyService economyService) { super(unit); this.economyService = economyService; } @Override public void onFrame(Game game, Player player) { if (unit.getPosition().getDistance(base.getBaseLocation().getPosition()) < 120) { if (unit.getLastCommand().getUnitCommandType() != UnitCommandType.Attack_Move) { for (Unit u : game.getUnitsInRadius(unit.getPosition(), 64)) { if (!u.isFlying() && u.getPlayer().equals(game.enemy())) { System.out.println("Enemey close attacking with builders"); unit.attack(unit.getPosition()); return; } } } } if (!reserved && base != null) { if (unit.isIdle() && base.getBaseLocation().getMinerals().size() > 0) { // TODO: if size is 0 transfer workers to another base Unit mineral = base.getBaseLocation().getMinerals().get(r.nextInt(base.getBaseLocation().getMinerals().size())); if (mineral != null) { unit.gather(mineral, false); } } } if (typeToBuild != null) { game.drawLineMap(unit.getPosition(), buildLocation.getPoint().toPosition(), Color.White); if (building != null) { game.drawTextScreen(300, 60, "Building created: " + typeToBuild); // if (building.isCompleted() || !unit.isConstructing()) { // this means it finished // constructing System.out.println("BUILDER: Completed: " + typeToBuild); boolean removeReserved = true; if (building.getType() == UnitType.Terran_Refinery) removeReserved = false; building = null; typeToBuild = null; currentSpread = 1; if (removeReserved) setReserved(false); return; } if (unit.isConstructing()) { building = unit.getBuildUnit(); return; } if (typeToBuild != UnitType.Terran_Command_Center) { // for command centers they just must be placed on the correct spot if (game.canBuildHere(buildLocation, typeToBuild)) { drawBox(game, buildLocation, typeToBuild.width(), typeToBuild.height()); } else { game.drawTextScreen(100, 120, "Can't find build location for " + typeToBuild); TilePosition newBuildLocation = game.getBuildLocation(typeToBuild, buildLocation, currentSpread); // first try if we can't find a better location nearby if (!newBuildLocation.isValid()) { // still invalid then pick a completely new build location System.out.println("Spread:" + currentSpread + " type: " + typeToBuild + " position-x: " + buildLocation.toPosition().getX() + " y: " + newBuildLocation.toPosition().getY()); currentSpread++; if (currentSpread > 500) currentSpread = 0; return; } else { System.out.println("Spread:" + currentSpread + " type: " + typeToBuild + " position-x: " + buildLocation.toPosition().getX() + " y: " + buildLocation.toPosition().getY()); buildLocation = newBuildLocation; } } } // if he is not constructing yet give the construct order if (!unit.isConstructing() && economyService.getMinerals() >= typeToBuild.mineralPrice()) { unit.build(typeToBuild, buildLocation); } // send him to build position if (economyService.getMinerals() >= typeToBuild.mineralPrice() - (typeToBuild.mineralPrice() / 4) && !unit.isConstructing() && buildLocation.toPosition().getDistance(unit.getPosition()) > -(TilePosition.SIZE_IN_PIXELS * 3) + 16) { Position dest = MathUtil.moveToLocation(unit.getPosition(), buildLocation.toPosition(), -(TilePosition.SIZE_IN_PIXELS * 3)); game.drawCircleMap(dest, 5, Color.Yellow); unit.move(dest); } } } public void assignToBase(Base base) { this.base = base; } /** * Reserves itsef and tries to build a building at position * * @param unitType * @param position * @param minerals */ public void build(UnitType unitType, TilePosition position) { building = null; typeToBuild = unitType; buildLocation = position; economyService.reserveMinerales(unitType.mineralPrice()); currentSpread = 1; setReserved(true); } public boolean isReserved() { return reserved; } public void setReserved(boolean reserved) { this.reserved = reserved; } @Override public void onEntityCreate(UnitEntity entity) { Unit createdUnit = entity.getUnit(); if (createdUnit.getType().isBuilding() && (unit.equals(createdUnit.getBuildUnit()))) { // if (createdUnit.getType().equals(typeToBuild)) { System.out.println("BUILDER: Created " + createdUnit.getType()); building = createdUnit; economyService.freeMinerals(typeToBuild.mineralPrice()); } } private void drawBox(Game game, TilePosition tp, int sizeX, int sizeY) { game.drawBoxMap(tp.toPosition(), new Position(tp.toPosition().getX() + sizeX, tp.toPosition().getY() + sizeY), Color.White); } @Override public void onEntityDestroyed(UnitEntity unit) { if (unit.getUnit().equals(this.unit)) { if (building == null) { build(typeToBuild, buildLocation); } else { Builder freeBuilder = base.getFreeBuilder(); freeBuilder.typeToBuild = typeToBuild; freeBuilder.buildLocation = buildLocation; freeBuilder.currentSpread = 1; freeBuilder.building = building; freeBuilder.setReserved(true); freeBuilder.getUnit().stop(); freeBuilder.getUnit().rightClick(building); } } } }
package me.xdrop.jrand.annotation.processing; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import javax.annotation.Generated; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Types; import java.util.Arrays; import java.util.List; import static me.xdrop.jrand.annotation.processing.ProcessorRepository.CLASS_SUFFIX; public class ForkClassGenerator { private static String GENERATOR_ID = "me.xdrop.jrand.annotation.processing.ForkClassGenerator"; private ProcessingEnvironment processingEnv; public ForkClassGenerator(ProcessingEnvironment processingEnv) { this.processingEnv = processingEnv; } /** * Create a {@code fork()} method for the given class. Fork will attempt to return a clone of this * generator by cloning lists, maps, primitive types as well as other generators. * While forking any other data structure is subject to accidental mutation. * * @param generator The source generator class (eg. PhoneGenerator) * @param pkg The package of the generator class * @param variableElements A list of other variables in that class * @return A generated {@code fork()} method */ public MethodSpec createForkMethod(TypeElement generator, String pkg, List<VariableElement> variableElements) { AnnotationSpec generated = AnnotationSpec.builder(Generated.class) .addMember("value", "$S", GENERATOR_ID) .build(); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("fork") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(generated) .returns(ClassName.get(generator)); StringBuilder fields = new StringBuilder(); fields.append("\n"); TypeMirror listElement = processingEnv.getElementUtils().getTypeElement("java.util.List").asType(); TypeMirror mapElement = processingEnv.getElementUtils().getTypeElement("java.util.Map").asType(); TypeMirror generatorSuper = generator.getSuperclass(); Types typeUtils = processingEnv.getTypeUtils(); for (VariableElement variable : variableElements) { String varName = variable.getSimpleName().toString(); if (!variable.getModifiers().contains(Modifier.FINAL)){ if (typeUtils.isSubtype(variable.asType(), typeUtils.erasure(listElement))) { fields.append("new java.util.ArrayList<>("); fields.append(varName); fields.append(")"); } else if (typeUtils.isAssignable(variable.asType(), typeUtils.erasure(mapElement))) { fields.append("new java.util.HashMap<>("); fields.append(varName); fields.append(")"); } else if (variable.asType().getKind().isPrimitive()) { fields.append(varName); } else if (typeUtils.isAssignable(variable.asType(), typeUtils.erasure(generatorSuper))) { fields.append("(("); fields.append(variable.asType()).append(CLASS_SUFFIX); fields.append(')'); fields.append(varName); fields.append(')'); fields.append(".fork()"); } else { fields.append(varName); } fields.append(",\n"); } } String fieldString = ""; if (fields.length() > 1) { fieldString = fields.substring(0, fields.length() - 2); } ClassName generatedClassName = ClassName.get(pkg, generator.getSimpleName().toString().concat(CLASS_SUFFIX)); methodBuilder.addStatement("return new $T($L)", generatedClassName, fieldString); return methodBuilder.build(); } /** * Create a simple copy-constructor made from the given list of fields. The constructor * will blindly assign all fields given to the values given to the constructor. * * @param variableElements The list of fields which this constructor will assign to * @return The generated constructor */ public MethodSpec createCopyConstructor(List<VariableElement> variableElements) { AnnotationSpec generated = AnnotationSpec.builder(Generated.class) .addMember("value", "$S", GENERATOR_ID) .build(); MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addAnnotation(generated); variableElements.forEach(varEl -> { if (!varEl.getModifiers().contains(Modifier.FINAL)) { String identifier = varEl.getSimpleName().toString(); constructor.addParameter(ClassName.get(varEl.asType()), identifier); constructor.addStatement("this.$N = $N", identifier, identifier); } }); return constructor.build(); } /** * Generate the {@code fork} and constructor methods. See {@link ForkClassGenerator#createCopyConstructor(List)} * and {@link ForkClassGenerator#createForkMethod(TypeElement, String, List)} * * @param sourceClass The source class for which to generate these for * @return A list containing the fork method at index [0] and the constructor at index [1] */ public List<MethodSpec> getForkAndCloneMethods (TypeElement sourceClass) { List<VariableElement> variableElements = ElementFilter.fieldsIn(sourceClass.getEnclosedElements()); String pkg = processingEnv.getElementUtils().getPackageOf(sourceClass).toString(); MethodSpec forkMethod = createForkMethod(sourceClass, pkg, variableElements); MethodSpec copyConstructor = createCopyConstructor(variableElements); return Arrays.asList(forkMethod, copyConstructor); } }
package com.konkerlabs.platform.registry.business.services; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.konkerlabs.platform.registry.business.exceptions.BusinessException; import com.konkerlabs.platform.registry.business.model.User; import com.konkerlabs.platform.registry.business.repositories.PasswordBlacklistRepository; import com.konkerlabs.platform.registry.business.repositories.UserRepository; import com.konkerlabs.platform.registry.business.services.api.ServiceResponse; import com.konkerlabs.platform.registry.business.services.api.ServiceResponseBuilder; import com.konkerlabs.platform.registry.business.services.api.UploadService; import com.konkerlabs.platform.registry.business.services.api.UserService; import com.konkerlabs.platform.registry.config.PasswordUserConfig; import com.konkerlabs.platform.security.managers.PasswordManager; @Service public class UserServiceImpl implements UserService { private Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserRepository userRepository; @Autowired private UploadService uploadService; @Autowired private PasswordBlacklistRepository passwordBlacklistRepository; @Autowired private PasswordUserConfig passwordUserConfig; private PasswordManager passwordManager; public UserServiceImpl() { passwordManager = new PasswordManager(); } @Override public ServiceResponse<User> save(User user, String oldPassword, String newPassword, String newPasswordConfirmation) { User fromStorage = userRepository.findOne(user.getEmail()); if (!Optional.ofNullable(fromStorage).isPresent() || !Optional.ofNullable(user.getEmail()).isPresent() || !user.getEmail().equals(fromStorage.getEmail())) { LOG.debug(Validations.INVALID_USER_EMAIL.getCode(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); return ServiceResponseBuilder.<User>error() .withMessage(Validations.INVALID_USER_EMAIL.getCode()) .build(); } if (!Optional.ofNullable(oldPassword).isPresent() || !Optional.ofNullable(newPassword).isPresent() || !Optional.ofNullable(newPasswordConfirmation).isPresent()) { LOG.debug(Validations.INVALID_PASSWORD_CONFIRMATION.getCode(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); return ServiceResponseBuilder.<User>error() .withMessage(Validations.INVALID_PASSWORD_CONFIRMATION.getCode()) .build(); } if (!StringUtils.isEmpty(newPassword)) { try { validateOldPassword(oldPassword, fromStorage); } catch (BusinessException e) { return ServiceResponseBuilder.<User>error() .withMessage(e.getMessage()) .build(); } } return save(user, newPassword, newPasswordConfirmation); } @Override public ServiceResponse<User> save(User user, String newPassword, String newPasswordConfirmation) { User fromStorage = userRepository.findOne(user.getEmail()); if (!Optional.ofNullable(fromStorage).isPresent() || !Optional.ofNullable(user.getEmail()).isPresent() || !user.getEmail().equals(fromStorage.getEmail())) { return ServiceResponseBuilder.<User>error() .withMessage(Validations.INVALID_USER_EMAIL.getCode()) .build(); } if (!newPassword.equals(newPasswordConfirmation)) { LOG.debug(Validations.INVALID_PASSWORD_CONFIRMATION.getCode(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); return ServiceResponseBuilder.<User>error() .withMessage(Validations.INVALID_PASSWORD_CONFIRMATION.getCode()) .build(); } if (!Optional.ofNullable(user).isPresent()) { LOG.debug(Validations.INVALID_USER_DETAILS.getCode(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); return ServiceResponseBuilder.<User>error() .withMessage(Validations.INVALID_USER_DETAILS.getCode()) .build(); } if (!Optional.ofNullable(user.getName()).isPresent()) { LOG.debug(Validations.INVALID_USER_NAME.getCode(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); return ServiceResponseBuilder.<User>error() .withMessage(Validations.INVALID_USER_NAME.getCode()) .build(); } if (!Optional.ofNullable(user.getDateFormat()).isPresent()) { LOG.debug(Validations.INVALID_USER_PREFERENCE_DATEFORMAT.getCode(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); return ServiceResponseBuilder.<User>error() .withMessage(Validations.INVALID_USER_PREFERENCE_DATEFORMAT.getCode()) .build(); } if (!Optional.ofNullable(user.getZoneId()).isPresent()) { LOG.debug(Validations.INVALID_USER_PREFERENCE_LOCALE.getCode(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); return ServiceResponseBuilder.<User>error() .withMessage(Validations.INVALID_USER_PREFERENCE_LOCALE.getCode()) .build(); } if (!Optional.ofNullable(user.getLanguage()).isPresent()) { LOG.debug(Validations.INVALID_USER_PREFERENCE_LANGUAGE.getCode(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); return ServiceResponseBuilder.<User>error() .withMessage(Validations.INVALID_USER_PREFERENCE_LANGUAGE.getCode()) .build(); } if(!StringUtils.isEmpty(user.getAvatar()) && user.getAvatar().contains("data:image")) { ServiceResponse<String> response = uploadService.uploadBase64Img(user.getAvatar(), true); if(!response.getStatus().equals(ServiceResponse.Status.OK)){ return ServiceResponseBuilder.<User>error() .withMessages(response.getResponseMessages()) .build(); } user.setAvatar(response.getResult()); } else { user.setAvatar(fromStorage.getAvatar()); } if (!StringUtils.isEmpty(newPassword)) { try { validatePassword(user, fromStorage, newPassword, newPasswordConfirmation); } catch (BusinessException e) { return ServiceResponseBuilder.<User>error() .withMessage(e.getMessage()) .build(); } } Optional.ofNullable(newPasswordConfirmation).ifPresent(password -> { if (!StringUtils.isEmpty(newPasswordConfirmation)) { try { user.setPassword(encodePassword(password)); } catch (Exception e) { LOG.error("Error encoding password for user " + fromStorage.getEmail(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); } } }); if (Optional.ofNullable(user.getPassword()).isPresent() && !user.getPassword().startsWith(PasswordManager.QUALIFIER)) { LOG.debug(Errors.ERROR_SAVE_USER.getCode(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); return ServiceResponseBuilder.<User>error() .withMessage(Errors.ERROR_SAVE_USER.getCode()).build(); } try { fillFrom(user, fromStorage); userRepository.save(fromStorage); Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()) .ifPresent(authentication -> { User principal = (User) Optional.ofNullable(authentication.getPrincipal()) .filter(p -> !p.equals("anonymousUser")).orElse(User.builder().build()); fillFrom(fromStorage, principal); }); return ServiceResponseBuilder.<User>ok().withResult(fromStorage).build(); } catch (Exception e) { LOG.debug(Errors.ERROR_SAVE_USER.getCode(), fromStorage.getTenant().toURI(), fromStorage.getTenant().getLogLevel(), fromStorage); return ServiceResponseBuilder.<User>error() .withMessage(Errors.ERROR_SAVE_USER.getCode()).build(); } } /** * Fill new values from form * * @param form * @param storage */ private void fillFrom(User form, User storage) { storage.setLanguage(form.getLanguage()); storage.setZoneId(form.getZoneId()); storage.setAvatar(form.getAvatar()); storage.setDateFormat(form.getDateFormat()); storage.setPassword(!StringUtils.isEmpty(form.getPassword()) ? form.getPassword() : storage.getPassword()); storage.setName(form.getName()); storage.setPhone(form.getPhone()); storage.setNotificationViaEmail(form.isNotificationViaEmail()); } /** * Encode the password * * @param password * @return String encoded password * @throws Exception */ private String encodePassword(String password) throws Exception { if (!Optional.ofNullable(passwordManager).isPresent()) { passwordManager = new PasswordManager(); } return passwordManager.createHash( password, Optional.of(passwordUserConfig.getIterations()) ); } /** * Validate password change rules * * @param fromForm * @param fromStorage * @throws BusinessException */ private void validatePassword(User fromForm, User fromStorage, String newPassword, String newPasswordConfirmation ) throws BusinessException { validatePasswordConfirmation(newPassword, newPasswordConfirmation); validatePasswordLenght(newPasswordConfirmation); validatePasswordPattern(fromForm.getUsername(), newPasswordConfirmation); validatePasswordBlackList(newPasswordConfirmation); } /** * Validate informed oldPassword compability with stored password * * @param oldPassword * @throws BusinessException */ private void validateOldPassword(String oldPassword, User fromStorage) throws BusinessException { if (!Optional.ofNullable(passwordManager).isPresent()) { passwordManager = new PasswordManager(); } if (!Optional.ofNullable(fromStorage).isPresent()) { throw new BusinessException(Validations.INVALID_USER_DETAILS.getCode()); } try { if (!passwordManager.validatePassword(oldPassword, fromStorage.getPassword())) { throw new BusinessException(Validations.INVALID_PASSWORD_INVALID.getCode()); } } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { throw new BusinessException(Validations.INVALID_PASSWORD_USER_DATA.getCode()); } } private void validatePasswordConfirmation(String newPassword, String newPasswordConfirmation) throws BusinessException { if (!newPassword.equals(newPasswordConfirmation)) { throw new BusinessException(Validations.INVALID_PASSWORD_CONFIRMATION.getCode()); } } private void validatePasswordLenght(String password) throws BusinessException { if (password.length() < 12) { throw new BusinessException(Validations.INVALID_PASSWORD_LENGTH.getCode()); } } private void validatePasswordPattern(String username, String password) throws BusinessException { if (password.equalsIgnoreCase(username)) { throw new BusinessException(Validations.INVALID_PASSWORD_USER_DATA.getCode()); } } private void validatePasswordBlackList(String password) throws BusinessException { User.PasswordBlacklist matches = passwordBlacklistRepository.findOne(password); if (Optional.ofNullable(matches).isPresent()) { throw new BusinessException(Validations.INVALID_PASSWORD_BLACKLISTED.getCode()); } } @Override public ServiceResponse<User> findByEmail(String email) { if (!Optional.ofNullable(email).isPresent()) { return ServiceResponseBuilder.<User>error() .withMessage(Validations.NO_EXIST_USER.getCode()).build(); } User user = userRepository.findOne(email); return ServiceResponseBuilder.<User>ok().withResult(user).build(); } }
package liquibase.statementexecute; import liquibase.changelog.ChangeSet; import liquibase.database.Database; import liquibase.database.core.*; import liquibase.statement.SqlStatement; import liquibase.statement.core.CreateDatabaseChangeLogTableStatement; import liquibase.statement.core.MarkChangeSetRanStatement; import liquibase.util.LiquibaseUtil; import org.junit.Test; import java.util.Arrays; import java.util.List; public class MarkChangeSetRanExecuteTest extends AbstractExecuteTest { @Override protected List<? extends SqlStatement> setupStatements(Database database) { return Arrays.asList(new CreateDatabaseChangeLogTableStatement()); } @Test public void generateSql_insert() throws Exception { this.statementUnderTest = new MarkChangeSetRanStatement(new ChangeSet("a", "b", false, false, "c", "e", "f", null), ChangeSet.ExecType.EXECUTED); String version = LiquibaseUtil.getBuildVersion().replaceAll("SNAPSHOT", "SNP"); assertCorrect("insert into [databasechangelog] ([id], [author], [filename], [dateexecuted], [orderexecuted]," + " [md5sum], [description], [comments], [exectype], [contexts], [labels], [liquibase], " + "[deployment_id]) values ('a', 'b', 'c', getdate(), 1, '7:d41d8cd98f00b204e9800998ecf8427e', 'empty'," + " '', 'executed', 'e', null, '"+version+"', null)", MSSQLDatabase.class); assertCorrect("insert into databasechangelog (id, author, filename, dateexecuted, orderexecuted, md5sum, description, comments, exectype, liquibase) values ('a', 'b', 'c', systimestamp, 1, '7:d41d8cd98f00b204e9800998ecf8427e', 'empty', '', 'executed', '"+version+"')",OracleDatabase.class); assertCorrect("insert into [databasechangelog] ([id], [author], [filename], [dateexecuted], [orderexecuted], [md5sum], [description], [comments], [exectype], [liquibase]) values ('a', 'b', 'c', getdate(), 1, '7:d41d8cd98f00b204e9800998ecf8427e', 'empty', '', 'executed', '"+version+"')",SybaseDatabase.class); assertCorrect("insert into databasechangelog (id, author, filename, dateexecuted, orderexecuted, md5sum, description, comments, exectype, liquibase) values ('a', 'b', 'c', current year to fraction(5), 1, '7:d41d8cd98f00b204e9800998ecf8427e', 'empty', '', 'executed', '"+version+"')",InformixDatabase.class); assertCorrect("insert into databasechangelog (id, author, filename, dateexecuted, orderexecuted, md5sum, description, comments, exectype, liquibase) values ('a', 'b', 'c', current timestamp, 1, '7:d41d8cd98f00b204e9800998ecf8427e', 'empty', '', 'executed', '"+version+"')",DB2Database.class); assertCorrect("insert into databasechangelog (id, author, filename, dateexecuted, orderexecuted, md5sum, description, comments, exectype, liquibase) values ('a', 'b', 'c', current_timestamp, 1, '7:d41d8cd98f00b204e9800998ecf8427e', 'empty', '', 'executed', '"+version+"')",FirebirdDatabase.class, DerbyDatabase.class); assertCorrect("insert into databasechangelog (id, author, filename, dateexecuted, orderexecuted, md5sum, description, comments, exectype, liquibase) values ('a', 'b', 'c', now, 1, '7:d41d8cd98f00b204e9800998ecf8427e', 'empty', '', 'executed', '"+version+"')",HsqlDatabase.class); assertCorrect("insert into databasechangelog (id, author, filename, dateexecuted, orderexecuted, md5sum, description, comments, exectype, liquibase) values ('a', 'b', 'c', now(), 1, '7:d41d8cd98f00b204e9800998ecf8427e', 'empty', '', 'executed', '"+version+"')",SybaseASADatabase.class); assertCorrect("insert into databasechangelog (id, author, filename, dateexecuted, orderexecuted, md5sum, description, comments, exectype, liquibase) values ('a', 'b', 'c', now(), 1, '7:d41d8cd98f00b204e9800998ecf8427e', 'empty', '', 'executed', '"+version+"')",MySQLDatabase.class,PostgresDatabase.class,H2Database.class); assertCorrectOnRest("insert into databasechangelog (id, author, filename, dateexecuted, orderexecuted, md5sum, description, comments, exectype, liquibase) values ('a', 'b', 'c', current timestamp, 1, '7:d41d8cd98f00b204e9800998ecf8427e', 'empty', '', 'executed', '"+version+"')"); } @Test public void generateSql_update() throws Exception { this.statementUnderTest = new MarkChangeSetRanStatement(new ChangeSet("a", "b", false, false, "c", "e", "f", null), ChangeSet.ExecType.RERAN); assertCorrect("update [databasechangelog] set [dateexecuted] = getdate(), [deployment_id] = null, [exectype] = 'reran', [md5sum] = '7:d41d8cd98f00b204e9800998ecf8427e', [orderexecuted] = 2 where [id] = 'a' and [author] = 'b' and [filename] = 'c'", MSSQLDatabase.class); assertCorrect("update [databasechangelog] set [dateexecuted] = SYSTIMESTAMP, [exectype] = 'reran', [md5sum] = '7:d41d8cd98f00b204e9800998ecf8427e' where id='a' and author='b' and filename='c'", OracleDatabase.class); assertCorrect("update [databasechangelog] set [dateexecuted] = getdate(), [exectype] = 'reran', [md5sum] = '7:d41d8cd98f00b204e9800998ecf8427e' where id='a' and author='b' and filename='c'", SybaseDatabase.class); assertCorrect("update [databasechangelog] set [dateexecuted] = current year to fraction(5), [exectype] = 'reran', [md5sum] = '7:d41d8cd98f00b204e9800998ecf8427e' where id='a' and author='b' and filename='c'", InformixDatabase.class); assertCorrect("update [databasechangelog] set [dateexecuted] = current timestamp, [exectype] = 'reran', [md5sum] = '7:d41d8cd98f00b204e9800998ecf8427e' where id='a' and author='b' and filename='c'", DB2Database.class); assertCorrect("update [databasechangelog] set [dateexecuted] = current_timestamp, [exectype] = 'reran', [md5sum] = '7:d41d8cd98f00b204e9800998ecf8427e' where id='a' and author='b' and filename='c'", FirebirdDatabase.class, DerbyDatabase.class); assertCorrect("update [databasechangelog] set [dateexecuted] = NOW(), [exectype] = 'reran', [md5sum] = '7:d41d8cd98f00b204e9800998ecf8427e' where id='a' and author='b' and filename='c'", SybaseASADatabase.class); assertCorrect("update [databasechangelog] set [dateexecuted] = NOW(), [exectype] = 'reran', [md5sum] = '7:d41d8cd98f00b204e9800998ecf8427e' where id='a' and author='b' and filename='c'", MySQLDatabase.class,HsqlDatabase.class,PostgresDatabase.class,H2Database.class); assertCorrectOnRest("update [databasechangelog] set [dateexecuted] = NOW(), [exectype] = 'reran', [md5sum] = '7:d41d8cd98f00b204e9800998ecf8427e' where id='a' and author='b' and filename='c'"); } }
package org.terracotta.management.model.capabilities.descriptors; import java.io.Serializable; import java.util.AbstractMap; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; /** * @author Mathieu Carbou */ public class Settings extends AbstractMap<String, Object> implements Descriptor, Serializable { private static final long serialVersionUID = 1; private final Map<String, Object> map = new LinkedHashMap<String, Object>(); public Settings() { } public Settings(Map<String, String> map) { this.map.putAll(map); } public Settings(Settings settings) { this.map.putAll(settings.map); } @Override public Set<Entry<String, Object>> entrySet() { return map.entrySet(); } public <T> T get(String key, Class<T> type) { return type.cast(map.get(key)); } public <T> T getOrDefault(String key, Class<T> type, T def) { T o = get(key, type); return o == null ? def : o; } public String getString(String key) { return get(key, String.class); } public String getStringOrDefault(String key, String def) { return getOrDefault(key, String.class, def); } public Number getNumber(String key) { return get(key, Number.class); } public Number getNumberOrDefault(String key, Number def) { return getOrDefault(key, Number.class, def); } public boolean getBool(String key) { return get(key, Boolean.class); } public boolean getBoolOrDefault(String key, boolean def) { return getOrDefault(key, Boolean.class, def); } public String[] getStrings(String key) { return get(key, String[].class); } public String[] getStringsOrDefault(String key, String... def) { return getOrDefault(key, String[].class, def); } public Settings set(String key, Settings settings) { map.put(key, settings); return this; } public Settings set(String key, String value) { map.put(key, value); return this; } public Settings set(String key, Number value) { map.put(key, value); return this; } public Settings set(String key, boolean value) { map.put(key, value); return this; } public Settings set(String key, Enum<?> value) { return set(key, value == null ? null : value.name()); } public Settings set(String key, Class<?> value) { return set(key, value == null ? null : value.getName()); } public Settings set(String key, String... items) { map.put(key, items); return this; } public <T> Settings with(String key, T object, Builder<T> builder) { Settings child = new Settings(); map.put(key, child); builder.build(child, object); return this; } public <T> Settings withEach(String containerKey, Collection<T> list, Builder<T> builder) { Settings container = new Settings(); map.put(containerKey, container); int i = 0; for (T o : list) { Settings child = new Settings(); container.set(String.valueOf(i++), child); builder.build(child, o); } return this; } public <V> Settings withEach(String containerKey, Map<String, V> map, Builder<V> builder) { Settings container = new Settings(); this.map.put(containerKey, container); for (Map.Entry<String, V> entry : map.entrySet()) { Settings child = new Settings(); container.set(entry.getKey(), child); builder.build(child, entry.getValue()); } return this; } public interface Builder<T> { void build(Settings settings, T object); } }
package me.calebjones.spacelaunchnow.ui.launchdetail.fragments; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import me.calebjones.spacelaunchnow.R; import me.calebjones.spacelaunchnow.common.BaseFragment; import me.calebjones.spacelaunchnow.content.database.ListPreferences; import me.calebjones.spacelaunchnow.data.models.VehicleDetails; import me.calebjones.spacelaunchnow.data.models.Launch; import me.calebjones.spacelaunchnow.ui.launchdetail.activity.LaunchDetailActivity; import me.calebjones.spacelaunchnow.utils.Analytics; import me.calebjones.spacelaunchnow.utils.Utils; import timber.log.Timber; public class AgencyDetailFragment extends BaseFragment { private SharedPreferences sharedPref; private static ListPreferences sharedPreference; private Context context; public static Launch detailLaunch; private VehicleDetails launchVehicle; @BindView(R.id.mission_one) LinearLayout mission_one; @BindView(R.id.mission_two) LinearLayout mission_two; @BindView(R.id.agency_one) LinearLayout launch_one; @BindView(R.id.agency_two) LinearLayout launch_two; @BindView(R.id.mission_agency_type) TextView mission_agency_type; @BindView(R.id.mission_vehicle_agency_one) TextView mission_agency_one; @BindView(R.id.mission_agency_type_one) TextView mission_agency_type_one; @BindView(R.id.mission_infoButton_one) TextView mission_infoButton_one; @BindView(R.id.mission_wikiButton_one) TextView mission_wikiButton_one; @BindView(R.id.mission_vehicle_agency_two) TextView mission_agency_two; @BindView(R.id.mission_agency_type_two) TextView mission_agency_type_two; @BindView(R.id.mission_infoButton_two) TextView mission_infoButton_two; @BindView(R.id.mission_wikiButton_two) TextView mission_wikiButton_two; @BindView(R.id.launch_agency_type) TextView launch_agency_type; @BindView(R.id.launch_vehicle_agency_one) TextView launch_vehicle_agency_one; @BindView(R.id.launch_agency_type_one) TextView launch_agency_type_one; @BindView(R.id.infoButton_one) TextView infoButton_one; @BindView(R.id.wikiButton_one) TextView wikiButton_one; @BindView(R.id.launch_vehicle_agency_two) TextView launch_vehicle_agency_two; @BindView(R.id.launch_agency_type_two) TextView launch_agency_type_two; @BindView(R.id.infoButton_two) TextView infoButton_two; @BindView(R.id.wikiButton_two) TextView wikiButton_two; @BindView(R.id.launch_agency_summary_one) TextView launch_agency_summary_one; @BindView(R.id.launch_agency_summary_two) TextView launch_agency_summary_two; @BindView(R.id.mission_agency_summary_one) TextView mission_agency_summary_one; @BindView(R.id.mission_agency_summary_two) TextView mission_agency_summary_two; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view; this.sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext()); this.context = getContext(); setScreenName("Agency Detail Fragment"); sharedPreference = ListPreferences.getInstance(this.context); view = inflater.inflate(R.layout.detail_launch_agency, container, false); ButterKnife.bind(this, view); Timber.v("Creating views..."); if (detailLaunch != null){ setUpViews(detailLaunch); } return view; } @Override public void onResume() { if (detailLaunch != null) { setUpViews(detailLaunch); } super.onResume(); } public void setLaunch(Launch launch) { detailLaunch = launch; if (isVisible()) { setUpViews(launch); } } private void setUpViews(Launch launch){ detailLaunch = launch; Timber.v("Setting up views..."); int pads = detailLaunch.getLocation().getPads().size(); int mission_agencies= 0; if (pads > 0){ mission_agencies = detailLaunch.getLocation().getPads().get(0).getAgencies().size(); } int vehicle_agencies = detailLaunch.getRocket().getAgencies().size(); if (mission_agencies >= 2){ setTwoMissionAgencies(); } else if (mission_agencies == 1){ setOneMissionAgencies(); } else { setNoMissionAgencies(); } if (vehicle_agencies >= 2){ setTwoVehicleAgencies(); } else if (vehicle_agencies == 1){ setOneVehicleAgencies(); } else { setNoVehicleAgencies(); } } private void setNoMissionAgencies() { mission_agency_type.setVisibility(View.VISIBLE); mission_one.setVisibility(View.GONE); mission_two.setVisibility(View.GONE); } private void setOneMissionAgencies() { mission_agency_type.setVisibility(View.VISIBLE); mission_agency_type.setText(detailLaunch.getLocation().getPads().get(0).getName()); String agencyTypeOne = getAgencyType(detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getType()); String agencyNameOne = detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getName(); String agencyAbbrevOne = detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getAbbrev(); checkLaunchSummary(agencyAbbrevOne, mission_agency_summary_one); mission_one.setVisibility(View.VISIBLE); mission_two.setVisibility(View.GONE); mission_agency_one.setText(String.format("%s (%s)", agencyNameOne, agencyAbbrevOne)); mission_agency_type_one.setText("Type: " + agencyTypeOne); if (detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getWikiURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getWikiURL())); mission_wikiButton_one.setVisibility(View.VISIBLE); mission_wikiButton_one.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getWikiURL()); Analytics.from(getActivity()).sendButtonClickedWithURL("Mission Wiki", detailLaunch.getName(), detailLaunch.getLocation() .getPads() .get(0) .getAgencies() .get(0) .getWikiURL()); } }); } else { mission_wikiButton_one.setVisibility(View.GONE); } if (detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getInfoURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getLocation() .getPads().get(0).getAgencies().get(0).getInfoURL())); mission_infoButton_one.setVisibility(View.VISIBLE); mission_infoButton_one.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getLocation().getPads() .get(0).getAgencies().get(0).getInfoURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Info", detailLaunch.getName(), detailLaunch.getLocation().getPads() .get(0).getAgencies().get(0).getInfoURL() ); } }); } else { mission_infoButton_one.setVisibility(View.GONE); } } private void setTwoMissionAgencies() { mission_agency_type.setVisibility(View.VISIBLE); mission_agency_type.setText(detailLaunch.getLocation().getPads().get(0).getName()); String agencyTypeOne = getAgencyType(detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getType()); String agencyNameOne = detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getName(); String agencyAbbrevOne = detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getAbbrev(); String agencyTypeTwo = getAgencyType(detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getType()); String agencyNameTwo = detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getName(); String agencyAbbrevTwo = detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getAbbrev(); checkLaunchSummary(agencyAbbrevOne, mission_agency_summary_one); checkLaunchSummary(agencyAbbrevTwo, mission_agency_summary_two); mission_one.setVisibility(View.VISIBLE); mission_two.setVisibility(View.VISIBLE); mission_agency_type_one.setText(String.format("Type: %s", agencyTypeOne)); mission_agency_type_two.setText(String.format("Type: %s", agencyTypeTwo)); mission_agency_one.setText(String.format("%s (%s)", agencyNameOne, agencyAbbrevOne)); mission_agency_two.setText(String.format("%s (%s)", agencyNameTwo, agencyAbbrevTwo)); if (detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getWikiURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getWikiURL())); mission_wikiButton_one.setVisibility(View.VISIBLE); mission_wikiButton_one.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity,context, detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getWikiURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Wiki", detailLaunch.getName(), detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getWikiURL()); } }); } else { mission_wikiButton_one.setVisibility(View.GONE); } if (detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getInfoURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getInfoURL())); mission_infoButton_one.setVisibility(View.VISIBLE); mission_infoButton_one.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getInfoURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Info", detailLaunch.getName(), detailLaunch.getLocation().getPads().get(0).getAgencies().get(0).getInfoURL()); } }); } else { mission_infoButton_one.setVisibility(View.GONE); } if (detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getWikiURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getWikiURL())); mission_wikiButton_two.setVisibility(View.VISIBLE); mission_wikiButton_two.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getWikiURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Wiki", detailLaunch.getName(), detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getWikiURL()); } }); } else { mission_wikiButton_two.setVisibility(View.GONE); } if (detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getInfoURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getInfoURL())); mission_infoButton_two.setVisibility(View.VISIBLE); mission_infoButton_two.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getInfoURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Info", detailLaunch.getName(), detailLaunch.getLocation().getPads().get(0).getAgencies().get(1).getInfoURL()); } }); } else { mission_infoButton_two.setVisibility(View.GONE); } } private void setNoVehicleAgencies() { launch_agency_type.setVisibility(View.VISIBLE); launch_one.setVisibility(View.GONE); launch_two.setVisibility(View.GONE); } private void setOneVehicleAgencies() { launch_agency_type.setVisibility(View.VISIBLE); launch_agency_type.setText(detailLaunch.getRocket().getName()); String countryCode = detailLaunch.getRocket().getAgencies().get(0).getCountryCode(); String agencyType = getAgencyType(detailLaunch.getRocket().getAgencies().get(0).getType()); String agencyName = detailLaunch.getRocket().getAgencies().get(0).getName(); String agencyAbbrev = detailLaunch.getRocket().getAgencies().get(0).getAbbrev(); checkLaunchSummary(agencyAbbrev, launch_agency_summary_one); if (countryCode.length() > 10){ countryCode = countryCode.substring(0,3) + ", "+ countryCode.substring(4,7) + ", "+ countryCode.substring(7,10) + "..."; agencyType = agencyType + " | Multinational"; } else if (countryCode.length() > 4 && countryCode.length() < 10){ countryCode = countryCode.substring(0,3); } launch_one.setVisibility(View.VISIBLE); launch_two.setVisibility(View.GONE); launch_vehicle_agency_one.setText(String.format("%s (%s) %s",agencyName , agencyAbbrev, countryCode)); launch_agency_type_one.setText("Type: " + agencyType); if (detailLaunch.getRocket().getAgencies().get(0).getWikiURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getRocket().getAgencies().get(0).getWikiURL())); wikiButton_one.setVisibility(View.VISIBLE); wikiButton_one.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getRocket().getAgencies().get(0).getWikiURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Wiki", detailLaunch.getName(), detailLaunch.getRocket().getAgencies().get(0).getWikiURL() ); } }); } else { wikiButton_one.setVisibility(View.GONE); } if (detailLaunch.getRocket().getAgencies().get(0).getInfoURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getRocket().getAgencies().get(0).getInfoURL())); infoButton_one.setVisibility(View.VISIBLE); infoButton_one.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getRocket().getAgencies().get(0).getInfoURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Info", detailLaunch.getName(), detailLaunch.getRocket().getAgencies().get(0).getInfoURL() ); } }); } else { infoButton_one.setVisibility(View.GONE); } } private void setTwoVehicleAgencies() { String countryCode = detailLaunch.getRocket().getAgencies().get(0).getCountryCode(); String agencyOne = getAgencyType(detailLaunch.getRocket().getAgencies().get(0).getType()); String agencyNameOne = detailLaunch.getRocket().getAgencies().get(0).getName(); String agencyAbbrevOne = detailLaunch.getRocket().getAgencies().get(0).getAbbrev(); checkLaunchSummary(agencyAbbrevOne, launch_agency_summary_one); if (countryCode.length() > 10){ countryCode = countryCode.substring(0,3) + ", "+ countryCode.substring(4,7) + ", "+ countryCode.substring(7,10) + "..."; agencyOne = agencyOne + " | Multinational"; } else if (countryCode.length() > 4 && countryCode.length() < 10) { countryCode = countryCode.substring(0, 3); } String countryCodeTwo = detailLaunch.getRocket().getAgencies().get(1).getCountryCode(); String agencyTwo = getAgencyType(detailLaunch.getRocket().getAgencies().get(1).getType()); String agencyNameTwo = detailLaunch.getRocket().getAgencies().get(1).getName(); String agencyAbbrevTwo = detailLaunch.getRocket().getAgencies().get(1).getAbbrev(); checkLaunchSummary(agencyAbbrevTwo, launch_agency_summary_two); if (countryCodeTwo.length() > 10){ countryCodeTwo = countryCodeTwo.substring(0,3) + ", "+ countryCodeTwo.substring(4,7) + ", "+ countryCodeTwo.substring(7,10) + "..."; agencyTwo = agencyTwo + " | Multinational"; } else if (countryCodeTwo.length() > 4 && countryCodeTwo.length() < 10) { countryCodeTwo = countryCodeTwo.substring(0, 3); } launch_one.setVisibility(View.VISIBLE); launch_two.setVisibility(View.VISIBLE); launch_agency_type_one.setText(String.format("Type: %s", agencyOne)); launch_agency_type_two.setText(String.format("Type: %s", agencyTwo)); launch_vehicle_agency_one.setText(String.format("%s (%s) %s",agencyNameOne, agencyAbbrevOne , countryCode)); launch_vehicle_agency_two.setText(String.format("%s (%s) %s", agencyNameTwo,agencyAbbrevTwo, countryCodeTwo)); if (detailLaunch.getRocket().getAgencies().get(0).getInfoURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getRocket().getAgencies().get(0).getWikiURL())); wikiButton_one.setVisibility(View.VISIBLE); wikiButton_one.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getRocket().getAgencies().get(0).getWikiURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Wiki", detailLaunch.getName(), detailLaunch.getRocket().getAgencies().get(0).getInfoURL() ); } }); } else { wikiButton_one.setVisibility(View.GONE); } if (detailLaunch.getRocket().getAgencies().get(0).getInfoURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getRocket().getAgencies().get(0).getInfoURL())); infoButton_one.setVisibility(View.VISIBLE); infoButton_one.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getRocket().getAgencies().get(0).getInfoURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Info", detailLaunch.getName(), detailLaunch.getRocket().getAgencies().get(0).getInfoURL() ); } }); } else { infoButton_one.setVisibility(View.GONE); } if (detailLaunch.getRocket().getAgencies().get(1).getWikiURL().length() > 0){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getRocket().getAgencies().get(1).getWikiURL())); wikiButton_two.setVisibility(View.VISIBLE); wikiButton_two.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getRocket().getAgencies().get(1).getWikiURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Wiki", detailLaunch.getName(), detailLaunch.getRocket().getAgencies().get(1).getWikiURL() ); } }); } else { wikiButton_two.setVisibility(View.GONE); } if (detailLaunch.getRocket().getAgencies().get(1).getInfoURL().length() > 1){ ((LaunchDetailActivity)context).mayLaunchUrl(Uri.parse(detailLaunch.getRocket().getAgencies().get(1).getInfoURL())); infoButton_two.setVisibility(View.VISIBLE); infoButton_two.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity)context; Utils.openCustomTab(activity, context, detailLaunch.getRocket().getAgencies().get(1).getInfoURL()); Analytics.from(getActivity()).sendButtonClickedWithURL( "Mission Info", detailLaunch.getName(), detailLaunch.getRocket().getAgencies().get(1).getInfoURL() ); } }); } else { infoButton_two.setVisibility(View.GONE); } } private void checkLaunchSummary(String abbrev, TextView view) { if (abbrev.equalsIgnoreCase("spx")){ view.setText(R.string.spacex_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("usaf")){ view.setText(R.string.usaf_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("cnsa")){ view.setText(R.string.cnsa_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("casc")){ view.setText(R.string.casc_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("isro")){ view.setText(R.string.isro_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("vko")){ view.setText(R.string.vko_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("fka")){ view.setText(R.string.roscosmos_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("ula")){ view.setText(R.string.ula_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("gd")){ view.setText(R.string.gd_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("asa")){ view.setText(R.string.asa_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("TsSKB-Progress")){ view.setText(R.string.TsSKB_summary); view.setVisibility(View.VISIBLE); } else if (abbrev.equalsIgnoreCase("nasa")){ view.setText(R.string.nasa_summary); view.setVisibility(View.VISIBLE); } } private String getAgencyType(int type){ String agency; switch (type){ case 1: agency = "Government"; break; case 2: agency = "Multinational"; break; case 3: agency = "Commercial"; break; case 4: agency = "Educational"; break; case 5: agency = "Private"; break; case 6: agency = "Unknown"; break; default: agency = "Unknown"; } return agency; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } public static AgencyDetailFragment newInstance() { return new AgencyDetailFragment(); } }
package org.eclipse.persistence.jaxb.compiler; import java.awt.Image; import java.beans.Introspector; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; 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 javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessorOrder; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttachmentRef; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlInlineBinaryData; import javax.xml.bind.annotation.XmlList; import javax.xml.bind.annotation.XmlMimeType; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchema; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSchemaTypes; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.XmlType.DEFAULT; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters; import javax.xml.namespace.QName; import javax.xml.transform.Source; import org.eclipse.persistence.exceptions.JAXBException; import org.eclipse.persistence.internal.descriptors.Namespace; import org.eclipse.persistence.internal.helper.ClassConstants; import org.eclipse.persistence.internal.helper.ConversionManager; import org.eclipse.persistence.internal.jaxb.JaxbClassLoader; import org.eclipse.persistence.internal.libraries.asm.ClassWriter; import org.eclipse.persistence.internal.libraries.asm.CodeVisitor; import org.eclipse.persistence.internal.libraries.asm.Constants; import org.eclipse.persistence.internal.libraries.asm.Label; import org.eclipse.persistence.internal.libraries.asm.Type; import org.eclipse.persistence.internal.libraries.asm.attrs.Annotation; import org.eclipse.persistence.internal.libraries.asm.attrs.LocalVariableTypeTableAttribute; import org.eclipse.persistence.internal.libraries.asm.attrs.RuntimeVisibleAnnotations; import org.eclipse.persistence.internal.libraries.asm.attrs.SignatureAttribute; import org.eclipse.persistence.internal.oxm.XMLConversionManager; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.jaxb.TypeMappingInfo; import org.eclipse.persistence.jaxb.javamodel.AnnotationProxy; import org.eclipse.persistence.jaxb.javamodel.Helper; import org.eclipse.persistence.jaxb.javamodel.JavaClass; import org.eclipse.persistence.jaxb.javamodel.JavaConstructor; import org.eclipse.persistence.jaxb.javamodel.JavaField; import org.eclipse.persistence.jaxb.javamodel.JavaHasAnnotations; import org.eclipse.persistence.jaxb.javamodel.JavaMethod; import org.eclipse.persistence.jaxb.javamodel.JavaPackage; import org.eclipse.persistence.jaxb.javamodel.reflection.JavaFieldImpl; import org.eclipse.persistence.jaxb.xmlmodel.XmlAccessOrder; import org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType; import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation; import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlReadTransformer; import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransformer; import org.eclipse.persistence.mappings.transformers.AttributeTransformer; import org.eclipse.persistence.mappings.transformers.FieldTransformer; import org.eclipse.persistence.oxm.NamespaceResolver; import org.eclipse.persistence.oxm.XMLConstants; import org.eclipse.persistence.oxm.annotations.XmlAccessMethods; import org.eclipse.persistence.oxm.annotations.XmlCDATA; import org.eclipse.persistence.oxm.annotations.XmlClassExtractor; import org.eclipse.persistence.oxm.annotations.XmlContainerProperty; import org.eclipse.persistence.oxm.annotations.XmlCustomizer; import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode; import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorValue; import org.eclipse.persistence.oxm.annotations.XmlElementsJoinNodes; import org.eclipse.persistence.oxm.annotations.XmlInverseReference; import org.eclipse.persistence.oxm.annotations.XmlIsSetNullPolicy; import org.eclipse.persistence.oxm.annotations.XmlJoinNode; import org.eclipse.persistence.oxm.annotations.XmlJoinNodes; import org.eclipse.persistence.oxm.annotations.XmlKey; import org.eclipse.persistence.oxm.annotations.XmlNullPolicy; import org.eclipse.persistence.oxm.annotations.XmlParameter; import org.eclipse.persistence.oxm.annotations.XmlPath; import org.eclipse.persistence.oxm.annotations.XmlPaths; import org.eclipse.persistence.oxm.annotations.XmlProperties; import org.eclipse.persistence.oxm.annotations.XmlProperty; import org.eclipse.persistence.oxm.annotations.XmlReadOnly; import org.eclipse.persistence.oxm.annotations.XmlWriteOnly; import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers; /** * INTERNAL: * <p> * <b>Purpose:</b>To perform some initial processing of Java classes and JAXB * 2.0 Annotations and generate meta data that can be used by the Mappings * Generator and Schema Generator * <p> * <b>Responsibilities:</b> * <ul> * <li>Generate a map of TypeInfo objects, keyed on class name</li> * <li>Generate a map of user defined schema types</li> * <li>Identify any class-based JAXB 2.0 callback methods, and create * MarshalCallback and UnmarshalCallback objects to wrap them.</li> * <li>Centralize processing which is common to both Schema Generation and * Mapping Generation tasks</li> * <p> * This class does the initial processing of the JAXB 2.0 Generation. It * generates meta data that can be used by the later Schema Generation and * Mapping Generation steps. * * @see org.eclipse.persistence.jaxb.compiler.Generator * @author mmacivor * @since Oracle TopLink 11.1.1.0.0 */ public class AnnotationsProcessor { static final String JAVAX_ACTIVATION_DATAHANDLER = "javax.activation.DataHandler"; static final String JAVAX_MAIL_INTERNET_MIMEMULTIPART = "javax.mail.internet.MimeMultipart"; private static final String JAVAX_XML_BIND_JAXBELEMENT = "javax.xml.bind.JAXBElement"; private static final String TYPE_METHOD_NAME = "type"; private static final String VALUE_METHOD_NAME = "value"; private static final String ARRAY_PACKAGE_NAME = "jaxb.dev.java.net.array"; private static final String ARRAY_NAMESPACE = "http://jaxb.dev.java.net/array"; private static final String ARRAY_CLASS_NAME_SUFFIX = "Array"; private static final String JAXB_DEV = "jaxb.dev.java.net"; private static final String ORG_W3C_DOM = "org.w3c.dom"; private static final String CREATE = "create"; private static final String ELEMENT_DECL_GLOBAL = "javax.xml.bind.annotation.XmlElementDecl.GLOBAL"; private static final String ELEMENT_DECL_DEFAULT = "\u0000"; private static final String EMPTY_STRING = ""; private static final String JAVA_UTIL_LIST = "java.util.List"; private static final String JAVA_LANG_OBJECT = "java.lang.Object"; private static final String SLASH = "/"; private static final String AT_SIGN = "@"; private static final String SEMI_COLON = ";"; private static final String L = "L"; private static final String ITEM = "item"; private static final String IS_STR = "is"; private static final String GET_STR = "get"; private static final String SET_STR = "set"; private static final Character DOT_CHR = '.'; private static final Character DOLLAR_SIGN_CHR = '$'; private static final Character SLASH_CHR = '/'; private ArrayList<JavaClass> typeInfoClasses; private HashMap<String, NamespaceInfo> packageToNamespaceMappings; private HashMap<String, MarshalCallback> marshalCallbacks; private HashMap<String, QName> userDefinedSchemaTypes; private HashMap<String, TypeInfo> typeInfo; private ArrayList<QName> typeQNames; private HashMap<String, UnmarshalCallback> unmarshalCallbacks; private HashMap<String, HashMap<QName, ElementDeclaration>> elementDeclarations; private HashMap<String, ElementDeclaration> xmlRootElements; private List<ElementDeclaration> localElements; private HashMap<String, JavaMethod> factoryMethods; private Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry> xmlRegistries; private Map<String, Class> arrayClassesToGeneratedClasses; private Map<Class, JavaClass> generatedClassesToArrayClasses; private Map<java.lang.reflect.Type, Class> collectionClassesToGeneratedClasses; private Map<Class, java.lang.reflect.Type> generatedClassesToCollectionClasses; private Map<JavaClass, TypeMappingInfo> javaClassToTypeMappingInfos; private Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedClasses; private Map<TypeMappingInfo, Class> typeMappingInfoToAdapterClasses; private Map<TypeMappingInfo, QName> typeMappingInfoToSchemaType; private NamespaceResolver namespaceResolver; private Helper helper; private String defaultTargetNamespace; private JAXBMetadataLogger logger; private boolean isDefaultNamespaceAllowed; private boolean hasSwaRef; public AnnotationsProcessor(Helper helper) { this.helper = helper; isDefaultNamespaceAllowed = true; hasSwaRef = false; } /** * Generate TypeInfo instances for a given array of JavaClasses. * * @param classes */ void processClassesAndProperties(JavaClass[] classes, TypeMappingInfo[] typeMappingInfos) { init(classes, typeMappingInfos); preBuildTypeInfo(classes); classes = postBuildTypeInfo(classes); processJavaClasses(null); processPropertyTypes(this.typeInfoClasses.toArray(new JavaClass[this.typeInfoClasses.size()])); finalizeProperties(); createElementsForTypeMappingInfo(); } public void createElementsForTypeMappingInfo() { if (this.javaClassToTypeMappingInfos != null && !this.javaClassToTypeMappingInfos.isEmpty()) { Set<JavaClass> classes = this.javaClassToTypeMappingInfos.keySet(); for (JavaClass nextClass : classes) { TypeMappingInfo nextInfo = this.javaClassToTypeMappingInfos.get(nextClass); if (nextInfo != null) { boolean xmlAttachmentRef = false; String xmlMimeType = null; java.lang.annotation.Annotation[] annotations = getAnnotations(nextInfo); Class adapterClass = this.typeMappingInfoToAdapterClasses.get(nextInfo); Class declJavaType = null; if (adapterClass != null) { declJavaType = CompilerHelper.getTypeFromAdapterClass(adapterClass); } if (annotations != null) { for (int j = 0; j < annotations.length; j++) { java.lang.annotation.Annotation nextAnnotation = annotations[j]; if (nextAnnotation != null) { if (nextAnnotation instanceof XmlMimeType) { XmlMimeType javaAnnotation = (XmlMimeType) nextAnnotation; xmlMimeType = javaAnnotation.value(); } else if (nextAnnotation instanceof XmlAttachmentRef) { xmlAttachmentRef = true; if(!this.hasSwaRef) { this.hasSwaRef = true; } } } } } QName qname = null; String nextClassName = nextClass.getQualifiedName(); if (declJavaType != null) { nextClassName = declJavaType.getCanonicalName(); } if (typeMappingInfoToGeneratedClasses != null) { Class generatedClass = typeMappingInfoToGeneratedClasses.get(nextInfo); if (generatedClass != null) { nextClassName = generatedClass.getCanonicalName(); } } TypeInfo nextTypeInfo = typeInfo.get(nextClassName); if (nextTypeInfo != null) { qname = new QName(nextTypeInfo.getClassNamespace(), nextTypeInfo.getSchemaTypeName()); } else { qname = getUserDefinedSchemaTypes().get(nextClassName); if (qname == null) { if (nextClassName.equals(ClassConstants.APBYTE.getName()) || nextClassName.equals(Image.class.getName()) || nextClassName.equals(Source.class.getName()) || nextClassName.equals("javax.activation.DataHandler")) { if (xmlAttachmentRef) { qname = XMLConstants.SWA_REF_QNAME; } else { qname = XMLConstants.BASE_64_BINARY_QNAME; } } else if (nextClassName.equals(ClassConstants.OBJECT.getName())) { qname = XMLConstants.ANY_TYPE_QNAME; } else if (nextClassName.equals(ClassConstants.XML_GREGORIAN_CALENDAR.getName())) { qname = XMLConstants.ANY_SIMPLE_TYPE_QNAME; } else { Class theClass = helper.getClassForJavaClass(nextClass); qname = (QName) XMLConversionManager.getDefaultJavaTypes().get(theClass); } } } if (qname != null) { typeMappingInfoToSchemaType.put(nextInfo, qname); } if (nextInfo.getXmlTagName() != null) { ElementDeclaration element = new ElementDeclaration(nextInfo.getXmlTagName(), nextClass, nextClass.getQualifiedName(), false); element.setTypeMappingInfo(nextInfo); element.setXmlMimeType(xmlMimeType); element.setXmlAttachmentRef(xmlAttachmentRef); if (declJavaType != null) { element.setJavaType(helper.getJavaClass(declJavaType)); } Class generatedClass = typeMappingInfoToGeneratedClasses.get(nextInfo); if (generatedClass != null) { element.setJavaType(helper.getJavaClass(generatedClass)); } if (nextInfo.getElementScope() == TypeMappingInfo.ElementScope.Global) { this.getGlobalElements().put(element.getElementName(), element); } else { this.localElements.add(element); } String rootNamespace = element.getElementName().getNamespaceURI(); if(rootNamespace == null) { rootNamespace = XMLConstants.EMPTY_STRING; } if (rootNamespace.equals(XMLConstants.EMPTY_STRING)) { isDefaultNamespaceAllowed = false; } } } } } } /** * Returns an array of Annotations for a given TypeMappingInfo. This array * will either be populated from the TypeMappingInfo's array of annotations, * or based on an xml-element if present. The xml-element will take * precedence over the annotation array; if there is an xml-element the * Array of Annotations will be ignored. * * @param tmInfo * @return */ private java.lang.annotation.Annotation[] getAnnotations(TypeMappingInfo tmInfo) { if (tmInfo.getXmlElement() != null) { ClassLoader loader = helper.getClassLoader(); // create a single ConversionManager for that will be shared by the // proxy objects ConversionManager cMgr = new ConversionManager(); cMgr.setLoader(loader); // unmarshal the node into an XmlElement org.eclipse.persistence.jaxb.xmlmodel.XmlElement xElt = (org.eclipse.persistence.jaxb.xmlmodel.XmlElement) CompilerHelper.getXmlElement(tmInfo.getXmlElement(), loader); List annotations = new ArrayList(); // where applicable, a given dynamic proxy will contain a Map of // method name/return value entries Map<String, Object> components = null; // handle @XmlElement: set 'type' method if (!(xElt.getType().equals("javax.xml.bind.annotation.XmlElement.DEFAULT"))) { components = new HashMap(); components.put(TYPE_METHOD_NAME, xElt.getType()); annotations.add(AnnotationProxy.getProxy(components, XmlElement.class, loader, cMgr)); } // handle @XmlList if (xElt.isXmlList()) { annotations.add(AnnotationProxy.getProxy(components, XmlList.class, loader, cMgr)); } // handle @XmlAttachmentRef if (xElt.isXmlAttachmentRef()) { annotations.add(AnnotationProxy.getProxy(components, XmlAttachmentRef.class, loader, cMgr)); } // handle @XmlMimeType: set 'value' method if (xElt.getXmlMimeType() != null) { components = new HashMap(); components.put(VALUE_METHOD_NAME, xElt.getXmlMimeType()); annotations.add(AnnotationProxy.getProxy(components, XmlMimeType.class, loader, cMgr)); } // handle @XmlJavaTypeAdapter: set 'type' and 'value' methods if (xElt.getXmlJavaTypeAdapter() != null) { components = new HashMap(); components.put(TYPE_METHOD_NAME, xElt.getXmlJavaTypeAdapter().getType()); components.put(VALUE_METHOD_NAME, xElt.getXmlJavaTypeAdapter().getValue()); annotations.add(AnnotationProxy.getProxy(components, XmlJavaTypeAdapter.class, loader, cMgr)); } // return the newly created array of dynamic proxy objects return (java.lang.annotation.Annotation[]) annotations.toArray(new java.lang.annotation.Annotation[annotations.size()]); } // no xml-element set on the info, (i.e. no xml overrides) so return the // array of Annotation objects return tmInfo.getAnnotations(); } /** * Initialize maps, lists, etc. Typically called prior to processing a set * of classes via preBuildTypeInfo, postBuildTypeInfo, processJavaClasses. */ void init(JavaClass[] classes, TypeMappingInfo[] typeMappingInfos) { typeInfoClasses = new ArrayList<JavaClass>(); typeInfo = new HashMap<String, TypeInfo>(); typeQNames = new ArrayList<QName>(); userDefinedSchemaTypes = new HashMap<String, QName>(); if (packageToNamespaceMappings == null) { packageToNamespaceMappings = new HashMap<String, NamespaceInfo>(); } this.factoryMethods = new HashMap<String, JavaMethod>(); this.xmlRegistries = new HashMap<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry>(); this.namespaceResolver = new NamespaceResolver(); this.xmlRootElements = new HashMap<String, ElementDeclaration>(); arrayClassesToGeneratedClasses = new HashMap<String, Class>(); collectionClassesToGeneratedClasses = new HashMap<java.lang.reflect.Type, Class>(); generatedClassesToArrayClasses = new HashMap<Class, JavaClass>(); generatedClassesToCollectionClasses = new HashMap<Class, java.lang.reflect.Type>(); typeMappingInfoToGeneratedClasses = new HashMap<TypeMappingInfo, Class>(); typeMappingInfoToSchemaType = new HashMap<TypeMappingInfo, QName>(); elementDeclarations = new HashMap<String, HashMap<QName, ElementDeclaration>>(); HashMap globalElements = new HashMap<QName, ElementDeclaration>(); elementDeclarations.put(XmlElementDecl.GLOBAL.class.getName(), globalElements); localElements = new ArrayList<ElementDeclaration>(); javaClassToTypeMappingInfos = new HashMap<JavaClass, TypeMappingInfo>(); if (typeMappingInfos != null) { for (int i = 0; i < typeMappingInfos.length; i++) { javaClassToTypeMappingInfos.put(classes[i], typeMappingInfos[i]); } } typeMappingInfoToAdapterClasses = new HashMap<TypeMappingInfo, Class>(); if (typeMappingInfos != null) { for (TypeMappingInfo next : typeMappingInfos) { java.lang.annotation.Annotation[] annotations = getAnnotations(next); if (annotations != null) { for (java.lang.annotation.Annotation nextAnnotation : annotations) { if (nextAnnotation instanceof XmlJavaTypeAdapter) { typeMappingInfoToAdapterClasses.put(next, ((XmlJavaTypeAdapter) nextAnnotation).value()); } } } } } } /** * Process class level annotations only. It is assumed that a call to init() * has been made prior to calling this method. After the types created via * this method have been modified (if necessary) postBuildTypeInfo and * processJavaClasses should be called to finish processing. * * @param javaClasses * @return */ public Map<String, TypeInfo> preBuildTypeInfo(JavaClass[] javaClasses) { for (JavaClass javaClass : javaClasses) { if (javaClass == null || !shouldGenerateTypeInfo(javaClass) || isXmlRegistry(javaClass) || javaClass.isArray()) { continue; } TypeInfo info = typeInfo.get(javaClass.getQualifiedName()); if (info != null) { if (info.isPreBuilt()) { continue; } } if (javaClass.isEnum()) { info = new EnumTypeInfo(helper); } else { info = new TypeInfo(helper); } info.setJavaClassName(javaClass.getQualifiedName()); info.setPreBuilt(true); // handle @XmlTransient if (helper.isAnnotationPresent(javaClass, XmlTransient.class)) { info.setXmlTransient(true); } // handle @XmlInlineBinaryData if (helper.isAnnotationPresent(javaClass, XmlInlineBinaryData.class)) { info.setInlineBinaryData(true); } // handle @XmlRootElement processXmlRootElement(javaClass, info); // handle @XmlSeeAlso processXmlSeeAlso(javaClass, info); NamespaceInfo packageNamespace = getNamespaceInfoForPackage(javaClass); // handle @XmlType preProcessXmlType(javaClass, info, packageNamespace); // handle @XmlAccessorType preProcessXmlAccessorType(javaClass, info, packageNamespace); // handle @XmlAccessorOrder preProcessXmlAccessorOrder(javaClass, info, packageNamespace); // handle package level @XmlJavaTypeAdapters processPackageLevelAdapters(javaClass, info); // handle class level @XmlJavaTypeAdapters processClassLevelAdapters(javaClass, info); // handle descriptor customizer preProcessCustomizer(javaClass, info); // handle package level @XmlSchemaType(s) processSchemaTypes(javaClass, info); // handle class extractor if (helper.isAnnotationPresent(javaClass, XmlClassExtractor.class)) { XmlClassExtractor classExtractor = (XmlClassExtractor) helper.getAnnotation(javaClass, XmlClassExtractor.class); info.setClassExtractorName(classExtractor.value().getName()); } // handle user properties if (helper.isAnnotationPresent(javaClass, XmlProperties.class)) { XmlProperties xmlProperties = (XmlProperties) helper.getAnnotation(javaClass, XmlProperties.class); Map<Object, Object> propertiesMap = createUserPropertiesMap(xmlProperties.value()); info.setUserProperties(propertiesMap); } else if (helper.isAnnotationPresent(javaClass, XmlProperty.class)) { XmlProperty xmlProperty = (XmlProperty) helper.getAnnotation(javaClass, XmlProperty.class); Map<Object, Object> propertiesMap = createUserPropertiesMap(new XmlProperty[] { xmlProperty }); info.setUserProperties(propertiesMap); } // handle class indicator field name if (helper.isAnnotationPresent(javaClass, XmlDiscriminatorNode.class)) { XmlDiscriminatorNode xmlDiscriminatorNode = (XmlDiscriminatorNode) helper.getAnnotation(javaClass, XmlDiscriminatorNode.class); info.setXmlDiscriminatorNode(xmlDiscriminatorNode.value()); } // handle class indicator if (helper.isAnnotationPresent(javaClass, XmlDiscriminatorValue.class)) { XmlDiscriminatorValue xmlDiscriminatorValue = (XmlDiscriminatorValue) helper.getAnnotation(javaClass, XmlDiscriminatorValue.class); info.setXmlDiscriminatorValue(xmlDiscriminatorValue.value()); } typeInfoClasses.add(javaClass); typeInfo.put(info.getJavaClassName(), info); } return typeInfo; } /** * Process any additional classes (i.e. inner classes, @XmlSeeAlso, * @XmlRegistry, etc.) for a given set of JavaClasses, then complete * building all of the required TypeInfo objects. This method * is typically called after init and preBuildTypeInfo have * been called. * * @param javaClasses * @return updated array of JavaClasses, made up of the original classes * plus any additional ones */ public JavaClass[] postBuildTypeInfo(JavaClass[] javaClasses) { if (javaClasses.length == 0) { return javaClasses; } // create type info instances for any additional classes javaClasses = processAdditionalClasses(javaClasses); preBuildTypeInfo(javaClasses); updateGlobalElements(javaClasses); buildTypeInfo(javaClasses); return javaClasses; } /** * INTERNAL: * * Complete building TypeInfo objects for a given set of JavaClass * instances. This method assumes that init, preBuildTypeInfo, and * postBuildTypeInfo have been called. * * @param allClasses * @return */ private Map<String, TypeInfo> buildTypeInfo(JavaClass[] allClasses) { for (JavaClass javaClass : allClasses) { if (javaClass == null) { continue; } TypeInfo info = typeInfo.get(javaClass.getQualifiedName()); if (info == null || info.isPostBuilt()) { continue; } info.setPostBuilt(true); // handle factory methods processFactoryMethods(javaClass, info); NamespaceInfo packageNamespace = getNamespaceInfoForPackage(javaClass); // handle @XmlAccessorType postProcessXmlAccessorType(info, packageNamespace); // handle @XmlType postProcessXmlType(javaClass, info, packageNamespace); // handle @XmlEnum if (info.isEnumerationType()) { addEnumTypeInfo(javaClass, ((EnumTypeInfo) info)); continue; } // process schema type name processTypeQName(javaClass, info, packageNamespace); // handle superclass if necessary JavaClass superClass = (JavaClass) javaClass.getSuperclass(); if (shouldGenerateTypeInfo(superClass)) { JavaClass[] jClassArray = new JavaClass[] { superClass }; buildNewTypeInfo(jClassArray); } // add properties info.setProperties(getPropertiesForClass(javaClass, info)); // process properties processTypeInfoProperties(javaClass, info); // handle @XmlAccessorOrder postProcessXmlAccessorOrder(info, packageNamespace); validatePropOrderForInfo(info); } return typeInfo; } /** * Perform any final generation and/or validation operations on TypeInfo * properties. * */ public void finalizeProperties() { ArrayList<JavaClass> jClasses = getTypeInfoClasses(); for (JavaClass jClass : jClasses) { TypeInfo tInfo = getTypeInfo().get(jClass.getQualifiedName()); // don't need to validate props on a transient class at this point if (tInfo.isTransient()) { continue; } if(!jClass.isInterface() && !tInfo.isEnumerationType() && !jClass.isAbstract()) { if (tInfo.getFactoryMethodName() == null && tInfo.getObjectFactoryClassName() == null) { JavaConstructor zeroArgConstructor = jClass.getDeclaredConstructor(new JavaClass[] {}); if (zeroArgConstructor == null) { if(tInfo.isSetXmlJavaTypeAdapter()) { tInfo.setTransient(true); } else { throw org.eclipse.persistence.exceptions.JAXBException.factoryMethodOrConstructorRequired(jClass.getName()); } } } } // validate XmlValue if (tInfo.getXmlValueProperty() != null) { validateXmlValueFieldOrProperty(jClass, tInfo.getXmlValueProperty()); } for (Property property : tInfo.getPropertyList()) { // need to check for transient reference class JavaClass typeClass = property.getActualType(); TypeInfo targetInfo = typeInfo.get(typeClass.getQualifiedName()); if (targetInfo != null && targetInfo.isTransient()) { throw JAXBException.invalidReferenceToTransientClass(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName()); } // only one XmlValue is allowed per class, and if there is one only XmlAttributes are allowed if (tInfo.isSetXmlValueProperty()) { if (property.isXmlValue() && !(tInfo.getXmlValueProperty().getPropertyName().equals(property.getPropertyName()))) { throw JAXBException.xmlValueAlreadySet(property.getPropertyName(), tInfo.getXmlValueProperty().getPropertyName(), jClass.getName()); } if (!property.isXmlValue() && !property.isAttribute() && !property.isInverseReference() && !property.isTransient()) { throw JAXBException.propertyOrFieldShouldBeAnAttribute(property.getPropertyName()); } } if(property.isSwaAttachmentRef() && !this.hasSwaRef) { this.hasSwaRef = true; } // validate XmlIDREF if (property.isXmlIdRef()) { // the target class must have an associated TypeInfo unless it is Object if (targetInfo == null && !typeClass.getQualifiedName().equals(JAVA_LANG_OBJECT)) { throw JAXBException.invalidIDREFClass(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName()); } // if the property is an XmlIDREF, the target must have an XmlID set if (targetInfo != null && targetInfo.getIDProperty() == null) { throw JAXBException.invalidIdRef(property.getPropertyName(), typeClass.getQualifiedName()); } } // there can only be one XmlID per type info if (property.isXmlId() && tInfo.getIDProperty() != null && !(tInfo.getIDProperty().getPropertyName().equals(property.getPropertyName()))) { throw JAXBException.idAlreadySet(property.getPropertyName(), tInfo.getIDProperty().getPropertyName(), jClass.getName()); } // there can only be one XmlAnyAttribute per type info if (property.isAnyAttribute() && tInfo.isSetAnyAttributePropertyName() && !(tInfo.getAnyAttributePropertyName().equals(property.getPropertyName()))) { throw JAXBException.multipleAnyAttributeMapping(jClass.getName()); } // there can only be one XmlAnyElement per type info if (property.isAny() && tInfo.isSetAnyElementPropertyName() && !(tInfo.getAnyElementPropertyName().equals(property.getPropertyName()))) { throw JAXBException.xmlAnyElementAlreadySet(property.getPropertyName(), tInfo.getAnyElementPropertyName(), jClass.getName()); } // an XmlAttachmentRef can only appear on a DataHandler property if (property.isSwaAttachmentRef() && !areEquals(property.getActualType(), JAVAX_ACTIVATION_DATAHANDLER)) { throw JAXBException.invalidAttributeRef(property.getPropertyName(), jClass.getQualifiedName()); } // an XmlElementWrapper can only appear on a Collection or Array if (property.getXmlElementWrapper() != null) { if (!isCollectionType(property) && !property.getType().isArray()) { throw JAXBException.invalidElementWrapper(property.getPropertyName()); } } // handle XmlElementRef(s) - validate and build the required ElementDeclaration object if (property.isReference()) { processReferenceProperty(property, tInfo, jClass); } // handle XmlTransformation - validate transformer class/method if (property.isXmlTransformation()) { processXmlTransformationProperty(property); } // validate XmlJoinNodes if (property.isSetXmlJoinNodes()) { // the target class must have an associated TypeInfo if (targetInfo == null) { throw JAXBException.invalidXmlJoinNodeReferencedClass(property.getPropertyName(), typeClass.getQualifiedName()); } // validate each referencedXmlPath - target TypeInfo should // have XmlID/XmlKey property with matching XmlPath if (targetInfo.getIDProperty() == null && targetInfo.getXmlKeyProperties() == null) { throw JAXBException.noKeyOrIDPropertyOnJoinTarget(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName()); } for (org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode : property.getXmlJoinNodes().getXmlJoinNode()) { String refXPath = xmlJoinNode.getReferencedXmlPath(); if (targetInfo.getIDProperty() != null && refXPath.equals(targetInfo.getIDProperty().getXmlPath())) { continue; } boolean matched = false; if (targetInfo.getXmlKeyProperties() != null) { for (Property xmlkeyProperty : targetInfo.getXmlKeyProperties()) { if (refXPath.equals(xmlkeyProperty.getXmlPath())) { matched = true; break; } } } if (!matched) { throw JAXBException.invalidReferencedXmlPathOnJoin(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName(), refXPath); } } } } } } /** * Process a given TypeInfo instance's properties. * * @param info */ private void processTypeInfoProperties(JavaClass javaClass, TypeInfo info) { ArrayList<Property> properties = info.getPropertyList(); for (Property property : properties) { // handle @XmlID processXmlID(property, javaClass, info); // handle @XmlIDREF - validate these properties after processing of // all types is completed processXmlIDREF(property); if(property.isMap()) { JavaClass keyType = property.getKeyType(); if (shouldGenerateTypeInfo(keyType)) { JavaClass[] jClassArray = new JavaClass[] { keyType }; buildNewTypeInfo(jClassArray); } JavaClass valueType = property.getValueType(); if (shouldGenerateTypeInfo(valueType)) { JavaClass[] jClassArray = new JavaClass[] { valueType }; buildNewTypeInfo(jClassArray); } } } } void processPropertyTypes(JavaClass[] classes) { for (JavaClass next:classes) { TypeInfo info = getTypeInfo().get(next.getQualifiedName()); if(info != null) { for (Property property : info.getPropertyList()) { if(property.isTransient()) { continue; } JavaClass type = property.getActualType(); if (!(this.typeInfo.containsKey(type.getQualifiedName())) && shouldGenerateTypeInfo(type)) { CompilerHelper.addClassToClassLoader(type, helper.getClassLoader()); JavaClass[] jClassArray = new JavaClass[] { type }; buildNewTypeInfo(jClassArray); } if(property.isChoice()) { processChoiceProperty(property, info, next, type); for(Property choiceProp:property.getChoiceProperties()) { type = choiceProp.getActualType(); if (!(this.typeInfo.containsKey(type.getQualifiedName())) && shouldGenerateTypeInfo(type)) { CompilerHelper.addClassToClassLoader(type, helper.getClassLoader()); JavaClass[] jClassArray = new JavaClass[] { type }; buildNewTypeInfo(jClassArray); } } } } } } } /** * This method was initially designed to handle processing one or more * JavaClass instances. Over time its functionality has been broken apart * and handled in different methods. Its sole purpose now is to check for * callback methods. * * @param classes * this paramater can and should be null as it is not used */ public void processJavaClasses(JavaClass[] classes) { checkForCallbackMethods(); } /** * Process any additional classes, such as inner classes, @XmlRegistry or * from @XmlSeeAlso. * * @param classes * @return */ private JavaClass[] processAdditionalClasses(JavaClass[] classes) { ArrayList<JavaClass> extraClasses = new ArrayList<JavaClass>(); ArrayList<JavaClass> classesToProcess = new ArrayList<JavaClass>(); for (JavaClass jClass : classes) { Class xmlElementType = null; JavaClass javaClass = jClass; TypeMappingInfo tmi = javaClassToTypeMappingInfos.get(javaClass); if (tmi != null) { Class adapterClass = this.typeMappingInfoToAdapterClasses.get(tmi); if (adapterClass != null) { JavaClass adapterJavaClass = helper.getJavaClass(adapterClass); JavaClass newType = helper.getJavaClass(Object.class); // look for marshal method for (Object nextMethod : adapterJavaClass.getDeclaredMethods()) { JavaMethod method = (JavaMethod) nextMethod; if (method.getName().equals("marshal")) { JavaClass returnType = method.getReturnType(); if (!returnType.getQualifiedName().equals(newType.getQualifiedName())) { newType = (JavaClass) returnType; break; } } } javaClass = newType; } java.lang.annotation.Annotation[] annotations = getAnnotations(tmi); if (annotations != null) { for (int j = 0; j < annotations.length; j++) { java.lang.annotation.Annotation nextAnnotation = annotations[j]; if (nextAnnotation != null) { if (nextAnnotation instanceof XmlElement) { XmlElement javaAnnotation = (XmlElement) nextAnnotation; if (javaAnnotation.type() != XmlElement.DEFAULT.class) { xmlElementType = javaAnnotation.type(); } } } } } } if (areEquals(javaClass, byte[].class) || areEquals(javaClass, JAVAX_ACTIVATION_DATAHANDLER) || areEquals(javaClass, Source.class) || areEquals(javaClass, Image.class) || areEquals(javaClass, JAVAX_MAIL_INTERNET_MIMEMULTIPART)) { if (tmi == null || tmi.getXmlTagName() == null) { ElementDeclaration declaration = new ElementDeclaration(null, javaClass, javaClass.getQualifiedName(), false, XmlElementDecl.GLOBAL.class); declaration.setTypeMappingInfo(tmi); getGlobalElements().put(null, declaration); } } else if (javaClass.isArray()) { if (!helper.isBuiltInJavaType(javaClass.getComponentType())) { extraClasses.add(javaClass.getComponentType()); } Class generatedClass; if (null == tmi) { generatedClass = arrayClassesToGeneratedClasses.get(javaClass.getName()); } else { generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader()); } if (generatedClass == null) { generatedClass = generateWrapperForArrayClass(javaClass, tmi, xmlElementType, extraClasses); extraClasses.add(helper.getJavaClass(generatedClass)); arrayClassesToGeneratedClasses.put(javaClass.getName(), generatedClass); } generatedClassesToArrayClasses.put(generatedClass, javaClass); typeMappingInfoToGeneratedClasses.put(tmi, generatedClass); } else if (isCollectionType(javaClass)) { JavaClass componentClass; if (javaClass.hasActualTypeArguments()) { componentClass = (JavaClass) javaClass.getActualTypeArguments().toArray()[0]; if (!componentClass.isPrimitive()) { extraClasses.add(componentClass); } } else { componentClass = helper.getJavaClass(Object.class); } Class generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader()); if (generatedClass == null) { generatedClass = generateCollectionValue(javaClass, tmi, xmlElementType); extraClasses.add(helper.getJavaClass(generatedClass)); } typeMappingInfoToGeneratedClasses.put(tmi, generatedClass); } else if (isMapType(javaClass)) { JavaClass keyClass; JavaClass valueClass; if (javaClass.hasActualTypeArguments()) { keyClass = (JavaClass) javaClass.getActualTypeArguments().toArray()[0]; if (!helper.isBuiltInJavaType(keyClass)) { extraClasses.add(keyClass); } valueClass = (JavaClass) javaClass.getActualTypeArguments().toArray()[1]; if (!helper.isBuiltInJavaType(valueClass)) { extraClasses.add(valueClass); } } else { keyClass = helper.getJavaClass(Object.class); valueClass = helper.getJavaClass(Object.class); } Class generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader()); if (generatedClass == null) { generatedClass = generateWrapperForMapClass(javaClass, keyClass, valueClass, tmi); extraClasses.add(helper.getJavaClass(generatedClass)); } typeMappingInfoToGeneratedClasses.put(tmi, generatedClass); } else { // process @XmlRegistry, @XmlSeeAlso and inner classes processClass(javaClass, classesToProcess); } } // process @XmlRegistry, @XmlSeeAlso and inner classes for (JavaClass javaClass : extraClasses) { processClass(javaClass, classesToProcess); } return classesToProcess.toArray(new JavaClass[classesToProcess.size()]); } /** * Adds additional classes to the given List, from inner classes, * * @XmlRegistry or @XmlSeeAlso. * * @param javaClass * @param classesToProcess */ private void processClass(JavaClass javaClass, ArrayList<JavaClass> classesToProcess) { if (shouldGenerateTypeInfo(javaClass)) { if (isXmlRegistry(javaClass)) { this.processObjectFactory(javaClass, classesToProcess); } else { classesToProcess.add(javaClass); // handle @XmlSeeAlso TypeInfo info = typeInfo.get(javaClass.getQualifiedName()); if (info != null && info.isSetXmlSeeAlso()) { for (String jClassName : info.getXmlSeeAlso()) { classesToProcess.add(helper.getJavaClass(jClassName)); } } // handle inner classes for (Iterator<JavaClass> jClassIt = javaClass.getDeclaredClasses().iterator(); jClassIt.hasNext();) { JavaClass innerClass = jClassIt.next(); if (shouldGenerateTypeInfo(innerClass)) { CompilerHelper.addClassToClassLoader(innerClass, helper.getClassLoader()); TypeInfo tInfo = typeInfo.get(innerClass.getQualifiedName()); if ((tInfo != null && !tInfo.isTransient()) || !helper.isAnnotationPresent(innerClass, XmlTransient.class)) { classesToProcess.add(innerClass); } } } } } } /** * Process an @XmlSeeAlso annotation. TypeInfo instances will be created for * each class listed. * * @param javaClass */ private void processXmlSeeAlso(JavaClass javaClass, TypeInfo info) { // reflectively load @XmlSeeAlso class to avoid dependency Class xmlSeeAlsoClass = null; Method valueMethod = null; try { xmlSeeAlsoClass = PrivilegedAccessHelper.getClassForName("javax.xml.bind.annotation.XmlSeeAlso"); valueMethod = PrivilegedAccessHelper.getDeclaredMethod(xmlSeeAlsoClass, "value", new Class[] {}); } catch (ClassNotFoundException ex) { // Ignore this exception. If SeeAlso isn't available, don't try to // process } catch (NoSuchMethodException ex) { } if (xmlSeeAlsoClass != null && helper.isAnnotationPresent(javaClass, xmlSeeAlsoClass)) { Object seeAlso = helper.getAnnotation(javaClass, xmlSeeAlsoClass); Class[] values = null; try { values = (Class[]) PrivilegedAccessHelper.invokeMethod(valueMethod, seeAlso, new Object[] {}); } catch (Exception ex) { } List<String> seeAlsoClassNames = new ArrayList<String>(); for (Class next : values) { seeAlsoClassNames.add(next.getName()); } info.setXmlSeeAlso(seeAlsoClassNames); } } /** * Process any factory methods. * * @param javaClass * @param info */ private void processFactoryMethods(JavaClass javaClass, TypeInfo info) { JavaMethod factoryMethod = this.factoryMethods.get(javaClass.getRawName()); if (factoryMethod != null) { // set up factory method info for mappings. info.setFactoryMethodName(factoryMethod.getName()); info.setObjectFactoryClassName(factoryMethod.getOwningClass().getRawName()); JavaClass[] paramTypes = factoryMethod.getParameterTypes(); if (paramTypes != null && paramTypes.length > 0) { String[] paramTypeNames = new String[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { paramTypeNames[i] = paramTypes[i].getRawName(); } info.setFactoryMethodParamTypes(paramTypeNames); } } } /** * Process any package-level @XmlJavaTypeAdapters. * * @param javaClass * @param info */ private void processPackageLevelAdapters(JavaClass javaClass, TypeInfo info) { JavaPackage pack = javaClass.getPackage(); if (helper.isAnnotationPresent(pack, XmlJavaTypeAdapters.class)) { XmlJavaTypeAdapters adapters = (XmlJavaTypeAdapters) helper.getAnnotation(pack, XmlJavaTypeAdapters.class); XmlJavaTypeAdapter[] adapterArray = adapters.value(); for (XmlJavaTypeAdapter next : adapterArray) { processPackageLevelAdapter(next, info); } } if (helper.isAnnotationPresent(pack, XmlJavaTypeAdapter.class)) { XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(pack, XmlJavaTypeAdapter.class); processPackageLevelAdapter(adapter, info); } } private void processPackageLevelAdapter(XmlJavaTypeAdapter next, TypeInfo info) { JavaClass adapterClass = helper.getJavaClass(next.value()); JavaClass boundType = helper.getJavaClass(next.type()); if (boundType != null) { info.addPackageLevelAdapterClass(adapterClass, boundType); } else { getLogger().logWarning(JAXBMetadataLogger.INVALID_BOUND_TYPE, new Object[] { boundType, adapterClass }); } } /** * Process any class-level @XmlJavaTypeAdapters. * * @param javaClass * @param info */ private void processClassLevelAdapters(JavaClass javaClass, TypeInfo info) { if (helper.isAnnotationPresent(javaClass, XmlJavaTypeAdapter.class)) { XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(javaClass, XmlJavaTypeAdapter.class); String boundType = adapter.type().getName(); if (boundType == null || boundType.equals("javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT")) { boundType = javaClass.getRawName(); } org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter(); xja.setValue(adapter.value().getName()); xja.setType(boundType); info.setXmlJavaTypeAdapter(xja); } } /** * Process any @XmlSchemaType(s). * * @param javaClass * @param info */ private void processSchemaTypes(JavaClass javaClass, TypeInfo info) { JavaPackage pack = javaClass.getPackage(); if (helper.isAnnotationPresent(pack, XmlSchemaTypes.class)) { XmlSchemaTypes types = (XmlSchemaTypes) helper.getAnnotation(pack, XmlSchemaTypes.class); XmlSchemaType[] typeArray = types.value(); for (XmlSchemaType next : typeArray) { processSchemaType(next); } } else if (helper.isAnnotationPresent(pack, XmlSchemaType.class)) { processSchemaType((XmlSchemaType) helper.getAnnotation(pack, XmlSchemaType.class)); } } /** * Process @XmlRootElement annotation on a given JavaClass. * * @param javaClass * @param info */ private void processXmlRootElement(JavaClass javaClass, TypeInfo info) { if (helper.isAnnotationPresent(javaClass, XmlRootElement.class)) { XmlRootElement rootElemAnnotation = (XmlRootElement) helper.getAnnotation(javaClass, XmlRootElement.class); org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = new org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement(); xmlRE.setName(rootElemAnnotation.name()); xmlRE.setNamespace(rootElemAnnotation.namespace()); info.setXmlRootElement(xmlRE); } } /** * Process @XmlType annotation on a given JavaClass and update the TypeInfo * for pre-processing. Note that if no @XmlType annotation is present we * still create a new XmlType an set it on the TypeInfo. * * @param javaClass * @param info * @param packageNamespace */ private void preProcessXmlType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) { org.eclipse.persistence.jaxb.xmlmodel.XmlType xmlType = new org.eclipse.persistence.jaxb.xmlmodel.XmlType(); if (helper.isAnnotationPresent(javaClass, XmlType.class)) { XmlType typeAnnotation = (XmlType) helper.getAnnotation(javaClass, XmlType.class); // set name xmlType.setName(typeAnnotation.name()); // set namespace xmlType.setNamespace(typeAnnotation.namespace()); // set propOrder String[] propOrder = typeAnnotation.propOrder(); // handle case where propOrder is an empty array if (propOrder != null) { xmlType.getPropOrder(); } for (String prop : propOrder) { xmlType.getPropOrder().add(prop); } // set factoryClass Class factoryClass = typeAnnotation.factoryClass(); if (factoryClass == DEFAULT.class) { xmlType.setFactoryClass("javax.xml.bind.annotation.XmlType.DEFAULT"); } else { xmlType.setFactoryClass(factoryClass.getCanonicalName()); } // set factoryMethodName xmlType.setFactoryMethod(typeAnnotation.factoryMethod()); } else { // set defaults xmlType.setName(getSchemaTypeNameForClassName(javaClass.getName())); xmlType.setNamespace(packageNamespace.getNamespace()); } info.setXmlType(xmlType); } /** * Process XmlType for a given TypeInfo. Here we assume that the TypeInfo * has an XmlType set - typically via preProcessXmlType or XmlProcessor * override. * * @param javaClass * @param info * @param packageNamespace */ private void postProcessXmlType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) { // assumes that the TypeInfo has an XmlType set from org.eclipse.persistence.jaxb.xmlmodel.XmlType xmlType = info.getXmlType(); // set/validate factoryClass and factoryMethod String factoryClassName = xmlType.getFactoryClass(); String factoryMethodName = xmlType.getFactoryMethod(); if (factoryClassName.equals("javax.xml.bind.annotation.XmlType.DEFAULT")) { if (factoryMethodName != null && !factoryMethodName.equals(EMPTY_STRING)) { // factory method applies to the current class - verify method exists JavaMethod method = javaClass.getDeclaredMethod(factoryMethodName, new JavaClass[] {}); if (method == null) { throw org.eclipse.persistence.exceptions.JAXBException.factoryMethodNotDeclared(factoryMethodName, javaClass.getName()); } info.setFactoryMethodName(factoryMethodName); } } else { if (factoryMethodName == null || factoryMethodName.equals(EMPTY_STRING)) { throw org.eclipse.persistence.exceptions.JAXBException.factoryClassWithoutFactoryMethod(javaClass.getName()); } info.setObjectFactoryClassName(factoryClassName); info.setFactoryMethodName(factoryMethodName); } // figure out type name String typeName = xmlType.getName(); if (typeName.equals(XMLProcessor.DEFAULT)) { typeName = getSchemaTypeNameForClassName(javaClass.getName()); } info.setSchemaTypeName(typeName); // set propOrder if (xmlType.isSetPropOrder()) { List<String> props = xmlType.getPropOrder(); if (props.size() == 0) { info.setPropOrder(new String[0]); } else if (props.get(0).equals(EMPTY_STRING)) { info.setPropOrder(new String[] { EMPTY_STRING }); } else { info.setPropOrder(xmlType.getPropOrder().toArray(new String[xmlType.getPropOrder().size()])); } } // figure out namespace if (xmlType.getNamespace().equals(XMLProcessor.DEFAULT)) { info.setClassNamespace(packageNamespace.getNamespace()); } else { info.setClassNamespace(xmlType.getNamespace()); } } /** * Process @XmlAccessorType annotation on a given JavaClass and update the * TypeInfo for pre-processing. * * @param javaClass * @param info * @param packageNamespace */ private void preProcessXmlAccessorType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) { org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType xmlAccessType; if (helper.isAnnotationPresent(javaClass, XmlAccessorType.class)) { XmlAccessorType accessorType = (XmlAccessorType) helper.getAnnotation(javaClass, XmlAccessorType.class); xmlAccessType = org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType.fromValue(accessorType.value().name()); info.setXmlAccessType(xmlAccessType); } } /** * Post process XmlAccessorType. In some cases, such as @XmlSeeAlso classes, * the access type may not have been set * * @param info */ private void postProcessXmlAccessorType(TypeInfo info, NamespaceInfo packageNamespace) { if (!info.isSetXmlAccessType()) { //Check for super class JavaClass next = helper.getJavaClass(info.getJavaClassName()).getSuperclass(); while(next != null && !(next.getName().equals(JAVA_LANG_OBJECT))) { TypeInfo parentInfo = this.typeInfo.get(next.getName()); if(parentInfo != null && parentInfo.isSetXmlAccessType()) { info.setXmlAccessType(parentInfo.getXmlAccessType()); break; } next = next.getSuperclass(); } // use value in package-info.java as last resort - will default if // not set info.setXmlAccessType(org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType.fromValue(packageNamespace.getAccessType().name())); } } /** * Process package and class @XmlAccessorOrder. Class level annotation * overrides a package level annotation. * * @param javaClass * @param info * @param packageNamespace */ private void preProcessXmlAccessorOrder(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) { XmlAccessorOrder order = null; // class level annotation overrides package level annotation if (helper.isAnnotationPresent(javaClass, XmlAccessorOrder.class)) { order = (XmlAccessorOrder) helper.getAnnotation(javaClass, XmlAccessorOrder.class); info.setXmlAccessOrder(XmlAccessOrder.fromValue(order.value().name())); } } /** * Post process XmlAccessorOrder. This method assumes that the given * TypeInfo has already had its order set (via annotations in * preProcessXmlAccessorOrder or via xml metadata override in XMLProcessor). * * @param javaClass * @param info */ private void postProcessXmlAccessorOrder(TypeInfo info, NamespaceInfo packageNamespace) { if (!info.isSetXmlAccessOrder()) { // use value in package-info.java as last resort - will default if // not set info.setXmlAccessOrder(org.eclipse.persistence.jaxb.xmlmodel.XmlAccessOrder.fromValue(packageNamespace.getAccessOrder().name())); } info.orderProperties(); } /** * Process @XmlElement annotation on a given property. * * @param property */ private void processXmlElement(Property property, TypeInfo info) { if (helper.isAnnotationPresent(property.getElement(), XmlElement.class)) { XmlElement element = (XmlElement) helper.getAnnotation(property.getElement(), XmlElement.class); property.setIsRequired(element.required()); property.setNillable(element.nillable()); if (element.type() != XmlElement.DEFAULT.class && !(property.isSwaAttachmentRef())) { property.setOriginalType(property.getType()); if (isCollectionType(property.getType())) { property.setGenericType(helper.getJavaClass(element.type())); } else { property.setType(helper.getJavaClass(element.type())); } property.setHasXmlElementType(true); } // handle default value if (!element.defaultValue().equals(ELEMENT_DECL_DEFAULT)) { property.setDefaultValue(element.defaultValue()); } validateElementIsInPropOrder(info, property.getPropertyName()); } } /** * Process @XmlID annotation on a given property * * @param property * @param info */ private void processXmlID(Property property, JavaClass javaClass, TypeInfo info) { if (helper.isAnnotationPresent(property.getElement(), XmlID.class)) { property.setIsXmlId(true); info.setIDProperty(property); } } /** * Process @XmlIDREF on a given property. * * @param property */ private void processXmlIDREF(Property property) { if (helper.isAnnotationPresent(property.getElement(), XmlIDREF.class)) { property.setIsXmlIdRef(true); } } /** * Process @XmlJavaTypeAdapter on a given property. * * @param property * @param propertyType */ private void processXmlJavaTypeAdapter(Property property, TypeInfo info, JavaClass javaClass) { JavaClass adapterClass = null; JavaClass ptype = property.getActualType(); if (helper.isAnnotationPresent(property.getElement(), XmlJavaTypeAdapter.class)) { XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(property.getElement(), XmlJavaTypeAdapter.class); org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter(); xja.setValue(adapter.value().getName()); xja.setType(adapter.type().getName()); property.setXmlJavaTypeAdapter(xja); } else { TypeInfo ptypeInfo = typeInfo.get(ptype.getQualifiedName()); org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xmlJavaTypeAdapter; if (ptypeInfo == null && shouldGenerateTypeInfo(ptype)) { if(helper.isAnnotationPresent(ptype, XmlJavaTypeAdapter.class)) { XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(ptype, XmlJavaTypeAdapter.class); org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter(); xja.setValue(adapter.value().getName()); String boundType = adapter.type().getName(); if (boundType == null || boundType.equals("javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT")) { boundType = ptype.getRawName(); } xja.setType(adapter.type().getName()); property.setXmlJavaTypeAdapter(xja); } } if (ptypeInfo != null) { if (null != (xmlJavaTypeAdapter = ptypeInfo.getXmlJavaTypeAdapter())) { try { property.setXmlJavaTypeAdapter(xmlJavaTypeAdapter); } catch (JAXBException e) { throw JAXBException.invalidTypeAdapterClass(xmlJavaTypeAdapter.getValue(), javaClass.getName()); } } } if (info.getPackageLevelAdaptersByClass().get(ptype.getQualifiedName()) != null && !property.isSetXmlJavaTypeAdapter()) { adapterClass = info.getPackageLevelAdapterClass(ptype); org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter(); xja.setValue(adapterClass.getQualifiedName()); xja.setType(ptype.getQualifiedName()); property.setXmlJavaTypeAdapter(xja); } } } private void removeTypeInfo(String qualifiedName, TypeInfo info) { this.typeInfo.remove(qualifiedName); String typeName = info.getSchemaTypeName(); if (typeName != null && !(EMPTY_STRING.equals(typeName))) { QName typeQName = new QName(info.getClassNamespace(), typeName); this.typeQNames.remove(typeQName); } for(JavaClass next:this.typeInfoClasses) { if(next.getQualifiedName().equals(info.getJavaClassName())) { this.typeInfoClasses.remove(next); break; } } } /** * Store a QName (if necessary) based on a given TypeInfo's schema type * name. * * @param javaClass * @param info */ private void processTypeQName(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) { String typeName = info.getSchemaTypeName(); if (typeName != null && !(EMPTY_STRING.equals(typeName))) { QName typeQName = new QName(info.getClassNamespace(), typeName); boolean containsQName = typeQNames.contains(typeQName); if (containsQName) { throw JAXBException.nameCollision(typeQName.getNamespaceURI(), typeQName.getLocalPart()); } else { typeQNames.add(typeQName); } } } public boolean shouldGenerateTypeInfo(JavaClass javaClass) { if (javaClass == null || javaClass.isPrimitive() || javaClass.isAnnotation() || ORG_W3C_DOM.equals(javaClass.getPackageName())) { return false; } if (userDefinedSchemaTypes.get(javaClass.getQualifiedName()) != null) { return false; } if (javaClass.isArray()) { String javaClassName = javaClass.getName(); if (!(javaClassName.equals(ClassConstants.APBYTE.getName()))) { return true; } } if (helper.isBuiltInJavaType(javaClass)) { return false; } if (isCollectionType(javaClass) || isMapType(javaClass)) { return false; } return true; } public ArrayList<Property> getPropertiesForClass(JavaClass cls, TypeInfo info) { ArrayList<Property> returnList = new ArrayList<Property>(); if (!info.isTransient()) { JavaClass superClass = cls.getSuperclass(); if (null != superClass) { TypeInfo superClassInfo = typeInfo.get(superClass.getQualifiedName()); while (superClassInfo != null && superClassInfo.isTransient()) { if (info.getXmlAccessType() == XmlAccessType.FIELD) { returnList.addAll(getFieldPropertiesForClass(superClass, superClassInfo, false)); } else if (info.getXmlAccessType() == XmlAccessType.PROPERTY) { returnList.addAll(getPropertyPropertiesForClass(superClass, superClassInfo, false)); } else if (info.getXmlAccessType() == XmlAccessType.PUBLIC_MEMBER) { returnList.addAll(getPublicMemberPropertiesForClass(superClass, superClassInfo)); } else { returnList.addAll(getNoAccessTypePropertiesForClass(superClass, superClassInfo)); } superClass = superClass.getSuperclass(); superClassInfo = typeInfo.get(superClass.getQualifiedName()); } } } if (info.isTransient()) { returnList.addAll(getNoAccessTypePropertiesForClass(cls, info)); } else if (info.getXmlAccessType() == XmlAccessType.FIELD) { returnList.addAll(getFieldPropertiesForClass(cls, info, false)); returnList.addAll(getPropertyPropertiesForClass(cls, info, false, true)); } else if (info.getXmlAccessType() == XmlAccessType.PROPERTY) { returnList.addAll(getFieldPropertiesForClass(cls, info, false, true)); returnList.addAll(getPropertyPropertiesForClass(cls, info, false)); } else if (info.getXmlAccessType() == XmlAccessType.PUBLIC_MEMBER) { returnList.addAll(getPublicMemberPropertiesForClass(cls, info)); } else { returnList.addAll(getNoAccessTypePropertiesForClass(cls, info)); } return returnList; } public ArrayList<Property> getFieldPropertiesForClass(JavaClass cls, TypeInfo info, boolean onlyPublic) { return getFieldPropertiesForClass(cls, info, onlyPublic, false); } public ArrayList<Property> getFieldPropertiesForClass(JavaClass cls, TypeInfo info, boolean onlyPublic, boolean onlyExplicit) { ArrayList<Property> properties = new ArrayList<Property>(); if (cls == null) { return properties; } for (Iterator<JavaField> fieldIt = cls.getDeclaredFields().iterator(); fieldIt.hasNext();) { JavaField nextField = fieldIt.next(); int modifiers = nextField.getModifiers(); if (!helper.isAnnotationPresent(nextField, XmlTransient.class)) { if (!Modifier.isTransient(modifiers) && ((Modifier.isPublic(nextField.getModifiers()) && onlyPublic) || !onlyPublic)) { if (!Modifier.isStatic(modifiers)) { if((onlyExplicit && hasJAXBAnnotations(nextField)) || !onlyExplicit) { Property property = buildNewProperty(info, cls, nextField, nextField.getName(), nextField.getResolvedType()); properties.add(property); } } else if (helper.isAnnotationPresent(nextField, XmlAttribute.class)) { try { Property property = buildNewProperty(info, cls, nextField, nextField.getName(), nextField.getResolvedType()); Object value = ((JavaFieldImpl) nextField).get(null); if(value != null) { String stringValue = (String) XMLConversionManager.getDefaultXMLManager().convertObject(value, String.class, property.getSchemaType()); property.setFixedValue(stringValue); } else { property.setWriteOnly(true); } properties.add(property); } catch (ClassCastException e) { // do Nothing } catch (IllegalAccessException e) { // do Nothing } } } } else { // If a property is marked transient ensure it doesn't exist in // the propOrder List<String> propOrderList = Arrays.asList(info.getPropOrder()); if (propOrderList.contains(nextField.getName())) { throw JAXBException.transientInProporder(nextField.getName()); } } } return properties; } /* * Create a new Property Object and process the annotations that are common * to fields and methods */ private Property buildNewProperty(TypeInfo info, JavaClass cls, JavaHasAnnotations javaHasAnnotations, String propertyName, JavaClass ptype) { Property property = null; if (helper.isAnnotationPresent(javaHasAnnotations, XmlElements.class)) { property = buildChoiceProperty(javaHasAnnotations); } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlElementRef.class) || helper.isAnnotationPresent(javaHasAnnotations, XmlElementRefs.class)) { property = buildReferenceProperty(info, javaHasAnnotations, propertyName, ptype); if (helper.isAnnotationPresent(javaHasAnnotations, XmlAnyElement.class)) { XmlAnyElement anyElement = (XmlAnyElement) helper.getAnnotation(javaHasAnnotations, XmlAnyElement.class); property.setIsAny(true); if (anyElement.value() != null) { property.setDomHandlerClassName(anyElement.value().getName()); } property.setLax(anyElement.lax()); info.setAnyElementPropertyName(propertyName); } } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlAnyElement.class)) { XmlAnyElement anyElement = (XmlAnyElement) helper.getAnnotation(javaHasAnnotations, XmlAnyElement.class); property = new Property(helper); property.setIsAny(true); if (anyElement.value() != null) { property.setDomHandlerClassName(anyElement.value().getName()); } property.setLax(anyElement.lax()); info.setAnyElementPropertyName(propertyName); } else if (helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlTransformation.class) || helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlReadTransformer.class) || helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlWriteTransformer.class) || helper.isAnnotationPresent(javaHasAnnotations, XmlWriteTransformers.class)) { property = buildTransformationProperty(javaHasAnnotations, cls); } else { property = new Property(helper); } property.setPropertyName(propertyName); property.setElement(javaHasAnnotations); // if there is a TypeInfo for ptype check it for transient, otherwise // check the class TypeInfo pTypeInfo = typeInfo.get(ptype.getQualifiedName()); if ((pTypeInfo != null && !pTypeInfo.isTransient()) || !helper.isAnnotationPresent(ptype, XmlTransient.class)) { property.setType(ptype); } else { JavaClass parent = ptype.getSuperclass(); while (parent != null) { if (parent.getName().equals(JAVA_LANG_OBJECT)) { property.setType(parent); break; } // if there is a TypeInfo for parent check it for transient, // otherwise check the class TypeInfo parentTypeInfo = typeInfo.get(parent.getQualifiedName()); if ((parentTypeInfo != null && !parentTypeInfo.isTransient()) || !helper.isAnnotationPresent(parent, XmlTransient.class)) { property.setType(parent); break; } parent = parent.getSuperclass(); } } processPropertyAnnotations(info, cls, javaHasAnnotations, property); if (helper.isAnnotationPresent(javaHasAnnotations, XmlPath.class)) { XmlPath xmlPath = (XmlPath) helper.getAnnotation(javaHasAnnotations, XmlPath.class); property.setXmlPath(xmlPath.value()); // set schema name String schemaName = XMLProcessor.getNameFromXPath(xmlPath.value(), property.getPropertyName(), property.isAttribute()); QName qName; NamespaceInfo nsInfo = getNamespaceInfoForPackage(cls); if (nsInfo.isElementFormQualified()) { qName = new QName(nsInfo.getNamespace(), schemaName); } else { qName = new QName(schemaName); } property.setSchemaName(qName); } else { property.setSchemaName(getQNameForProperty(propertyName, javaHasAnnotations, getNamespaceInfoForPackage(cls), info.getClassNamespace())); } ptype = property.getActualType(); if (ptype.isPrimitive()) { property.setIsRequired(true); } // apply class level adapters - don't override property level adapter if (!property.isSetXmlJavaTypeAdapter()) { TypeInfo refClassInfo = getTypeInfo().get(ptype.getQualifiedName()); if (refClassInfo != null && refClassInfo.isSetXmlJavaTypeAdapter()) { org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xmlJavaTypeAdapter = null; try { xmlJavaTypeAdapter = refClassInfo.getXmlJavaTypeAdapter(); property.setXmlJavaTypeAdapter(refClassInfo.getXmlJavaTypeAdapter()); } catch (JAXBException e) { throw JAXBException.invalidTypeAdapterClass(xmlJavaTypeAdapter.getValue(), cls.getName()); } } } return property; } /** * Build a new 'choice' property. Here, we flag a new property as a 'choice' * and create/set an XmlModel XmlElements object based on the @XmlElements * annotation. * * Validation and building of the XmlElement properties will be done during * finalizeProperties in the processChoiceProperty method. * * @param javaHasAnnotations * @return */ private Property buildChoiceProperty(JavaHasAnnotations javaHasAnnotations) { Property choiceProperty = new Property(helper); choiceProperty.setChoice(true); boolean isIdRef = helper.isAnnotationPresent(javaHasAnnotations, XmlIDREF.class); choiceProperty.setIsXmlIdRef(isIdRef); // build an XmlElement to set on the Property org.eclipse.persistence.jaxb.xmlmodel.XmlElements xmlElements = new org.eclipse.persistence.jaxb.xmlmodel.XmlElements(); XmlElement[] elements = ((XmlElements) helper.getAnnotation(javaHasAnnotations, XmlElements.class)).value(); for (int i = 0; i < elements.length; i++) { XmlElement next = elements[i]; org.eclipse.persistence.jaxb.xmlmodel.XmlElement xmlElement = new org.eclipse.persistence.jaxb.xmlmodel.XmlElement(); xmlElement.setDefaultValue(next.defaultValue()); xmlElement.setName(next.name()); xmlElement.setNamespace(next.namespace()); xmlElement.setNillable(next.nillable()); xmlElement.setRequired(next.required()); xmlElement.setType(next.type().getName()); xmlElements.getXmlElement().add(xmlElement); } choiceProperty.setXmlElements(xmlElements); // handle XmlElementsJoinNodes if (helper.isAnnotationPresent(javaHasAnnotations, XmlElementsJoinNodes.class)) { org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes; org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode; List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes> xmlJoinNodesList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes>(); List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode> xmlJoinNodeList = null; for (XmlJoinNodes xmlJNs : ((XmlElementsJoinNodes) helper.getAnnotation(javaHasAnnotations, XmlElementsJoinNodes.class)).value()) { xmlJoinNodeList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode>(); for (XmlJoinNode xmlJN : xmlJNs.value()) { xmlJoinNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode(); xmlJoinNode.setXmlPath(xmlJN.xmlPath()); xmlJoinNode.setReferencedXmlPath(xmlJN.referencedXmlPath()); xmlJoinNodeList.add(xmlJoinNode); } if (xmlJoinNodeList.size() > 0) { xmlJoinNodes = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes(); xmlJoinNodes.setXmlJoinNode(xmlJoinNodeList); xmlJoinNodesList.add(xmlJoinNodes); } } choiceProperty.setXmlJoinNodesList(xmlJoinNodesList); } return choiceProperty; } private Property buildTransformationProperty(JavaHasAnnotations javaHasAnnotations, JavaClass cls) { Property property = new Property(helper); org.eclipse.persistence.oxm.annotations.XmlTransformation transformationAnnotation = (org.eclipse.persistence.oxm.annotations.XmlTransformation) helper.getAnnotation(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlTransformation.class); XmlTransformation transformation = new XmlTransformation(); if (transformationAnnotation != null) { transformation.setOptional(transformationAnnotation.optional()); } // Read Transformer org.eclipse.persistence.oxm.annotations.XmlReadTransformer readTransformer = (org.eclipse.persistence.oxm.annotations.XmlReadTransformer) helper.getAnnotation(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlReadTransformer.class); if (readTransformer != null) { org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlReadTransformer xmlReadTransformer = new org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlReadTransformer(); if (!(readTransformer.transformerClass() == AttributeTransformer.class)) { xmlReadTransformer.setTransformerClass(readTransformer.transformerClass().getName()); } else if (!(readTransformer.method().equals(EMPTY_STRING))) { xmlReadTransformer.setMethod(readTransformer.method()); } transformation.setXmlReadTransformer(xmlReadTransformer); } // Handle Write Transformers org.eclipse.persistence.oxm.annotations.XmlWriteTransformer[] transformers = null; if (helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlWriteTransformer.class)) { org.eclipse.persistence.oxm.annotations.XmlWriteTransformer writeTransformer = (org.eclipse.persistence.oxm.annotations.XmlWriteTransformer) helper.getAnnotation(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlWriteTransformer.class); transformers = new org.eclipse.persistence.oxm.annotations.XmlWriteTransformer[] { writeTransformer }; } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlWriteTransformers.class)) { XmlWriteTransformers writeTransformers = (XmlWriteTransformers) helper.getAnnotation(javaHasAnnotations, XmlWriteTransformers.class); transformers = writeTransformers.value(); } if (transformers != null) { for (org.eclipse.persistence.oxm.annotations.XmlWriteTransformer next : transformers) { org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransformer xmlWriteTransformer = new org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransformer(); if (!(next.transformerClass() == FieldTransformer.class)) { xmlWriteTransformer.setTransformerClass(next.transformerClass().getName()); } else if (!(next.method().equals(EMPTY_STRING))) { xmlWriteTransformer.setMethod(next.method()); } xmlWriteTransformer.setXmlPath(next.xmlPath()); transformation.getXmlWriteTransformer().add(xmlWriteTransformer); } } property.setXmlTransformation(transformation); property.setIsXmlTransformation(true); return property; } /** * Complete creation of a 'choice' property. Here, a Property is created for * each XmlElement in the XmlElements list. Validation is performed as well. * Each created Property is added to the owning Property's list of choice * properties. * * @param choiceProperty * @param info * @param cls * @param propertyType */ private void processChoiceProperty(Property choiceProperty, TypeInfo info, JavaClass cls, JavaClass propertyType) { String propertyName = choiceProperty.getPropertyName(); validateElementIsInPropOrder(info, propertyName); // validate XmlElementsXmlJoinNodes (if set) if (choiceProperty.isSetXmlJoinNodesList()) { // there must be one XmlJoinNodes entry per XmlElement if (choiceProperty.getXmlElements().getXmlElement().size() != choiceProperty.getXmlJoinNodesList().size()) { throw JAXBException.incorrectNumberOfXmlJoinNodesOnXmlElements(propertyName, cls.getQualifiedName()); } } XmlPath[] paths = null; if (helper.isAnnotationPresent(choiceProperty.getElement(), XmlPaths.class)) { XmlPaths pathAnnotation = (XmlPaths) helper.getAnnotation(choiceProperty.getElement(), XmlPaths.class); paths = pathAnnotation.value(); } ArrayList<Property> choiceProperties = new ArrayList<Property>(); for (int i = 0; i < choiceProperty.getXmlElements().getXmlElement().size(); i++) { org.eclipse.persistence.jaxb.xmlmodel.XmlElement next = choiceProperty.getXmlElements().getXmlElement().get(i); Property choiceProp = new Property(helper); String name; String namespace; // handle XmlPath - if xml-path is set, we ignore name/namespace if (paths != null && next.getXmlPath() == null) { // Only set the path, if the path hasn't already been set from xml XmlPath nextPath = paths[i]; next.setXmlPath(nextPath.value()); } if (next.getXmlPath() != null) { choiceProp.setXmlPath(next.getXmlPath()); boolean isAttribute = next.getXmlPath().contains(AT_SIGN); // validate attribute - must be in nested path, not at root if (isAttribute && !next.getXmlPath().contains(SLASH)) { throw JAXBException.invalidXmlPathWithAttribute(propertyName, cls.getQualifiedName(), next.getXmlPath()); } choiceProp.setIsAttribute(isAttribute); name = XMLProcessor.getNameFromXPath(next.getXmlPath(), propertyName, isAttribute); namespace = XMLProcessor.DEFAULT; } else { // no xml-path, so use name/namespace from xml-element name = next.getName(); namespace = next.getNamespace(); } if (name == null || name.equals(XMLProcessor.DEFAULT)) { if (next.getJavaAttribute() != null) { name = next.getJavaAttribute(); } else { name = propertyName; } } // if the property has xml-idref, the target type of each // xml-element in the list must have an xml-id property if (choiceProperty.isXmlIdRef()) { TypeInfo tInfo = typeInfo.get(next.getType()); if (tInfo == null || !tInfo.isIDSet()) { throw JAXBException.invalidXmlElementInXmlElementsList(propertyName, name); } } QName qName = null; if (!namespace.equals(XMLProcessor.DEFAULT)) { qName = new QName(namespace, name); } else { NamespaceInfo namespaceInfo = getNamespaceInfoForPackage(cls); if (namespaceInfo.isElementFormQualified()) { qName = new QName(namespaceInfo.getNamespace(), name); } else { qName = new QName(name); } } choiceProp.setPropertyName(name); // figure out the property's type - note that for DEFAULT, if from XML the value will // be "XmlElement.DEFAULT", and from annotations the value will be "XmlElement$DEFAULT" if (next.getType().equals("javax.xml.bind.annotation.XmlElement.DEFAULT") || next.getType().equals("javax.xml.bind.annotation.XmlElement$DEFAULT")) { choiceProp.setType(propertyType); } else { choiceProp.setType(helper.getJavaClass(next.getType())); } // handle case of XmlJoinNodes w/XmlElements if (choiceProperty.isSetXmlJoinNodesList()) { // assumes one corresponding xml-join-nodes entry per xml-element org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes = choiceProperty.getXmlJoinNodesList().get(i); if (xmlJoinNodes != null) { choiceProp.setXmlJoinNodes(xmlJoinNodes); // set type if (!xmlJoinNodes.getType().equals(XMLProcessor.DEFAULT)) { JavaClass pType = helper.getJavaClass(xmlJoinNodes.getType()); if (isCollectionType(choiceProp.getType())) { choiceProp.setGenericType(pType); } else { choiceProp.setType(pType); } } } } choiceProp.setSchemaName(qName); choiceProp.setSchemaType(getSchemaTypeFor(choiceProp.getType())); choiceProp.setIsXmlIdRef(choiceProperty.isXmlIdRef()); choiceProp.setXmlElementWrapper(choiceProperty.getXmlElementWrapper()); choiceProperties.add(choiceProp); if (!(this.typeInfo.containsKey(choiceProp.getType().getQualifiedName())) && shouldGenerateTypeInfo(choiceProp.getType())) { JavaClass[] jClassArray = new JavaClass[] { choiceProp.getType() }; buildNewTypeInfo(jClassArray); } } choiceProperty.setChoiceProperties(choiceProperties); } /** * Build a reference property. Here we will build a list of XML model * XmlElementRef objects, based on the @XmlElement(s) annotation, to store * on the Property. Processing of the elements and validation will be * performed during the finalize property phase via the * processReferenceProperty method. * * @param info * @param javaHasAnnotations * @param propertyName * @param ptype * @return */ private Property buildReferenceProperty(TypeInfo info, JavaHasAnnotations javaHasAnnotations, String propertyName, JavaClass ptype) { Property property = new Property(helper); property.setType(ptype); XmlElementRef[] elementRefs; XmlElementRef ref = (XmlElementRef) helper.getAnnotation(javaHasAnnotations, XmlElementRef.class); if (ref != null) { elementRefs = new XmlElementRef[] { ref }; } else { XmlElementRefs refs = (XmlElementRefs) helper.getAnnotation(javaHasAnnotations, XmlElementRefs.class); elementRefs = refs.value(); info.setElementRefsPropertyName(propertyName); } List<org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef> eltRefs = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef>(); for (XmlElementRef nextRef : elementRefs) { org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef eltRef = new org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef(); eltRef.setName(nextRef.name()); eltRef.setNamespace(nextRef.namespace()); eltRef.setType(nextRef.type().getName()); eltRefs.add(eltRef); } property.setIsReference(true); property.setXmlElementRefs(eltRefs); return property; } /** * Build a reference property. * * @param property * @param info * @param javaHasAnnotations * @return */ private Property processReferenceProperty(Property property, TypeInfo info, JavaClass cls) { String propertyName = property.getPropertyName(); validateElementIsInPropOrder(info, propertyName); for (org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef nextRef : property.getXmlElementRefs()) { JavaClass type = property.getType(); String typeName = type.getQualifiedName(); if (isCollectionType(property)) { if (type.hasActualTypeArguments()) { type = property.getGenericType(); typeName = type.getQualifiedName(); } } // for DEFAULT, if from XML the type will be "XmlElementRef.DEFAULT", // and from annotations the value will be "XmlElementref$DEFAULT" if (!(nextRef.getType().equals("javax.xml.bind.annotation.XmlElementRef.DEFAULT") || nextRef.getType().equals("javax.xml.bind.annotation.XmlElementRef$DEFAULT"))) { typeName = nextRef.getType(); type = helper.getJavaClass(typeName); } boolean missingReference = true; for (Entry<String, ElementDeclaration> entry : xmlRootElements.entrySet()) { ElementDeclaration entryValue = entry.getValue(); if (type.isAssignableFrom(entryValue.getJavaType())) { addReferencedElement(property, entryValue); missingReference = false; } } if (missingReference) { String name = nextRef.getName(); String namespace = nextRef.getNamespace(); if (namespace.equals(XMLProcessor.DEFAULT)) { namespace = EMPTY_STRING; } QName qname = new QName(namespace, name); JavaClass scopeClass = cls; ElementDeclaration referencedElement = null; while (!(scopeClass.getName().equals(JAVA_LANG_OBJECT))) { HashMap<QName, ElementDeclaration> elements = getElementDeclarationsForScope(scopeClass.getName()); if (elements != null) { referencedElement = elements.get(qname); } if (referencedElement != null) { break; } scopeClass = scopeClass.getSuperclass(); } if (referencedElement == null) { referencedElement = this.getGlobalElements().get(qname); } if (referencedElement != null) { addReferencedElement(property, referencedElement); } else { throw org.eclipse.persistence.exceptions.JAXBException.invalidElementRef(property.getPropertyName(), cls.getName()); } } } return property; } private void processPropertyAnnotations(TypeInfo info, JavaClass cls, JavaHasAnnotations javaHasAnnotations, Property property) { // Check for mixed context if (helper.isAnnotationPresent(javaHasAnnotations, XmlMixed.class)) { info.setMixed(true); property.setMixedContent(true); } if (helper.isAnnotationPresent(javaHasAnnotations, XmlContainerProperty.class)) { XmlContainerProperty container = (XmlContainerProperty) helper.getAnnotation(javaHasAnnotations, XmlContainerProperty.class); property.setInverseReferencePropertyName(container.value()); property.setInverseReferencePropertyGetMethodName(container.getMethodName()); property.setInverseReferencePropertySetMethodName(container.setMethodName()); } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlInverseReference.class)) { XmlInverseReference inverseReference = (XmlInverseReference) helper.getAnnotation(javaHasAnnotations, XmlInverseReference.class); property.setInverseReferencePropertyName(inverseReference.mappedBy()); TypeInfo targetInfo = this.getTypeInfo().get(property.getActualType().getName()); if (targetInfo != null && targetInfo.getXmlAccessType() == XmlAccessType.PROPERTY) { String propName = property.getPropertyName(); propName = Character.toUpperCase(propName.charAt(0)) + propName.substring(1); property.setInverseReferencePropertyGetMethodName(GET_STR + propName); property.setInverseReferencePropertySetMethodName(SET_STR + propName); } property.setInverseReference(true); } processXmlJavaTypeAdapter(property, info, cls); if (helper.isAnnotationPresent(property.getElement(), XmlAttachmentRef.class) && areEquals(property.getActualType(), JAVAX_ACTIVATION_DATAHANDLER)) { property.setIsSwaAttachmentRef(true); property.setSchemaType(XMLConstants.SWA_REF_QNAME); } processXmlElement(property, info); //JavaClass ptype = property.getActualType(); if (!(property.isSwaAttachmentRef()) && isMtomAttachment(property)) { property.setIsMtomAttachment(true); property.setSchemaType(XMLConstants.BASE_64_BINARY_QNAME); } if (helper.isAnnotationPresent(property.getElement(), XmlMimeType.class)) { property.setMimeType(((XmlMimeType) helper.getAnnotation(property.getElement(), XmlMimeType.class)).value()); } // set indicator for inlining binary data - setting this to true on a // non-binary data type won't have any affect if (helper.isAnnotationPresent(property.getElement(), XmlInlineBinaryData.class) || info.isBinaryDataToBeInlined()) { property.setisInlineBinaryData(true); } // Get schema-type info if specified and set it on the property for // later use: if (helper.isAnnotationPresent(property.getElement(), XmlSchemaType.class)) { XmlSchemaType schemaType = (XmlSchemaType) helper.getAnnotation(property.getElement(), XmlSchemaType.class); QName schemaTypeQname = new QName(schemaType.namespace(), schemaType.name()); property.setSchemaType(schemaTypeQname); } if (helper.isAnnotationPresent(property.getElement(), XmlAttribute.class)) { property.setIsAttribute(true); property.setIsRequired(((XmlAttribute) helper.getAnnotation(property.getElement(), XmlAttribute.class)).required()); } if (helper.isAnnotationPresent(property.getElement(), XmlAnyAttribute.class)) { if (info.isSetAnyAttributePropertyName()) { throw org.eclipse.persistence.exceptions.JAXBException.multipleAnyAttributeMapping(cls.getName()); } if (!property.getType().getName().equals("java.util.Map")) { throw org.eclipse.persistence.exceptions.JAXBException.anyAttributeOnNonMap(property.getPropertyName()); } property.setIsAnyAttribute(true); info.setAnyAttributePropertyName(property.getPropertyName()); } // Make sure XmlElementWrapper annotation is on a collection or array if (helper.isAnnotationPresent(property.getElement(), XmlElementWrapper.class)) { XmlElementWrapper wrapper = (XmlElementWrapper) helper.getAnnotation(property.getElement(), XmlElementWrapper.class); org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper xmlEltWrapper = new org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper(); xmlEltWrapper.setName(wrapper.name()); xmlEltWrapper.setNamespace(wrapper.namespace()); xmlEltWrapper.setNillable(wrapper.nillable()); xmlEltWrapper.setRequired(wrapper.required()); property.setXmlElementWrapper(xmlEltWrapper); } if (helper.isAnnotationPresent(property.getElement(), XmlList.class)) { // Make sure XmlList annotation is on a collection or array if (!isCollectionType(property) && !property.getType().isArray()) { throw JAXBException.invalidList(property.getPropertyName()); } property.setIsXmlList(true); } if (helper.isAnnotationPresent(property.getElement(), XmlValue.class)) { property.setIsXmlValue(true); info.setXmlValueProperty(property); } if (helper.isAnnotationPresent(property.getElement(), XmlReadOnly.class)) { property.setReadOnly(true); } if (helper.isAnnotationPresent(property.getElement(), XmlWriteOnly.class)) { property.setWriteOnly(true); } if (helper.isAnnotationPresent(property.getElement(), XmlCDATA.class)) { property.setCdata(true); } if (helper.isAnnotationPresent(property.getElement(), XmlAccessMethods.class)) { XmlAccessMethods accessMethods = (XmlAccessMethods) helper.getAnnotation(property.getElement(), XmlAccessMethods.class); if (!(accessMethods.getMethodName().equals(EMPTY_STRING))) { property.setGetMethodName(accessMethods.getMethodName()); } if (!(accessMethods.setMethodName().equals(EMPTY_STRING))) { property.setSetMethodName(accessMethods.setMethodName()); } if (!(property.isMethodProperty())) { property.setMethodProperty(true); } } // handle user properties if (helper.isAnnotationPresent(property.getElement(), XmlProperties.class)) { XmlProperties xmlProperties = (XmlProperties) helper.getAnnotation(property.getElement(), XmlProperties.class); Map<Object, Object> propertiesMap = createUserPropertiesMap(xmlProperties.value()); property.setUserProperties(propertiesMap); } else if (helper.isAnnotationPresent(property.getElement(), XmlProperty.class)) { XmlProperty xmlProperty = (XmlProperty) helper.getAnnotation(property.getElement(), XmlProperty.class); Map<Object, Object> propertiesMap = createUserPropertiesMap(new XmlProperty[] { xmlProperty }); property.setUserProperties(propertiesMap); } // handle XmlKey if (helper.isAnnotationPresent(property.getElement(), XmlKey.class)) { info.addXmlKeyProperty(property); } // handle XmlJoinNode(s) processXmlJoinNodes(property); processXmlNullPolicy(property); } /** * Process XmlJoinNode(s) for a given Property. An * org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNode(s) will be * created/populated using the annotation, and set on the Property for later * processing. * * It is assumed that for a single join node XmlJoinNode will be used, and * for multiple join nodes XmlJoinNodes will be used. * * @param property * Property that may contain @XmlJoinNodes/@XmlJoinNode */ private void processXmlJoinNodes(Property property) { List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode> xmlJoinNodeList; org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode; org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes; // handle XmlJoinNodes if (helper.isAnnotationPresent(property.getElement(), XmlJoinNodes.class)) { xmlJoinNodeList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode>(); for (XmlJoinNode xmlJN : ((XmlJoinNodes) helper.getAnnotation(property.getElement(), XmlJoinNodes.class)).value()) { xmlJoinNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode(); xmlJoinNode.setXmlPath(xmlJN.xmlPath()); xmlJoinNode.setReferencedXmlPath(xmlJN.referencedXmlPath()); xmlJoinNodeList.add(xmlJoinNode); } xmlJoinNodes = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes(); xmlJoinNodes.setXmlJoinNode(xmlJoinNodeList); property.setXmlJoinNodes(xmlJoinNodes); } // handle XmlJoinNode else if (helper.isAnnotationPresent(property.getElement(), XmlJoinNode.class)) { XmlJoinNode xmlJN = (XmlJoinNode) helper.getAnnotation(property.getElement(), XmlJoinNode.class); xmlJoinNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode(); xmlJoinNode.setXmlPath(xmlJN.xmlPath()); xmlJoinNode.setReferencedXmlPath(xmlJN.referencedXmlPath()); xmlJoinNodeList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode>(); xmlJoinNodeList.add(xmlJoinNode); xmlJoinNodes = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes(); xmlJoinNodes.setXmlJoinNode(xmlJoinNodeList); property.setXmlJoinNodes(xmlJoinNodes); } } /** * Responsible for validating transformer settings on a given property. * Validates that for field transformers either a transformer class OR * method name is set (not both) and that an xml-path is set. Validates that * for attribute transformers either a transformer class OR method name is * set (not both). * * @param property */ private void processXmlTransformationProperty(Property property) { if (property.isSetXmlTransformation()) { XmlTransformation xmlTransformation = property.getXmlTransformation(); // validate transformer(s) if (xmlTransformation.isSetXmlReadTransformer()) { // validate read transformer XmlReadTransformer readTransformer = xmlTransformation.getXmlReadTransformer(); if (readTransformer.isSetTransformerClass()) { // handle read transformer class if (readTransformer.isSetMethod()) { // cannot have both class and method set throw JAXBException.readTransformerHasBothClassAndMethod(property.getPropertyName()); } } else { // handle read transformer method if (!readTransformer.isSetMethod()) { // require class or method to be set throw JAXBException.readTransformerHasNeitherClassNorMethod(property.getPropertyName()); } } } if (xmlTransformation.isSetXmlWriteTransformers()) { // handle write transformer(s) for (XmlWriteTransformer writeTransformer : xmlTransformation.getXmlWriteTransformer()) { // must have an xml-path set if (!writeTransformer.isSetXmlPath()) { throw JAXBException.writeTransformerHasNoXmlPath(property.getPropertyName()); } if (writeTransformer.isSetTransformerClass()) { // handle write transformer class if (writeTransformer.isSetMethod()) { // cannot have both class and method set throw JAXBException.writeTransformerHasBothClassAndMethod(property.getPropertyName(), writeTransformer.getXmlPath()); } } else { // handle write transformer method if (!writeTransformer.isSetMethod()) { // require class or method to be set throw JAXBException.writeTransformerHasNeitherClassNorMethod(property.getPropertyName(), writeTransformer.getXmlPath()); } } } } } } /** * Compares a JavaModel JavaClass to a Class. Equality is based on the raw * name of the JavaClass compared to the canonical name of the Class. * * @param src * @param tgt * @return */ protected boolean areEquals(JavaClass src, Class tgt) { if (src == null || tgt == null) { return false; } return src.getRawName().equals(tgt.getCanonicalName()); } private void processXmlNullPolicy(Property property) { if (helper.isAnnotationPresent(property.getElement(), XmlNullPolicy.class)) { XmlNullPolicy nullPolicy = (XmlNullPolicy) helper.getAnnotation(property.getElement(), XmlNullPolicy.class); org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy policy = new org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy(); policy.setEmptyNodeRepresentsNull(nullPolicy.emptyNodeRepresentsNull()); policy.setIsSetPerformedForAbsentNode(nullPolicy.isSetPerformedForAbsentNode()); policy.setXsiNilRepresentsNull(new Boolean(nullPolicy.xsiNilRepresentsNull())); policy.setNullRepresentationForXml(org.eclipse.persistence.jaxb.xmlmodel.XmlMarshalNullRepresentation.valueOf(nullPolicy.nullRepresentationForXml().toString())); property.setNullPolicy(policy); } else if (helper.isAnnotationPresent(property.getElement(), XmlIsSetNullPolicy.class)) { XmlIsSetNullPolicy nullPolicy = (XmlIsSetNullPolicy) helper.getAnnotation(property.getElement(), XmlIsSetNullPolicy.class); org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy policy = new org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy(); policy.setEmptyNodeRepresentsNull(nullPolicy.emptyNodeRepresentsNull()); policy.setXsiNilRepresentsNull(new Boolean(nullPolicy.xsiNilRepresentsNull())); policy.setNullRepresentationForXml(org.eclipse.persistence.jaxb.xmlmodel.XmlMarshalNullRepresentation.valueOf(nullPolicy.nullRepresentationForXml().toString())); policy.setIsSetMethodName(nullPolicy.isSetMethodName()); for (XmlParameter next : nullPolicy.isSetParameters()) { org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy.IsSetParameter param = new org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy.IsSetParameter(); param.setValue(next.value()); param.setType(next.type().getName()); policy.getIsSetParameter().add(param); } property.setNullPolicy(policy); } } /** * Compares a JavaModel JavaClass to a Class. Equality is based on the raw * name of the JavaClass compared to the canonical name of the Class. * * @param src * @param tgt * @return */ protected boolean areEquals(JavaClass src, String tgtCanonicalName) { if (src == null || tgtCanonicalName == null) { return false; } return src.getRawName().equals(tgtCanonicalName); } public ArrayList<Property> getPropertyPropertiesForClass(JavaClass cls, TypeInfo info, boolean onlyPublic) { return getPropertyPropertiesForClass(cls, info, onlyPublic, false); } public ArrayList<Property> getPropertyPropertiesForClass(JavaClass cls, TypeInfo info, boolean onlyPublic, boolean onlyExplicit) { ArrayList<Property> properties = new ArrayList<Property>(); if (cls == null) { return properties; } // First collect all the getters and setters ArrayList<JavaMethod> propertyMethods = new ArrayList<JavaMethod>(); for (JavaMethod next : new ArrayList<JavaMethod>(cls.getDeclaredMethods())) { if (((next.getName().startsWith(GET_STR) && next.getName().length() > 3) || (next.getName().startsWith(IS_STR) && next.getName().length() > 2)) && next.getParameterTypes().length == 0 && next.getReturnType() != helper.getJavaClass(java.lang.Void.class)) { int modifiers = next.getModifiers(); if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && ((onlyPublic && Modifier.isPublic(next.getModifiers())) || !onlyPublic)) { propertyMethods.add(next); } } else if (next.getName().startsWith(SET_STR) && next.getName().length() > 3 && next.getParameterTypes().length == 1) { int modifiers = next.getModifiers(); if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && ((onlyPublic && Modifier.isPublic(next.getModifiers())) || !onlyPublic)) { propertyMethods.add(next); } } } // Next iterate over the getters and find their setter methods, add // whichever one is // annotated to the properties list. If neither is, use the getter // keep track of property names to avoid processing the same property // twice (for getter and setter) ArrayList<String> propertyNames = new ArrayList<String>(); for (int i = 0; i < propertyMethods.size(); i++) { boolean isPropertyTransient = false; JavaMethod nextMethod = propertyMethods.get(i); String propertyName = EMPTY_STRING; JavaMethod getMethod; JavaMethod setMethod; JavaMethod propertyMethod = null; if (!nextMethod.getName().startsWith(SET_STR)) { if (nextMethod.getName().startsWith(GET_STR)) { propertyName = nextMethod.getName().substring(3); } else if (nextMethod.getName().startsWith(IS_STR)) { propertyName = nextMethod.getName().substring(2); } getMethod = nextMethod; String setMethodName = SET_STR + propertyName; // use the JavaBean API to correctly decapitalize the first // character, if necessary propertyName = Introspector.decapitalize(propertyName); JavaClass[] paramTypes = { (JavaClass) getMethod.getReturnType() }; setMethod = cls.getDeclaredMethod(setMethodName, paramTypes); if (setMethod != null && hasJAXBAnnotations(setMethod)) { // use the set method if it exists and is annotated if (!helper.isAnnotationPresent(setMethod, XmlTransient.class)) { propertyMethod = setMethod; } else { isPropertyTransient = true; } } else if((onlyExplicit && hasJAXBAnnotations(getMethod)) || !onlyExplicit) { if (!helper.isAnnotationPresent(getMethod, XmlTransient.class)) { propertyMethod = getMethod; } else { isPropertyTransient = true; } } else if(onlyExplicit){ continue; } } else { propertyName = nextMethod.getName().substring(3); setMethod = nextMethod; String getMethodName = GET_STR + propertyName; getMethod = cls.getDeclaredMethod(getMethodName, new JavaClass[] {}); if (getMethod == null) { // try is instead of get getMethodName = IS_STR + propertyName; getMethod = cls.getDeclaredMethod(getMethodName, new JavaClass[] {}); } if (getMethod != null && hasJAXBAnnotations(getMethod)) { // use the set method if it exists and is annotated if (!helper.isAnnotationPresent(getMethod, XmlTransient.class)) { propertyMethod = getMethod; } else { isPropertyTransient = true; } } else if((onlyExplicit && hasJAXBAnnotations(setMethod)) || !onlyExplicit) { if(!helper.isAnnotationPresent(setMethod, XmlTransient.class)) { propertyMethod = setMethod; } else { isPropertyTransient = true; } } else if(onlyExplicit) { continue; } // use the JavaBean API to correctly decapitalize the first // character, if necessary propertyName = Introspector.decapitalize(propertyName); } JavaClass ptype = null; if (getMethod != null) { ptype = (JavaClass) getMethod.getReturnType(); } else { ptype = setMethod.getParameterTypes()[0]; } if (!propertyNames.contains(propertyName)) { propertyNames.add(propertyName); Property property = buildNewProperty(info, cls, propertyMethod, propertyName, ptype); property.setTransient(isPropertyTransient); if (getMethod != null) { property.setOriginalGetMethodName(getMethod.getName()); if (property.getGetMethodName() == null) { property.setGetMethodName(getMethod.getName()); } } if (setMethod != null) { property.setOriginalSetMethodName(setMethod.getName()); if (property.getSetMethodName() == null) { property.setSetMethodName(setMethod.getName()); } } property.setMethodProperty(true); if (!helper.isAnnotationPresent(property.getElement(), XmlTransient.class)) { properties.add(property); } else { // If a property is marked transient ensure it doesn't exist // in the propOrder List<String> propOrderList = Arrays.asList(info.getPropOrder()); if (propOrderList.contains(propertyName)) { throw JAXBException.transientInProporder(propertyName); } property.setTransient(true); } } } properties = removeSuperclassProperties(cls, properties); // default to alphabetical ordering // RI compliancy Collections.sort(properties, new PropertyComparitor()); return properties; } private ArrayList<Property> removeSuperclassProperties(JavaClass cls, ArrayList<Property> properties) { ArrayList<Property> revisedProperties = new ArrayList<Property>(); revisedProperties.addAll(properties); // Check for any get() methods that are overridden in the subclass. // If we find any, remove the property, because it is already defined on the superclass. JavaClass superClass = cls.getSuperclass(); if (null != superClass) { TypeInfo superClassInfo = typeInfo.get(superClass.getQualifiedName()); if (superClassInfo != null && !superClassInfo.isTransient()) { for (Property prop : properties) { for (Property superProp : superClassInfo.getProperties().values()) { if (superProp.getGetMethodName() != null && superProp.getGetMethodName().equals(prop.getGetMethodName())) { revisedProperties.remove(prop); } } } } } return revisedProperties; } public ArrayList getPublicMemberPropertiesForClass(JavaClass cls, TypeInfo info) { ArrayList<Property> fieldProperties = getFieldPropertiesForClass(cls, info, false); ArrayList<Property> methodProperties = getPropertyPropertiesForClass(cls, info, false); // filter out non-public properties that aren't annotated ArrayList<Property> publicFieldProperties = new ArrayList<Property>(); ArrayList<Property> publicMethodProperties = new ArrayList<Property>(); for (Property next : fieldProperties) { if (Modifier.isPublic(((JavaField) next.getElement()).getModifiers())) { publicFieldProperties.add(next); } else { if (hasJAXBAnnotations(next.getElement())) { publicFieldProperties.add(next); } } } for (Property next : methodProperties) { if (next.getElement() != null) { if (Modifier.isPublic(((JavaMethod) next.getElement()).getModifiers())) { publicMethodProperties.add(next); } else { if (hasJAXBAnnotations(next.getElement())) { publicMethodProperties.add(next); } } } } // Not sure who should win if a property exists for both or the correct // order if (publicFieldProperties.size() >= 0 && publicMethodProperties.size() == 0) { return publicFieldProperties; } else if (publicMethodProperties.size() > 0 && publicFieldProperties.size() == 0) { return publicMethodProperties; } else { // add any non-duplicate method properties to the collection. // - in the case of a collision if one is annotated use it, // otherwise // use the field. HashMap fieldPropertyMap = getPropertyMapFromArrayList(publicFieldProperties); for (int i = 0; i < publicMethodProperties.size(); i++) { Property next = (Property) publicMethodProperties.get(i); if (fieldPropertyMap.get(next.getPropertyName()) == null) { publicFieldProperties.add(next); } } return publicFieldProperties; } } public HashMap getPropertyMapFromArrayList(ArrayList<Property> props) { HashMap propMap = new HashMap(props.size()); Iterator propIter = props.iterator(); while (propIter.hasNext()) { Property next = (Property) propIter.next(); propMap.put(next.getPropertyName(), next); } return propMap; } public ArrayList getNoAccessTypePropertiesForClass(JavaClass cls, TypeInfo info) { ArrayList<Property> list = new ArrayList<Property>(); if (cls == null) { return list; } // Iterate over the field and method properties. If ANYTHING contains an // annotation and // doesn't appear in the other list, add it to the final list List<Property> fieldProperties = getFieldPropertiesForClass(cls, info, false); Map<String, Property> fields = new HashMap<String, Property>(fieldProperties.size()); for(Property next : fieldProperties) { JavaHasAnnotations elem = next.getElement(); if (!hasJAXBAnnotations(elem)) { next.setTransient(true); } list.add(next); fields.put(next.getPropertyName(), next); } List<Property> methodProperties = getPropertyPropertiesForClass(cls, info, false); for(Property next : methodProperties) { JavaHasAnnotations elem = next.getElement(); if (hasJAXBAnnotations(elem)) { // If the property is annotated remove the corresponding field Property fieldProperty = fields.get(next.getPropertyName()); list.remove(fieldProperty); list.add(next); } else { // If the property is not annotated only add it if there is no // corresponding field. next.setTransient(true); if(fields.get(next.getPropertyName()) == null) { list.add(next); } } } return list; } /** * Use name, namespace and type information to setup a user-defined schema * type. This method will typically be called when processing an * * @XmlSchemaType(s) annotation or xml-schema-type(s) metadata. * * @param name * @param namespace * @param jClassQualifiedName */ public void processSchemaType(String name, String namespace, String jClassQualifiedName) { this.userDefinedSchemaTypes.put(jClassQualifiedName, new QName(namespace, name)); } public void processSchemaType(XmlSchemaType type) { JavaClass jClass = helper.getJavaClass(type.type()); if (jClass == null) { return; } processSchemaType(type.name(), type.namespace(), jClass.getQualifiedName()); } public void addEnumTypeInfo(JavaClass javaClass, EnumTypeInfo info) { if (javaClass == null) { return; } info.setClassName(javaClass.getQualifiedName()); Class restrictionClass = String.class; if (helper.isAnnotationPresent(javaClass, XmlEnum.class)) { XmlEnum xmlEnum = (XmlEnum) helper.getAnnotation(javaClass, XmlEnum.class); restrictionClass = xmlEnum.value(); } QName restrictionBase = getSchemaTypeFor(helper.getJavaClass(restrictionClass)); info.setRestrictionBase(restrictionBase); for (Iterator<JavaField> fieldIt = javaClass.getDeclaredFields().iterator(); fieldIt.hasNext();) { JavaField field = fieldIt.next(); if (field.isEnumConstant()) { String enumValue = field.getName(); if (helper.isAnnotationPresent(field, XmlEnumValue.class)) { enumValue = ((XmlEnumValue) helper.getAnnotation(field, XmlEnumValue.class)).value(); } info.addJavaFieldToXmlEnumValuePair(field.getName(), enumValue); } } //Add a non-named element declaration for each enumeration to trigger class generation ElementDeclaration elem = new ElementDeclaration(null, javaClass, javaClass.getQualifiedName(), false); //if(this.javaClassToTypeMappingInfos.get(javaClass) != null) { //elem.setTypeMappingInfo(this.javaClassToTypeMappingInfos.get(javaClass)); this.getLocalElements().add(elem); } private String decapitalize(String javaName) { char[] name = javaName.toCharArray(); int i = 0; while (i < name.length && (Character.isUpperCase(name[i]) || !Character.isLetter(name[i]))) { i++; } if (i > 0) { name[0] = Character.toLowerCase(name[0]); for (int j = 1; j < i - 1; j++) { name[j] = Character.toLowerCase(name[j]); } return new String(name); } else { return javaName; } } public String getSchemaTypeNameForClassName(String className) { String typeName = EMPTY_STRING; if (className.indexOf(DOLLAR_SIGN_CHR) != -1) { typeName = decapitalize(className.substring(className.lastIndexOf(DOLLAR_SIGN_CHR) + 1)); } else { typeName = decapitalize(className.substring(className.lastIndexOf(DOT_CHR) + 1)); } // now capitalize any characters that occur after a "break" boolean inBreak = false; StringBuffer toReturn = new StringBuffer(typeName.length()); for (int i = 0; i < typeName.length(); i++) { char next = typeName.charAt(i); if (Character.isDigit(next)) { if (!inBreak) { inBreak = true; } toReturn.append(next); } else { if (inBreak) { toReturn.append(Character.toUpperCase(next)); } else { toReturn.append(next); } } } return toReturn.toString(); } public QName getSchemaTypeOrNullFor(JavaClass javaClass) { if (javaClass == null) { return null; } // check user defined types first QName schemaType = (QName) userDefinedSchemaTypes.get(javaClass.getQualifiedName()); if (schemaType == null) { schemaType = (QName) helper.getXMLToJavaTypeMap().get(javaClass.getRawName()); } return schemaType; } public QName getSchemaTypeFor(JavaClass javaClass) { QName schemaType = getSchemaTypeOrNullFor(javaClass); if (schemaType == null) { return XMLConstants.ANY_SIMPLE_TYPE_QNAME; } return schemaType; } public boolean isCollectionType(Property field) { return isCollectionType(field.getType()); } public boolean isCollectionType(JavaClass type) { if (helper.getJavaClass(java.util.Collection.class).isAssignableFrom(type) || helper.getJavaClass(java.util.List.class).isAssignableFrom(type) || helper.getJavaClass(java.util.Set.class).isAssignableFrom(type)) { return true; } return false; } public NamespaceInfo processNamespaceInformation(XmlSchema xmlSchema) { NamespaceInfo info = new NamespaceInfo(); info.setNamespaceResolver(new NamespaceResolver()); String packageNamespace = null; if (xmlSchema != null) { String namespaceMapping = xmlSchema.namespace(); if (!(namespaceMapping.equals(EMPTY_STRING) || namespaceMapping.equals(XMLProcessor.DEFAULT))) { packageNamespace = namespaceMapping; } else if (namespaceMapping.equals(XMLProcessor.DEFAULT)) { packageNamespace = this.defaultTargetNamespace; } info.setNamespace(packageNamespace); XmlNs[] xmlns = xmlSchema.xmlns(); for (int i = 0; i < xmlns.length; i++) { XmlNs next = xmlns[i]; info.getNamespaceResolver().put(next.prefix(), next.namespaceURI()); } info.setAttributeFormQualified(xmlSchema.attributeFormDefault() == XmlNsForm.QUALIFIED); info.setElementFormQualified(xmlSchema.elementFormDefault() == XmlNsForm.QUALIFIED); // reflectively load XmlSchema class to avoid dependency try { Method locationMethod = PrivilegedAccessHelper.getDeclaredMethod(XmlSchema.class, "location", new Class[] {}); String location = (String) PrivilegedAccessHelper.invokeMethod(locationMethod, xmlSchema, new Object[] {}); if (location != null) { if (location.equals("##generate")) { location = null; } else if (location.equals(EMPTY_STRING)) { location = null; } } info.setLocation(location); } catch (Exception ex) { } } else { info.setNamespace(defaultTargetNamespace); } if (!info.isElementFormQualified() || info.isAttributeFormQualified()) { isDefaultNamespaceAllowed = false; } return info; } public HashMap<String, TypeInfo> getTypeInfo() { return typeInfo; } public ArrayList<JavaClass> getTypeInfoClasses() { return typeInfoClasses; } public HashMap<String, QName> getUserDefinedSchemaTypes() { return userDefinedSchemaTypes; } public NamespaceResolver getNamespaceResolver() { return namespaceResolver; } public String getSchemaTypeNameFor(JavaClass javaClass, XmlType xmlType) { String typeName = EMPTY_STRING; if (javaClass == null) { return typeName; } if (helper.isAnnotationPresent(javaClass, XmlType.class)) { // Figure out what kind of type we have // figure out type name XmlType typeAnnotation = (XmlType) helper.getAnnotation(javaClass, XmlType.class); typeName = typeAnnotation.name(); if (typeName.equals("#default")) { typeName = getSchemaTypeNameForClassName(javaClass.getName()); } } else { typeName = getSchemaTypeNameForClassName(javaClass.getName()); } return typeName; } public QName getQNameForProperty(String defaultName, JavaHasAnnotations element, NamespaceInfo namespaceInfo, String uri) { String name = XMLProcessor.DEFAULT; String namespace = XMLProcessor.DEFAULT; QName qName = null; if (helper.isAnnotationPresent(element, XmlAttribute.class)) { XmlAttribute xmlAttribute = (XmlAttribute) helper.getAnnotation(element, XmlAttribute.class); name = xmlAttribute.name(); namespace = xmlAttribute.namespace(); if (name.equals(XMLProcessor.DEFAULT)) { name = defaultName; } if (!namespace.equals(XMLProcessor.DEFAULT)) { qName = new QName(namespace, name); isDefaultNamespaceAllowed = false; } else { if (namespaceInfo.isAttributeFormQualified()) { qName = new QName(uri, name); } else { qName = new QName(name); } } } else { if (helper.isAnnotationPresent(element, XmlElement.class)) { XmlElement xmlElement = (XmlElement) helper.getAnnotation(element, XmlElement.class); name = xmlElement.name(); namespace = xmlElement.namespace(); } if (name.equals(XMLProcessor.DEFAULT)) { name = defaultName; } if (!namespace.equals(XMLProcessor.DEFAULT)) { qName = new QName(namespace, name); if (namespace.equals(XMLConstants.EMPTY_STRING)) { isDefaultNamespaceAllowed = false; } } else { if (namespaceInfo.isElementFormQualified()) { qName = new QName(uri, name); } else { qName = new QName(name); } } } return qName; } public HashMap<String, NamespaceInfo> getPackageToNamespaceMappings() { return packageToNamespaceMappings; } /** * Add a package name/NamespaceInfo entry to the map. This method will * lazy-load the map if necessary. * * @return */ public void addPackageToNamespaceMapping(String packageName, NamespaceInfo nsInfo) { if (packageToNamespaceMappings == null) { packageToNamespaceMappings = new HashMap<String, NamespaceInfo>(); } packageToNamespaceMappings.put(packageName, nsInfo); } public NamespaceInfo getNamespaceInfoForPackage(JavaClass javaClass) { String packageName = javaClass.getPackageName(); NamespaceInfo packageNamespace = packageToNamespaceMappings.get(packageName); if (packageNamespace == null) { packageNamespace = getNamespaceInfoForPackage(javaClass.getPackage(), packageName); } return packageNamespace; } public NamespaceInfo getNamespaceInfoForPackage(JavaPackage pack, String packageName) { NamespaceInfo packageNamespace = packageToNamespaceMappings.get(packageName); if (packageNamespace == null) { XmlSchema xmlSchema = (XmlSchema) helper.getAnnotation(pack, XmlSchema.class); packageNamespace = processNamespaceInformation(xmlSchema); // if it's still null, generate based on package name if (packageNamespace.getNamespace() == null) { packageNamespace.setNamespace(EMPTY_STRING); } if (helper.isAnnotationPresent(pack, XmlAccessorType.class)) { XmlAccessorType xmlAccessorType = (XmlAccessorType) helper.getAnnotation(pack, XmlAccessorType.class); packageNamespace.setAccessType(XmlAccessType.fromValue(xmlAccessorType.value().name())); } if (helper.isAnnotationPresent(pack, XmlAccessorOrder.class)) { XmlAccessorOrder xmlAccessorOrder = (XmlAccessorOrder) helper.getAnnotation(pack, XmlAccessorOrder.class); packageNamespace.setAccessOrder(XmlAccessOrder.fromValue(xmlAccessorOrder.value().name())); } packageToNamespaceMappings.put(packageName, packageNamespace); } return packageNamespace; } private void checkForCallbackMethods() { for (JavaClass next : typeInfoClasses) { if (next == null) { continue; } JavaClass unmarshallerCls = helper.getJavaClass(Unmarshaller.class); JavaClass marshallerCls = helper.getJavaClass(Marshaller.class); JavaClass objectCls = helper.getJavaClass(Object.class); JavaClass[] unmarshalParams = new JavaClass[] { unmarshallerCls, objectCls }; JavaClass[] marshalParams = new JavaClass[] { marshallerCls }; UnmarshalCallback unmarshalCallback = null; MarshalCallback marshalCallback = null; // look for before unmarshal callback if (next.getMethod("beforeUnmarshal", unmarshalParams) != null) { unmarshalCallback = new UnmarshalCallback(); unmarshalCallback.setDomainClassName(next.getQualifiedName()); unmarshalCallback.setHasBeforeUnmarshalCallback(); } // look for after unmarshal callback if (next.getMethod("afterUnmarshal", unmarshalParams) != null) { if (unmarshalCallback == null) { unmarshalCallback = new UnmarshalCallback(); unmarshalCallback.setDomainClassName(next.getQualifiedName()); } unmarshalCallback.setHasAfterUnmarshalCallback(); } // if before/after unmarshal callback was found, add the callback to // the list if (unmarshalCallback != null) { if (this.unmarshalCallbacks == null) { this.unmarshalCallbacks = new HashMap<String, UnmarshalCallback>(); } unmarshalCallbacks.put(next.getQualifiedName(), unmarshalCallback); } // look for before marshal callback if (next.getMethod("beforeMarshal", marshalParams) != null) { marshalCallback = new MarshalCallback(); marshalCallback.setDomainClassName(next.getQualifiedName()); marshalCallback.setHasBeforeMarshalCallback(); } // look for after marshal callback if (next.getMethod("afterMarshal", marshalParams) != null) { if (marshalCallback == null) { marshalCallback = new MarshalCallback(); marshalCallback.setDomainClassName(next.getQualifiedName()); } marshalCallback.setHasAfterMarshalCallback(); } // if before/after marshal callback was found, add the callback to // the list if (marshalCallback != null) { if (this.marshalCallbacks == null) { this.marshalCallbacks = new HashMap<String, MarshalCallback>(); } marshalCallbacks.put(next.getQualifiedName(), marshalCallback); } } } public HashMap<String, MarshalCallback> getMarshalCallbacks() { return this.marshalCallbacks; } public HashMap<String, UnmarshalCallback> getUnmarshalCallbacks() { return this.unmarshalCallbacks; } public JavaClass[] processObjectFactory(JavaClass objectFactoryClass, ArrayList<JavaClass> classes) { // if there is an xml-registry from XML for this JavaClass, create a map // of method names to XmlElementDecl objects to simplify processing // later on in this method Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl> elemDecls = new HashMap<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl>(); org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry xmlReg = xmlRegistries.get(objectFactoryClass.getQualifiedName()); if (xmlReg != null) { // process xml-element-decl entries for (org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl xmlElementDecl : xmlReg.getXmlElementDecl()) { // key each element-decl on method name elemDecls.put(xmlElementDecl.getJavaMethod(), xmlElementDecl); } } Collection methods = objectFactoryClass.getDeclaredMethods(); Iterator methodsIter = methods.iterator(); NamespaceInfo namespaceInfo = getNamespaceInfoForPackage(objectFactoryClass); while (methodsIter.hasNext()) { JavaMethod next = (JavaMethod) methodsIter.next(); if (next.getName().startsWith(CREATE)) { JavaClass type = next.getReturnType(); if (JAVAX_XML_BIND_JAXBELEMENT.equals(type.getName())) { Object[] actutalTypeArguments = next.getReturnType().getActualTypeArguments().toArray(); if(actutalTypeArguments.length == 0) { type = helper.getJavaClass(Object.class); } else { type = (JavaClass) next.getReturnType().getActualTypeArguments().toArray()[0]; } } else { this.factoryMethods.put(next.getReturnType().getRawName(), next); } // if there's an XmlElementDecl for this method from XML, use it // - otherwise look for an annotation org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl xmlEltDecl = elemDecls.get(next.getName()); if (xmlEltDecl != null || helper.isAnnotationPresent(next, XmlElementDecl.class)) { QName qname; QName substitutionHead = null; String url; String localName; String defaultValue = null; Class scopeClass = javax.xml.bind.annotation.XmlElementDecl.GLOBAL.class; if (xmlEltDecl != null) { url = xmlEltDecl.getNamespace(); localName = xmlEltDecl.getName(); String scopeClassName = xmlEltDecl.getScope(); if (!scopeClassName.equals(ELEMENT_DECL_GLOBAL)) { JavaClass jScopeClass = helper.getJavaClass(scopeClassName); if (jScopeClass != null) { scopeClass = helper.getClassForJavaClass(jScopeClass); if (scopeClass == null) { scopeClass = javax.xml.bind.annotation.XmlElementDecl.GLOBAL.class; } } } if (!xmlEltDecl.getSubstitutionHeadName().equals(EMPTY_STRING)) { String subHeadLocal = xmlEltDecl.getSubstitutionHeadName(); String subHeadNamespace = xmlEltDecl.getSubstitutionHeadNamespace(); if (subHeadNamespace.equals(XMLProcessor.DEFAULT)) { subHeadNamespace = namespaceInfo.getNamespace(); } substitutionHead = new QName(subHeadNamespace, subHeadLocal); } if (!(xmlEltDecl.getDefaultValue().length() == 1 && xmlEltDecl.getDefaultValue().startsWith(ELEMENT_DECL_DEFAULT))) { defaultValue = xmlEltDecl.getDefaultValue(); } } else { // there was no xml-element-decl for this method in XML, // so use the annotation XmlElementDecl elementDecl = (XmlElementDecl) helper.getAnnotation(next, XmlElementDecl.class); url = elementDecl.namespace(); localName = elementDecl.name(); scopeClass = elementDecl.scope(); if (!elementDecl.substitutionHeadName().equals(EMPTY_STRING)) { String subHeadLocal = elementDecl.substitutionHeadName(); String subHeadNamespace = elementDecl.substitutionHeadNamespace(); if (subHeadNamespace.equals(XMLProcessor.DEFAULT)) { subHeadNamespace = namespaceInfo.getNamespace(); } substitutionHead = new QName(subHeadNamespace, subHeadLocal); } if (!(elementDecl.defaultValue().length() == 1 && elementDecl.defaultValue().startsWith(ELEMENT_DECL_DEFAULT))) { defaultValue = elementDecl.defaultValue(); } } if (XMLProcessor.DEFAULT.equals(url)) { url = namespaceInfo.getNamespace(); } qname = new QName(url, localName); boolean isList = false; if (JAVA_UTIL_LIST.equals(type.getName())) { isList = true; if (type.hasActualTypeArguments()) { type = (JavaClass) type.getActualTypeArguments().toArray()[0]; } } ElementDeclaration declaration = new ElementDeclaration(qname, type, type.getQualifiedName(), isList, scopeClass); if (substitutionHead != null) { declaration.setSubstitutionHead(substitutionHead); } if (defaultValue != null) { declaration.setDefaultValue(defaultValue); } if (helper.isAnnotationPresent(next, XmlJavaTypeAdapter.class)) { XmlJavaTypeAdapter typeAdapter = (XmlJavaTypeAdapter) helper.getAnnotation(next, XmlJavaTypeAdapter.class); Class typeAdapterClass = typeAdapter.value(); declaration.setJavaTypeAdapterClass(typeAdapterClass); Class declJavaType = CompilerHelper.getTypeFromAdapterClass(typeAdapterClass); declaration.setJavaType(helper.getJavaClass(declJavaType)); declaration.setAdaptedJavaType(type); } HashMap<QName, ElementDeclaration> elements = getElementDeclarationsForScope(scopeClass.getName()); if (elements == null) { elements = new HashMap<QName, ElementDeclaration>(); this.elementDeclarations.put(scopeClass.getName(), elements); } elements.put(qname, declaration); } if (!helper.isBuiltInJavaType(type) && !helper.classExistsInArray(type, classes)) { classes.add(type); } } } if (classes.size() > 0) { return classes.toArray(new JavaClass[classes.size()]); } else { return new JavaClass[0]; } } /** * Lazy load and return the map of global elements. * * @return */ public HashMap<QName, ElementDeclaration> getGlobalElements() { return this.elementDeclarations.get(XmlElementDecl.GLOBAL.class.getName()); } public void updateGlobalElements(JavaClass[] classesToProcess) { // Once all the global element declarations have been created, make sure // that any ones that have // a substitution head set are added to the list of substitutable // elements on the declaration for that // head. // Look for XmlRootElement declarations for (JavaClass javaClass : classesToProcess) { TypeInfo info = typeInfo.get(javaClass.getQualifiedName()); if (info == null) { continue; } if (!info.isTransient() && info.isSetXmlRootElement()) { org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = info.getXmlRootElement(); NamespaceInfo namespaceInfo; namespaceInfo = getNamespaceInfoForPackage(javaClass); String elementName = xmlRE.getName(); if (elementName.equals(XMLProcessor.DEFAULT) || elementName.equals(EMPTY_STRING)) { if (javaClass.getName().indexOf(DOLLAR_SIGN_CHR) != -1) { elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf(DOLLAR_SIGN_CHR) + 1)); } else { elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf(DOT_CHR) + 1)); } // TCK Compliancy if (elementName.length() >= 3) { int idx = elementName.length() - 1; char ch = elementName.charAt(idx - 1); if (Character.isDigit(ch)) { char lastCh = Character.toUpperCase(elementName.charAt(idx)); elementName = elementName.substring(0, idx) + lastCh; } } } String rootNamespace = xmlRE.getNamespace(); QName rootElemName = null; if (rootNamespace.equals(XMLProcessor.DEFAULT)) { if (namespaceInfo == null) { rootElemName = new QName(elementName); } else { String rootNS = namespaceInfo.getNamespace(); rootElemName = new QName(rootNS, elementName); if (rootNS.equals(XMLConstants.EMPTY_STRING)) { isDefaultNamespaceAllowed = false; } } } else { rootElemName = new QName(rootNamespace, elementName); if (rootNamespace.equals(XMLConstants.EMPTY_STRING)) { isDefaultNamespaceAllowed = false; } } ElementDeclaration declaration = new ElementDeclaration(rootElemName, javaClass, javaClass.getQualifiedName(), false); declaration.setIsXmlRootElement(true); this.getGlobalElements().put(rootElemName, declaration); this.xmlRootElements.put(javaClass.getQualifiedName(), declaration); } } Iterator<QName> elementQnames = this.getGlobalElements().keySet().iterator(); while (elementQnames.hasNext()) { QName next = elementQnames.next(); ElementDeclaration nextDeclaration = this.getGlobalElements().get(next); QName substitutionHead = nextDeclaration.getSubstitutionHead(); while (substitutionHead != null) { ElementDeclaration rootDeclaration = this.getGlobalElements().get(substitutionHead); rootDeclaration.addSubstitutableElement(nextDeclaration); substitutionHead = rootDeclaration.getSubstitutionHead(); } } } private void addReferencedElement(Property property, ElementDeclaration referencedElement) { property.addReferencedElement(referencedElement); if (referencedElement.getSubstitutableElements() != null && referencedElement.getSubstitutableElements().size() > 0) { for (ElementDeclaration substitutable : referencedElement.getSubstitutableElements()) { addReferencedElement(property, substitutable); } } } /** * Returns true if the field or method passed in is annotated with JAXB * annotations. */ private boolean hasJAXBAnnotations(JavaHasAnnotations elem) { return (helper.isAnnotationPresent(elem, XmlElement.class) || helper.isAnnotationPresent(elem, XmlAttribute.class) || helper.isAnnotationPresent(elem, XmlAnyElement.class) || helper.isAnnotationPresent(elem, XmlAnyAttribute.class) || helper.isAnnotationPresent(elem, XmlValue.class) || helper.isAnnotationPresent(elem, XmlElements.class) || helper.isAnnotationPresent(elem, XmlElementRef.class) || helper.isAnnotationPresent(elem, XmlElementRefs.class) || helper.isAnnotationPresent(elem, XmlID.class) || helper.isAnnotationPresent(elem, XmlSchemaType.class) || helper.isAnnotationPresent(elem, XmlElementWrapper.class) || helper.isAnnotationPresent(elem, XmlList.class) || helper.isAnnotationPresent(elem, XmlMimeType.class) || helper.isAnnotationPresent(elem, XmlIDREF.class) || helper.isAnnotationPresent(elem, XmlPath.class) || helper.isAnnotationPresent(elem, XmlPaths.class) || helper.isAnnotationPresent(elem, XmlInverseReference.class) || helper.isAnnotationPresent(elem, XmlReadOnly.class) || helper.isAnnotationPresent(elem, XmlWriteOnly.class) || helper.isAnnotationPresent(elem, XmlCDATA.class) || helper.isAnnotationPresent(elem, XmlAccessMethods.class) || helper.isAnnotationPresent(elem, XmlNullPolicy.class) || helper.isAnnotationPresent(elem, XmlJavaTypeAdapter.class)); } private void validateElementIsInPropOrder(TypeInfo info, String name) { if (info.isTransient()) { return; } // If a property is marked with XMLElement, XMLElements, XMLElementRef // or XMLElementRefs // and propOrder is not empty then it must be in the proporder list String[] propOrder = info.getPropOrder(); if (propOrder.length > 0) { if (propOrder.length == 1 && propOrder[0].equals(EMPTY_STRING)) { return; } List<String> propOrderList = Arrays.asList(info.getPropOrder()); if (!propOrderList.contains(name)) { throw JAXBException.missingPropertyInPropOrder(name); } } } private void validatePropOrderForInfo(TypeInfo info) { if (info.isTransient()) { return; } // Ensure that all properties in the propOrder list actually exist String[] propOrder = info.getPropOrder(); int propOrderLength = propOrder.length; if (propOrderLength > 0) { for (int i = 1; i < propOrderLength; i++) { String nextPropName = propOrder[i]; if (!nextPropName.equals(EMPTY_STRING) && !info.getPropertyNames().contains(nextPropName)) { throw JAXBException.nonExistentPropertyInPropOrder(nextPropName); } } } } private void validateXmlValueFieldOrProperty(JavaClass cls, Property property) { JavaClass ptype = property.getActualType(); String propName = property.getPropertyName(); JavaClass parent = cls.getSuperclass(); while (parent != null && !(parent.getQualifiedName().equals(JAVA_LANG_OBJECT))) { TypeInfo parentTypeInfo = typeInfo.get(parent.getQualifiedName()); if (parentTypeInfo != null || shouldGenerateTypeInfo(parent)) { throw JAXBException.propertyOrFieldCannotBeXmlValue(propName); } parent = parent.getSuperclass(); } QName schemaQName = getSchemaTypeOrNullFor(ptype); if (schemaQName == null) { TypeInfo refInfo = typeInfo.get(ptype.getQualifiedName()); if (refInfo != null) { if (!refInfo.isPostBuilt()) { postBuildTypeInfo(new JavaClass[] { ptype }); } } else if (shouldGenerateTypeInfo(ptype)) { JavaClass[] jClasses = new JavaClass[] { ptype }; buildNewTypeInfo(jClasses); refInfo = typeInfo.get(ptype.getQualifiedName()); } if (refInfo != null && !refInfo.isEnumerationType() && refInfo.getXmlValueProperty() == null) { throw JAXBException.invalidTypeForXmlValueField(propName); } } } public boolean isMapType(JavaClass type) { return helper.getJavaClass(java.util.Map.class).isAssignableFrom(type); } private Class generateWrapperForMapClass(JavaClass mapClass, JavaClass keyClass, JavaClass valueClass, TypeMappingInfo typeMappingInfo) { String packageName = JAXB_DEV; NamespaceResolver combinedNamespaceResolver = new NamespaceResolver(); if (!helper.isBuiltInJavaType(keyClass)) { String keyPackageName = keyClass.getPackageName(); packageName = packageName + DOT_CHR + keyPackageName; NamespaceInfo keyNamespaceInfo = getNamespaceInfoForPackage(keyClass); if (keyNamespaceInfo != null) { java.util.Vector<Namespace> namespaces = keyNamespaceInfo.getNamespaceResolver().getNamespaces(); for (Namespace n : namespaces) { combinedNamespaceResolver.put(n.getPrefix(), n.getNamespaceURI()); } } } if (!helper.isBuiltInJavaType(valueClass)) { String valuePackageName = valueClass.getPackageName(); packageName = packageName + DOT_CHR + valuePackageName; NamespaceInfo valueNamespaceInfo = getNamespaceInfoForPackage(valueClass); if (valueNamespaceInfo != null) { java.util.Vector<Namespace> namespaces = valueNamespaceInfo.getNamespaceResolver().getNamespaces(); for (Namespace n : namespaces) { combinedNamespaceResolver.put(n.getPrefix(), n.getNamespaceURI()); } } } String namespace = this.defaultTargetNamespace; if (namespace == null) { namespace = EMPTY_STRING; } NamespaceInfo namespaceInfo = packageToNamespaceMappings.get(mapClass.getPackageName()); if (namespaceInfo == null) { namespaceInfo = getPackageToNamespaceMappings().get(packageName); } else { if (namespaceInfo.getNamespace() != null) { namespace = namespaceInfo.getNamespace(); } getPackageToNamespaceMappings().put(packageName, namespaceInfo); } if (namespaceInfo == null) { namespaceInfo = new NamespaceInfo(); namespaceInfo.setNamespace(namespace); namespaceInfo.setNamespaceResolver(combinedNamespaceResolver); getPackageToNamespaceMappings().put(packageName, namespaceInfo); } int beginIndex = keyClass.getName().lastIndexOf(DOT_CHR) + 1; String keyName = keyClass.getName().substring(beginIndex); int dollarIndex = keyName.indexOf(DOLLAR_SIGN_CHR); if (dollarIndex > -1) { keyName = keyName.substring(dollarIndex + 1); } beginIndex = valueClass.getName().lastIndexOf(DOT_CHR) + 1; String valueName = valueClass.getName().substring(beginIndex); dollarIndex = valueName.indexOf(DOLLAR_SIGN_CHR); if (dollarIndex > -1) { valueName = valueName.substring(dollarIndex + 1); } String collectionClassShortName = mapClass.getRawName().substring(mapClass.getRawName().lastIndexOf(DOT_CHR) + 1); String suggestedClassName = keyName + valueName + collectionClassShortName; String qualifiedClassName = packageName + DOT_CHR + suggestedClassName; qualifiedClassName = getNextAvailableClassName(qualifiedClassName); String qualifiedInternalClassName = qualifiedClassName.replace(DOT_CHR, SLASH_CHR); String internalKeyName = keyClass.getQualifiedName().replace(DOT_CHR, SLASH_CHR); String internalValueName = valueClass.getQualifiedName().replace(DOT_CHR, SLASH_CHR); Type mapType = Type.getType(L + mapClass.getRawName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON); ClassWriter cw = new ClassWriter(false); CodeVisitor cv; cw.visit(Constants.V1_5, Constants.ACC_PUBLIC + Constants.ACC_SUPER, qualifiedInternalClassName, "org/eclipse/persistence/internal/jaxb/many/MapValue", null, "StringEmployeeMap.java"); // FIELD ATTRIBUTES RuntimeVisibleAnnotations fieldAttrs1 = new RuntimeVisibleAnnotations(); if (typeMappingInfo != null) { java.lang.annotation.Annotation[] annotations = typeMappingInfo.getAnnotations(); if (annotations != null) { for (int i = 0; i < annotations.length; i++) { java.lang.annotation.Annotation nextAnnotation = annotations[i]; if (nextAnnotation != null && !(nextAnnotation instanceof XmlElement) && !(nextAnnotation instanceof XmlJavaTypeAdapter)) { String annotationClassName = nextAnnotation.annotationType().getName(); Annotation fieldAttrs1ann0 = new Annotation(L + annotationClassName.replace(DOT_CHR, SLASH_CHR) + SEMI_COLON); fieldAttrs1.annotations.add(fieldAttrs1ann0); for (Method next : nextAnnotation.annotationType().getDeclaredMethods()) { try { Object nextValue = next.invoke(nextAnnotation, new Object[] {}); if (nextValue instanceof Class) { Type nextType = Type.getType(L + ((Class) nextValue).getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON); nextValue = nextType; } fieldAttrs1ann0.add(next.getName(), nextValue); } catch (InvocationTargetException ex) { // ignore the invocation target exception here. } catch (IllegalAccessException ex) { } } } } } } // FIELD ATTRIBUTES SignatureAttribute fieldAttrs2 = new SignatureAttribute(L + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;"); fieldAttrs1.next = fieldAttrs2; cw.visitField(Constants.ACC_PUBLIC, "entry", L + mapType.getInternalName() + SEMI_COLON, null, fieldAttrs1); cv = cw.visitMethod(Constants.ACC_PUBLIC, "<init>", "()V", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitMethodInsn(Constants.INVOKESPECIAL, "org/eclipse/persistence/internal/jaxb/many/MapValue", "<init>", "()V"); cv.visitInsn(Constants.RETURN); cv.visitMaxs(1, 1); // METHOD ATTRIBUTES RuntimeVisibleAnnotations methodAttrs1 = new RuntimeVisibleAnnotations(); Annotation methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;"); methodAttrs1.annotations.add(methodAttrs1ann0); SignatureAttribute methodAttrs2 = new SignatureAttribute("(L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;)V"); methodAttrs1.next = methodAttrs2; cv = cw.visitMethod(Constants.ACC_PUBLIC, "setItem", "(L" + mapType.getInternalName() + ";)V", null, methodAttrs1); Label l0 = new Label(); cv.visitLabel(l0); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitVarInsn(Constants.ALOAD, 1); cv.visitFieldInsn(Constants.PUTFIELD, qualifiedInternalClassName, "entry", L + mapType.getInternalName() + SEMI_COLON); cv.visitInsn(Constants.RETURN); Label l1 = new Label(); cv.visitLabel(l1); // CODE ATTRIBUTE LocalVariableTypeTableAttribute cvAttr = new LocalVariableTypeTableAttribute(); cv.visitAttribute(cvAttr); cv.visitMaxs(2, 2); // METHOD ATTRIBUTES methodAttrs1 = new RuntimeVisibleAnnotations(); methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;"); methodAttrs1.annotations.add(methodAttrs1ann0); methodAttrs2 = new SignatureAttribute("()L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;"); methodAttrs1.next = methodAttrs2; cv = cw.visitMethod(Constants.ACC_PUBLIC, "getItem", "()L" + mapType.getInternalName() + SEMI_COLON, null, methodAttrs1); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitFieldInsn(Constants.GETFIELD, qualifiedInternalClassName, "entry", L + mapType.getInternalName() + SEMI_COLON); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "getItem", "()Ljava/lang/Object;", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "getItem", "()L" + mapType.getInternalName() + SEMI_COLON); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "setItem", "(Ljava/lang/Object;)V", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitVarInsn(Constants.ALOAD, 1); cv.visitTypeInsn(Constants.CHECKCAST, mapType.getInternalName()); cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "setItem", "(L" + mapType.getInternalName() + ";)V"); cv.visitInsn(Constants.RETURN); cv.visitMaxs(2, 2); // CLASS ATTRIBUTE RuntimeVisibleAnnotations annotationsAttr = new RuntimeVisibleAnnotations(); Annotation attrann0 = new Annotation("Ljavax/xml/bind/annotation/XmlType;"); attrann0.add("namespace", namespace); annotationsAttr.annotations.add(attrann0); cw.visitAttribute(annotationsAttr); SignatureAttribute attr = new SignatureAttribute("Lorg/eclipse/persistence/internal/jaxb/many/MapValue<L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;>;"); cw.visitAttribute(attr); cw.visitEnd(); byte[] classBytes = cw.toByteArray(); return generateClassFromBytes(qualifiedClassName, classBytes); } private Class generateWrapperForArrayClass(JavaClass arrayClass, TypeMappingInfo typeMappingInfo, Class xmlElementType, List<JavaClass> classesToProcess) { JavaClass componentClass = null; if (typeMappingInfo != null && xmlElementType != null) { componentClass = helper.getJavaClass(xmlElementType); } else { componentClass = arrayClass.getComponentType(); } if (componentClass.isArray()) { Class nestedArrayClass = arrayClassesToGeneratedClasses.get(componentClass.getName()); if(nestedArrayClass == null) { nestedArrayClass = generateWrapperForArrayClass(componentClass, typeMappingInfo, xmlElementType, classesToProcess); arrayClassesToGeneratedClasses.put(componentClass.getName(), nestedArrayClass); classesToProcess.add(helper.getJavaClass(nestedArrayClass)); } return generateArrayValue(arrayClass, componentClass, helper.getJavaClass(nestedArrayClass), typeMappingInfo); } else { return generateArrayValue(arrayClass, componentClass, componentClass, typeMappingInfo); } } private Class generateArrayValue(JavaClass arrayClass, JavaClass componentClass, JavaClass nestedClass, TypeMappingInfo typeMappingInfo) { String packageName; String qualifiedClassName; if (componentClass.isArray()) { packageName = componentClass.getPackageName(); qualifiedClassName = nestedClass.getQualifiedName() + ARRAY_CLASS_NAME_SUFFIX; } else { if (componentClass.isPrimitive()) { packageName = ARRAY_PACKAGE_NAME; qualifiedClassName = packageName + DOT_CHR + componentClass.getName() + ARRAY_CLASS_NAME_SUFFIX; } else { packageName = ARRAY_PACKAGE_NAME + DOT_CHR + componentClass.getPackageName(); if (componentClass.isMemberClass()) { qualifiedClassName = componentClass.getName(); qualifiedClassName = qualifiedClassName.substring(qualifiedClassName.indexOf(DOLLAR_SIGN_CHR) + 1); qualifiedClassName = ARRAY_PACKAGE_NAME + DOT_CHR + componentClass.getPackageName() + DOT_CHR + qualifiedClassName + ARRAY_CLASS_NAME_SUFFIX; } else { qualifiedClassName = ARRAY_PACKAGE_NAME + DOT_CHR + componentClass.getQualifiedName() + ARRAY_CLASS_NAME_SUFFIX; } } if (componentClass.isPrimitive() || helper.isBuiltInJavaType(componentClass)) { NamespaceInfo namespaceInfo = getPackageToNamespaceMappings().get(packageName); if (namespaceInfo == null) { namespaceInfo = new NamespaceInfo(); namespaceInfo.setNamespace(ARRAY_NAMESPACE); namespaceInfo.setNamespaceResolver(new NamespaceResolver()); getPackageToNamespaceMappings().put(packageName, namespaceInfo); } } else { NamespaceInfo namespaceInfo = getNamespaceInfoForPackage(componentClass.getPackage(), componentClass.getPackageName()); getPackageToNamespaceMappings().put(packageName, namespaceInfo); } } String qualifiedInternalClassName = qualifiedClassName.replace(DOT_CHR, SLASH_CHR); String superClassName; if (componentClass.isArray()) { superClassName = "org/eclipse/persistence/internal/jaxb/many/MultiDimensionalArrayValue"; } else { superClassName = "org/eclipse/persistence/internal/jaxb/many/ArrayValue"; } ClassWriter cw = new ClassWriter(false); cw.visit(Constants.V1_5, Constants.ACC_PUBLIC + Constants.ACC_SUPER, qualifiedInternalClassName, superClassName, null, null); CodeVisitor cv = cw.visitMethod(Constants.ACC_PUBLIC, "<init>", "()V", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitMethodInsn(Constants.INVOKESPECIAL, superClassName, "<init>", "()V"); cv.visitInsn(Constants.RETURN); cv.visitMaxs(1, 1); if (componentClass.isArray()) { cv = cw.visitMethod(Constants.ACC_PROTECTED, "adaptedClass", "()Ljava/lang/Class;", null, null); cv.visitLdcInsn(Type.getType(L + nestedClass.getQualifiedName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON)); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); } cv = cw.visitMethod(Constants.ACC_PROTECTED, "componentClass", "()Ljava/lang/Class;", null, null); JavaClass baseComponentClass = getBaseComponentType(componentClass); if (baseComponentClass.isPrimitive()) { cv.visitFieldInsn(Constants.GETSTATIC, getObjectType(baseComponentClass).getQualifiedName().replace(DOT_CHR, SLASH_CHR), "TYPE", "Ljava/lang/Class;"); } else { cv.visitLdcInsn(Type.getType(L + baseComponentClass.getQualifiedName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON)); } cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); RuntimeVisibleAnnotations getAdaptedValueMethodAnnotations = new RuntimeVisibleAnnotations(); // process any annotations set on the TypeMappingInfo instance java.lang.annotation.Annotation[] annotations; if (typeMappingInfo != null && ((annotations = getAnnotations(typeMappingInfo)) != null)) { for (java.lang.annotation.Annotation nextAnnotation : annotations) { if (nextAnnotation != null && !(nextAnnotation instanceof XmlElement) && !(nextAnnotation instanceof XmlJavaTypeAdapter)) { Annotation annotation = new Annotation(L + nextAnnotation.annotationType().getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON); for (Method next : nextAnnotation.annotationType().getDeclaredMethods()) { try { Object nextValue = next.invoke(nextAnnotation, new Object[] {}); if (nextValue instanceof Class) { nextValue = Type.getType(L + ((Class) nextValue).getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON); } annotation.add(next.getName(), nextValue); } catch (InvocationTargetException ex) { } catch (IllegalAccessException ex) { } } getAdaptedValueMethodAnnotations.annotations.add(annotation); } } } Annotation xmlElementAnnotation = new Annotation("Ljavax/xml/bind/annotation/XmlElement;"); xmlElementAnnotation.add("name", ITEM); xmlElementAnnotation.add("type", Type.getType(L + getObjectType(nestedClass).getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON)); getAdaptedValueMethodAnnotations.annotations.add(xmlElementAnnotation); cv = cw.visitMethod(Constants.ACC_PUBLIC, "getAdaptedValue", "()Ljava/util/List;", null, getAdaptedValueMethodAnnotations); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitFieldInsn(Constants.GETFIELD, qualifiedInternalClassName, "adaptedValue", "Ljava/util/List;"); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); return generateClassFromBytes(qualifiedClassName, cw.toByteArray()); } private JavaClass getBaseComponentType(JavaClass javaClass) { JavaClass componentType = javaClass.getComponentType(); if (null == componentType) { return javaClass; } if (!componentType.isArray()) { return componentType; } return getBaseComponentType(componentType); } private JavaClass getObjectType(JavaClass javaClass) { if (javaClass.isPrimitive()) { String primitiveClassName = javaClass.getRawName(); Class primitiveClass = getPrimitiveClass(primitiveClassName); return helper.getJavaClass(getObjectClass(primitiveClass)); } return javaClass; } private Class generateCollectionValue(JavaClass collectionClass, TypeMappingInfo typeMappingInfo, Class xmlElementType) { JavaClass componentClass; if (typeMappingInfo != null && xmlElementType != null) { componentClass = helper.getJavaClass(xmlElementType); } else if (collectionClass.hasActualTypeArguments()) { componentClass = ((JavaClass) collectionClass.getActualTypeArguments().toArray()[0]); } else { componentClass = helper.getJavaClass(Object.class); } if (componentClass.isPrimitive()) { Class primitiveClass = getPrimitiveClass(componentClass.getRawName()); componentClass = helper.getJavaClass(getObjectClass(primitiveClass)); } NamespaceInfo namespaceInfo = packageToNamespaceMappings.get(collectionClass.getPackageName()); String namespace = EMPTY_STRING; if (this.defaultTargetNamespace != null) { namespace = this.defaultTargetNamespace; } NamespaceInfo componentNamespaceInfo = getNamespaceInfoForPackage(componentClass); String packageName = componentClass.getPackageName(); packageName = "jaxb.dev.java.net." + packageName; if (namespaceInfo == null) { namespaceInfo = getPackageToNamespaceMappings().get(packageName); } else { getPackageToNamespaceMappings().put(packageName, namespaceInfo); if (namespaceInfo.getNamespace() != null) { namespace = namespaceInfo.getNamespace(); } } if (namespaceInfo == null) { if (componentNamespaceInfo != null) { namespaceInfo = componentNamespaceInfo; } else { namespaceInfo = new NamespaceInfo(); namespaceInfo.setNamespaceResolver(new NamespaceResolver()); } getPackageToNamespaceMappings().put(packageName, namespaceInfo); } String name = componentClass.getName(); Type componentType = Type.getType(L + componentClass.getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON); String componentTypeInternalName = null; if (name.equals("[B")) { name = "byteArray"; componentTypeInternalName = componentType.getInternalName(); } else if (name.equals("[Ljava.lang.Byte;")) { name = "ByteArray"; componentTypeInternalName = componentType.getInternalName() + SEMI_COLON; } else { componentTypeInternalName = L + componentType.getInternalName() + SEMI_COLON; } int beginIndex = name.lastIndexOf(DOT_CHR) + 1; name = name.substring(beginIndex); int dollarIndex = name.indexOf(DOLLAR_SIGN_CHR); if (dollarIndex > -1) { name = name.substring(dollarIndex + 1); } String collectionClassRawName = collectionClass.getRawName(); String collectionClassShortName = collectionClassRawName.substring(collectionClassRawName.lastIndexOf(DOT_CHR) + 1); String suggestedClassName = collectionClassShortName + "Of" + name; String qualifiedClassName = packageName + DOT_CHR + suggestedClassName; qualifiedClassName = getNextAvailableClassName(qualifiedClassName); String className = qualifiedClassName.substring(qualifiedClassName.lastIndexOf(DOT_CHR) + 1); Type collectionType = Type.getType(L + collectionClassRawName.replace(DOT_CHR, SLASH_CHR) + SEMI_COLON); String qualifiedInternalClassName = qualifiedClassName.replace(DOT_CHR, SLASH_CHR); ClassWriter cw = new ClassWriter(false); CodeVisitor cv; cw.visit(Constants.V1_5, Constants.ACC_PUBLIC + Constants.ACC_SUPER, qualifiedInternalClassName, "org/eclipse/persistence/internal/jaxb/many/CollectionValue", null, className.replace(DOT_CHR, SLASH_CHR) + ".java"); // FIELD ATTRIBUTES RuntimeVisibleAnnotations fieldAttrs1 = new RuntimeVisibleAnnotations(); if (typeMappingInfo != null) { java.lang.annotation.Annotation[] annotations = getAnnotations(typeMappingInfo); if (annotations != null) { for (int i = 0; i < annotations.length; i++) { java.lang.annotation.Annotation nextAnnotation = annotations[i]; if (nextAnnotation != null && !(nextAnnotation instanceof XmlElement) && !(nextAnnotation instanceof XmlJavaTypeAdapter)) { String annotationClassName = nextAnnotation.annotationType().getName(); Annotation fieldAttrs1ann0 = new Annotation(L + annotationClassName.replace(DOT_CHR, SLASH_CHR) + SEMI_COLON); fieldAttrs1.annotations.add(fieldAttrs1ann0); for (Method next : nextAnnotation.annotationType().getDeclaredMethods()) { try { Object nextValue = next.invoke(nextAnnotation, new Object[] {}); if (nextValue instanceof Class) { Type nextType = Type.getType(L + ((Class) nextValue).getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON); nextValue = nextType; } fieldAttrs1ann0.add(next.getName(), nextValue); } catch (InvocationTargetException ex) { // ignore the invocation target exception here. } catch (IllegalAccessException ex) { } } } } } } SignatureAttribute fieldAttrs2 = new SignatureAttribute(L + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;"); fieldAttrs1.next = fieldAttrs2; cw.visitField(Constants.ACC_PUBLIC, ITEM, L + collectionType.getInternalName() + SEMI_COLON, null, fieldAttrs1); cv = cw.visitMethod(Constants.ACC_PUBLIC, "<init>", "()V", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitMethodInsn(Constants.INVOKESPECIAL, "org/eclipse/persistence/internal/jaxb/many/CollectionValue", "<init>", "()V"); cv.visitInsn(Constants.RETURN); cv.visitMaxs(1, 1); // METHOD ATTRIBUTES RuntimeVisibleAnnotations methodAttrs1 = new RuntimeVisibleAnnotations(); Annotation methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;"); methodAttrs1.annotations.add(methodAttrs1ann0); SignatureAttribute methodAttrs2 = new SignatureAttribute("(L" + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;)V"); methodAttrs1.next = methodAttrs2; cv = cw.visitMethod(Constants.ACC_PUBLIC, "setItem", "(L" + collectionType.getInternalName() + ";)V", null, methodAttrs1); Label l0 = new Label(); cv.visitLabel(l0); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitVarInsn(Constants.ALOAD, 1); cv.visitFieldInsn(Constants.PUTFIELD, qualifiedInternalClassName, ITEM, L + collectionType.getInternalName() + SEMI_COLON); cv.visitInsn(Constants.RETURN); Label l1 = new Label(); cv.visitLabel(l1); // CODE ATTRIBUTE LocalVariableTypeTableAttribute cvAttr = new LocalVariableTypeTableAttribute(); cv.visitAttribute(cvAttr); cv.visitMaxs(2, 2); // METHOD ATTRIBUTES methodAttrs1 = new RuntimeVisibleAnnotations(); methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;"); methodAttrs1.annotations.add(methodAttrs1ann0); methodAttrs2 = new SignatureAttribute("()L" + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;"); methodAttrs1.next = methodAttrs2; cv = cw.visitMethod(Constants.ACC_PUBLIC, "getItem", "()L" + collectionType.getInternalName() + SEMI_COLON, null, methodAttrs1); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitFieldInsn(Constants.GETFIELD, qualifiedInternalClassName, ITEM, L + collectionType.getInternalName() + SEMI_COLON); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "getItem", "()Ljava/lang/Object;", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "getItem", "()L" + collectionType.getInternalName() + SEMI_COLON); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "setItem", "(Ljava/lang/Object;)V", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitVarInsn(Constants.ALOAD, 1); cv.visitTypeInsn(Constants.CHECKCAST, EMPTY_STRING + collectionType.getInternalName() + EMPTY_STRING); cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "setItem", "(L" + collectionType.getInternalName() + ";)V"); cv.visitInsn(Constants.RETURN); cv.visitMaxs(2, 2); // CLASS ATTRIBUTE RuntimeVisibleAnnotations annotationsAttr = new RuntimeVisibleAnnotations(); Annotation attrann0 = new Annotation("Ljavax/xml/bind/annotation/XmlType;"); attrann0.add("namespace", namespace); annotationsAttr.annotations.add(attrann0); cw.visitAttribute(annotationsAttr); SignatureAttribute attr = new SignatureAttribute("Lorg/eclipse/persistence/internal/jaxb/many/CollectionValue<L" + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;>;"); cw.visitAttribute(attr); cw.visitEnd(); byte[] classBytes = cw.toByteArray(); return generateClassFromBytes(qualifiedClassName, classBytes); } private Class generateClassFromBytes(String className, byte[] classBytes) { JaxbClassLoader loader = (JaxbClassLoader) helper.getClassLoader(); Class generatedClass = loader.generateClass(className, classBytes); return generatedClass; } /** * Inner class used for ordering a list of Properties alphabetically by * property name. * */ class PropertyComparitor implements Comparator<Property> { public int compare(Property p1, Property p2) { return p1.getPropertyName().compareTo(p2.getPropertyName()); } } private String getNextAvailableClassName(String suggestedName) { int counter = 1; return getNextAvailableClassName(suggestedName, suggestedName, counter); } private String getNextAvailableClassName(String suggestedBaseName, String suggestedName, int counter) { Iterator<Class> iter = typeMappingInfoToGeneratedClasses.values().iterator(); while (iter.hasNext()) { Class nextClass = iter.next(); if (nextClass.getName().equals(suggestedName)) { counter = counter + 1; return getNextAvailableClassName(suggestedBaseName, suggestedBaseName + counter, counter); } } return suggestedName; } private Class getPrimitiveClass(String primitiveClassName) { return ConversionManager.getDefaultManager().convertClassNameToClass(primitiveClassName); } private Class getObjectClass(Class primitiveClass) { return ConversionManager.getDefaultManager().getObjectClass(primitiveClass); } public Map<java.lang.reflect.Type, Class> getCollectionClassesToGeneratedClasses() { return collectionClassesToGeneratedClasses; } public Map<String, Class> getArrayClassesToGeneratedClasses() { return arrayClassesToGeneratedClasses; } public Map<Class, java.lang.reflect.Type> getGeneratedClassesToCollectionClasses() { return generatedClassesToCollectionClasses; } public Map<Class, JavaClass> getGeneratedClassesToArrayClasses() { return generatedClassesToArrayClasses; } /** * Convenience method for returning all of the TypeInfo objects for a given * package name. * * This method is inefficient as we need to iterate over the entire typeinfo * map for each call. We should eventually store the TypeInfos in a Map * based on package name, i.e.: * * Map<String, Map<String, TypeInfo>> * * @param packageName * @return List of TypeInfo objects for a given package name */ public Map<String, TypeInfo> getTypeInfosForPackage(String packageName) { Map<String, TypeInfo> typeInfos = new HashMap<String, TypeInfo>(); ArrayList<JavaClass> jClasses = getTypeInfoClasses(); for (JavaClass jClass : jClasses) { if (jClass.getPackageName().equals(packageName)) { String key = jClass.getQualifiedName(); typeInfos.put(key, typeInfo.get(key)); } } return typeInfos; } /** * Set namespace override info from XML bindings file. This will typically * be called from the XMLProcessor. * * @param packageToNamespaceMappings */ public void setPackageToNamespaceMappings(HashMap<String, NamespaceInfo> packageToNamespaceMappings) { this.packageToNamespaceMappings = packageToNamespaceMappings; } public SchemaTypeInfo addClass(JavaClass javaClass) { if (javaClass == null) { return null; } else if (helper.isAnnotationPresent(javaClass, XmlTransient.class)) { return null; } if (typeInfo == null) { // this is the first class. Initialize all the properties this.typeInfoClasses = new ArrayList<JavaClass>(); this.typeInfo = new HashMap<String, TypeInfo>(); this.typeQNames = new ArrayList<QName>(); this.userDefinedSchemaTypes = new HashMap<String, QName>(); this.packageToNamespaceMappings = new HashMap<String, NamespaceInfo>(); this.namespaceResolver = new NamespaceResolver(); } JavaClass[] jClasses = new JavaClass[] { javaClass }; buildNewTypeInfo(jClasses); TypeInfo info = typeInfo.get(javaClass.getQualifiedName()); NamespaceInfo namespaceInfo; String packageName = javaClass.getPackageName(); namespaceInfo = this.packageToNamespaceMappings.get(packageName); SchemaTypeInfo schemaInfo = new SchemaTypeInfo(); schemaInfo.setSchemaTypeName(new QName(info.getClassNamespace(), info.getSchemaTypeName())); if (info.isSetXmlRootElement()) { org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = info.getXmlRootElement(); String elementName = xmlRE.getName(); if (elementName.equals(XMLProcessor.DEFAULT) || elementName.equals(EMPTY_STRING)) { if (javaClass.getName().indexOf(DOLLAR_SIGN_CHR) != -1) { elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf(DOLLAR_SIGN_CHR) + 1)); } else { elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf(DOT_CHR) + 1)); } // TCK Compliancy if (elementName.length() >= 3) { int idx = elementName.length() - 1; char ch = elementName.charAt(idx - 1); if (Character.isDigit(ch)) { char lastCh = Character.toUpperCase(elementName.charAt(idx)); elementName = elementName.substring(0, idx) + lastCh; } } } String rootNamespace = xmlRE.getNamespace(); QName rootElemName = null; if (rootNamespace.equals(XMLProcessor.DEFAULT)) { rootElemName = new QName(namespaceInfo.getNamespace(), elementName); } else { rootElemName = new QName(rootNamespace, elementName); } schemaInfo.getGlobalElementDeclarations().add(rootElemName); ElementDeclaration declaration = new ElementDeclaration(rootElemName, javaClass, javaClass.getRawName(), false); this.getGlobalElements().put(rootElemName, declaration); } return schemaInfo; } /** * Convenience method which class pre and postBuildTypeInfo for a given set * of JavaClasses. * * @param javaClasses */ public void buildNewTypeInfo(JavaClass[] javaClasses) { preBuildTypeInfo(javaClasses); postBuildTypeInfo(javaClasses); processPropertyTypes(javaClasses); } /** * Pre-process a descriptor customizer. Here, the given JavaClass is checked * for the existence of an @XmlCustomizer annotation. * * Note that the post processing of the descriptor customizers will take * place in MappingsGenerator's generateProject method, after the * descriptors and mappings have been generated. * * @param jClass * @param tInfo * @see XmlCustomizer * @see MappingsGenerator */ private void preProcessCustomizer(JavaClass jClass, TypeInfo tInfo) { XmlCustomizer xmlCustomizer = (XmlCustomizer) helper.getAnnotation(jClass, XmlCustomizer.class); if (xmlCustomizer != null) { tInfo.setXmlCustomizer(xmlCustomizer.value().getName()); } } /** * Lazy load the metadata logger. * * @return */ private JAXBMetadataLogger getLogger() { if (logger == null) { logger = new JAXBMetadataLogger(); } return logger; } /** * Return the Helper object set on this processor. * * @return */ Helper getHelper() { return this.helper; } public boolean isDefaultNamespaceAllowed() { return isDefaultNamespaceAllowed; } public List<ElementDeclaration> getLocalElements() { return this.localElements; } public Map<TypeMappingInfo, Class> getTypeMappingInfoToGeneratedClasses() { return this.typeMappingInfoToGeneratedClasses; } public Map<TypeMappingInfo, Class> getTypeMappingInfoToAdapterClasses() { return this.typeMappingInfoToAdapterClasses; } /** * Add an XmlRegistry to ObjectFactory class name pair to the map. * * @param factoryClassName * ObjectFactory class name * @param xmlReg * org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry instance */ public void addXmlRegistry(String factoryClassName, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry xmlReg) { this.xmlRegistries.put(factoryClassName, xmlReg); } /** * Convenience method for determining if a given JavaClass should be * processed as an ObjectFactory class. * * @param javaClass * @return true if the JavaClass is annotated with @XmlRegistry or the map * of XmlRegistries contains a key equal to the JavaClass' qualified * name */ private boolean isXmlRegistry(JavaClass javaClass) { return (helper.isAnnotationPresent(javaClass, XmlRegistry.class) || xmlRegistries.get(javaClass.getQualifiedName()) != null); } public Map<TypeMappingInfo, QName> getTypeMappingInfoToSchemaType() { return this.typeMappingInfoToSchemaType; } String getDefaultTargetNamespace() { return this.defaultTargetNamespace; } void setDefaultTargetNamespace(String defaultTargetNamespace) { this.defaultTargetNamespace = defaultTargetNamespace; } public void setDefaultNamespaceAllowed(boolean isDefaultNamespaceAllowed) { this.isDefaultNamespaceAllowed = isDefaultNamespaceAllowed; } HashMap<QName, ElementDeclaration> getElementDeclarationsForScope(String scopeClassName) { return this.elementDeclarations.get(scopeClassName); } private Map<Object, Object> createUserPropertiesMap(XmlProperty[] properties) { Map<Object, Object> propMap = new HashMap<Object, Object>(); for (XmlProperty prop : properties) { Object pvalue = prop.value(); if (!(prop.valueType() == String.class)) { pvalue = XMLConversionManager.getDefaultXMLManager().convertObject(prop.value(), prop.valueType()); } propMap.put(prop.name(), pvalue); } return propMap; } /** * Indicates if a given Property represents an MTOM attachment. Will return true * if the given Property's actual type is one of: * * - DataHandler * - byte[] * - Byte[] * - Image * - Source * - MimeMultipart * * @param property * @return */ public boolean isMtomAttachment(Property property) { JavaClass ptype = property.getActualType(); return (areEquals(ptype, JAVAX_ACTIVATION_DATAHANDLER) || areEquals(ptype, byte[].class) || areEquals(ptype, Image.class) || areEquals(ptype, Source.class) || areEquals(ptype, JAVAX_MAIL_INTERNET_MIMEMULTIPART)); } public boolean hasSwaRef() { return this.hasSwaRef; } public void setHasSwaRef(boolean swaRef) { this.hasSwaRef = swaRef; } }
package org.eclipse.persistence.jaxb.compiler; import java.awt.Image; import java.beans.Introspector; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; 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 javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessorOrder; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttachmentRef; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlInlineBinaryData; import javax.xml.bind.annotation.XmlList; import javax.xml.bind.annotation.XmlMimeType; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchema; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSchemaTypes; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.XmlType.DEFAULT; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters; import javax.xml.namespace.QName; import javax.xml.transform.Source; import org.eclipse.persistence.exceptions.JAXBException; import org.eclipse.persistence.internal.descriptors.Namespace; import org.eclipse.persistence.internal.helper.ClassConstants; import org.eclipse.persistence.internal.helper.ConversionManager; import org.eclipse.persistence.internal.jaxb.JaxbClassLoader; import org.eclipse.persistence.internal.libraries.asm.ClassWriter; import org.eclipse.persistence.internal.libraries.asm.CodeVisitor; import org.eclipse.persistence.internal.libraries.asm.Constants; import org.eclipse.persistence.internal.libraries.asm.Label; import org.eclipse.persistence.internal.libraries.asm.Type; import org.eclipse.persistence.internal.libraries.asm.attrs.Annotation; import org.eclipse.persistence.internal.libraries.asm.attrs.LocalVariableTypeTableAttribute; import org.eclipse.persistence.internal.libraries.asm.attrs.RuntimeVisibleAnnotations; import org.eclipse.persistence.internal.libraries.asm.attrs.SignatureAttribute; import org.eclipse.persistence.internal.oxm.XMLConversionManager; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.jaxb.TypeMappingInfo; import org.eclipse.persistence.jaxb.javamodel.AnnotationProxy; import org.eclipse.persistence.jaxb.javamodel.Helper; import org.eclipse.persistence.jaxb.javamodel.JavaClass; import org.eclipse.persistence.jaxb.javamodel.JavaConstructor; import org.eclipse.persistence.jaxb.javamodel.JavaField; import org.eclipse.persistence.jaxb.javamodel.JavaHasAnnotations; import org.eclipse.persistence.jaxb.javamodel.JavaMethod; import org.eclipse.persistence.jaxb.javamodel.JavaPackage; import org.eclipse.persistence.jaxb.javamodel.reflection.JavaFieldImpl; import org.eclipse.persistence.jaxb.xmlmodel.XmlAccessOrder; import org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType; import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation; import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlReadTransformer; import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransformer; import org.eclipse.persistence.mappings.transformers.AttributeTransformer; import org.eclipse.persistence.mappings.transformers.FieldTransformer; import org.eclipse.persistence.oxm.NamespaceResolver; import org.eclipse.persistence.oxm.XMLConstants; import org.eclipse.persistence.oxm.annotations.XmlAccessMethods; import org.eclipse.persistence.oxm.annotations.XmlCDATA; import org.eclipse.persistence.oxm.annotations.XmlClassExtractor; import org.eclipse.persistence.oxm.annotations.XmlContainerProperty; import org.eclipse.persistence.oxm.annotations.XmlCustomizer; import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode; import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorValue; import org.eclipse.persistence.oxm.annotations.XmlElementsJoinNodes; import org.eclipse.persistence.oxm.annotations.XmlInverseReference; import org.eclipse.persistence.oxm.annotations.XmlIsSetNullPolicy; import org.eclipse.persistence.oxm.annotations.XmlJoinNode; import org.eclipse.persistence.oxm.annotations.XmlJoinNodes; import org.eclipse.persistence.oxm.annotations.XmlKey; import org.eclipse.persistence.oxm.annotations.XmlNullPolicy; import org.eclipse.persistence.oxm.annotations.XmlParameter; import org.eclipse.persistence.oxm.annotations.XmlPath; import org.eclipse.persistence.oxm.annotations.XmlPaths; import org.eclipse.persistence.oxm.annotations.XmlProperties; import org.eclipse.persistence.oxm.annotations.XmlProperty; import org.eclipse.persistence.oxm.annotations.XmlReadOnly; import org.eclipse.persistence.oxm.annotations.XmlWriteOnly; import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers; /** * INTERNAL: * <p> * <b>Purpose:</b>To perform some initial processing of Java classes and JAXB * 2.0 Annotations and generate meta data that can be used by the Mappings * Generator and Schema Generator * <p> * <b>Responsibilities:</b> * <ul> * <li>Generate a map of TypeInfo objects, keyed on class name</li> * <li>Generate a map of user defined schema types</li> * <li>Identify any class-based JAXB 2.0 callback methods, and create * MarshalCallback and UnmarshalCallback objects to wrap them.</li> * <li>Centralize processing which is common to both Schema Generation and * Mapping Generation tasks</li> * <p> * This class does the initial processing of the JAXB 2.0 Generation. It * generates meta data that can be used by the later Schema Generation and * Mapping Generation steps. * * @see org.eclipse.persistence.jaxb.compiler.Generator * @author mmacivor * @since Oracle TopLink 11.1.1.0.0 */ public class AnnotationsProcessor { static final String JAVAX_ACTIVATION_DATAHANDLER = "javax.activation.DataHandler"; static final String JAVAX_MAIL_INTERNET_MIMEMULTIPART = "javax.mail.internet.MimeMultipart"; private static final String JAVAX_XML_BIND_JAXBELEMENT = "javax.xml.bind.JAXBElement"; private static final String TYPE_METHOD_NAME = "type"; private static final String VALUE_METHOD_NAME = "value"; private static final String ARRAY_PACKAGE_NAME = "jaxb.dev.java.net.array"; private static final String ARRAY_NAMESPACE = "http://jaxb.dev.java.net/array"; private static final String ARRAY_CLASS_NAME_SUFFIX = "Array"; private static final String ORG_W3C_DOM = "org.w3c.dom"; private static final String CREATE = "create"; private static final String ELEMENT_DECL_GLOBAL = "javax.xml.bind.annotation.XmlElementDecl.GLOBAL"; private static final String ELEMENT_DECL_DEFAULT = "\u0000"; private static final String EMPTY_STRING = ""; private static final String JAVA_UTIL_LIST = "java.util.List"; private static final String JAVA_LANG_OBJECT = "java.lang.Object"; private static final String SLASH = "/"; private static final String AT_SIGN = "@"; private ArrayList<JavaClass> typeInfoClasses; private HashMap<String, NamespaceInfo> packageToNamespaceMappings; private HashMap<String, MarshalCallback> marshalCallbacks; private HashMap<String, QName> userDefinedSchemaTypes; private HashMap<String, TypeInfo> typeInfo; private ArrayList<QName> typeQNames; private HashMap<String, UnmarshalCallback> unmarshalCallbacks; private HashMap<String, HashMap<QName, ElementDeclaration>> elementDeclarations; private HashMap<String, ElementDeclaration> xmlRootElements; private List<ElementDeclaration> localElements; private HashMap<String, JavaMethod> factoryMethods; private Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry> xmlRegistries; private Map<String, Class> arrayClassesToGeneratedClasses; private Map<Class, JavaClass> generatedClassesToArrayClasses; private Map<java.lang.reflect.Type, Class> collectionClassesToGeneratedClasses; private Map<Class, java.lang.reflect.Type> generatedClassesToCollectionClasses; private Map<JavaClass, TypeMappingInfo> javaClassToTypeMappingInfos; private Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedClasses; private Map<TypeMappingInfo, Class> typeMappingInfoToAdapterClasses; private Map<TypeMappingInfo, QName> typeMappingInfoToSchemaType; private NamespaceResolver namespaceResolver; private Helper helper; private String defaultTargetNamespace; private JAXBMetadataLogger logger; private boolean isDefaultNamespaceAllowed; public AnnotationsProcessor(Helper helper) { this.helper = helper; isDefaultNamespaceAllowed = true; } /** * Generate TypeInfo instances for a given array of JavaClasses. * * @param classes */ void processClassesAndProperties(JavaClass[] classes, TypeMappingInfo[] typeMappingInfos) { init(classes, typeMappingInfos); preBuildTypeInfo(classes); classes = postBuildTypeInfo(classes); processJavaClasses(null); processPropertyTypes(this.typeInfoClasses.toArray(new JavaClass[this.typeInfoClasses.size()])); finalizeProperties(); createElementsForTypeMappingInfo(); } public void createElementsForTypeMappingInfo() { if (this.javaClassToTypeMappingInfos != null && !this.javaClassToTypeMappingInfos.isEmpty()) { Set<JavaClass> classes = this.javaClassToTypeMappingInfos.keySet(); for (JavaClass nextClass : classes) { TypeMappingInfo nextInfo = this.javaClassToTypeMappingInfos.get(nextClass); if (nextInfo != null) { boolean xmlAttachmentRef = false; String xmlMimeType = null; java.lang.annotation.Annotation[] annotations = getAnnotations(nextInfo); Class adapterClass = this.typeMappingInfoToAdapterClasses.get(nextInfo); Class declJavaType = null; if (adapterClass != null) { declJavaType = CompilerHelper.getTypeFromAdapterClass(adapterClass); } if (annotations != null) { for (int j = 0; j < annotations.length; j++) { java.lang.annotation.Annotation nextAnnotation = annotations[j]; if (nextAnnotation != null) { if (nextAnnotation instanceof XmlMimeType) { XmlMimeType javaAnnotation = (XmlMimeType) nextAnnotation; xmlMimeType = javaAnnotation.value(); } else if (nextAnnotation instanceof XmlAttachmentRef) { xmlAttachmentRef = true; } } } } QName qname = null; String nextClassName = nextClass.getQualifiedName(); if (declJavaType != null) { nextClassName = declJavaType.getCanonicalName(); } if (typeMappingInfoToGeneratedClasses != null) { Class generatedClass = typeMappingInfoToGeneratedClasses.get(nextInfo); if (generatedClass != null) { nextClassName = generatedClass.getCanonicalName(); } } TypeInfo nextTypeInfo = typeInfo.get(nextClassName); if (nextTypeInfo != null) { qname = new QName(nextTypeInfo.getClassNamespace(), nextTypeInfo.getSchemaTypeName()); } else { qname = getUserDefinedSchemaTypes().get(nextClassName); if (qname == null) { if (nextClassName.equals(ClassConstants.ABYTE.getName()) || nextClassName.equals(ClassConstants.APBYTE.getName()) || nextClassName.equals(Image.class.getName()) || nextClassName.equals(Source.class.getName()) || nextClassName.equals("javax.activation.DataHandler")) { if (xmlAttachmentRef) { qname = XMLConstants.SWA_REF_QNAME; } else { qname = XMLConstants.BASE_64_BINARY_QNAME; } } else if (nextClassName.equals(ClassConstants.OBJECT.getName())) { qname = XMLConstants.ANY_TYPE_QNAME; } else if (nextClassName.equals(ClassConstants.XML_GREGORIAN_CALENDAR.getName())) { qname = XMLConstants.ANY_SIMPLE_TYPE_QNAME; } else { Class theClass = helper.getClassForJavaClass(nextClass); qname = (QName) XMLConversionManager.getDefaultJavaTypes().get(theClass); } } } if (qname != null) { typeMappingInfoToSchemaType.put(nextInfo, qname); } if (nextInfo.getXmlTagName() != null) { ElementDeclaration element = new ElementDeclaration(nextInfo.getXmlTagName(), nextClass, nextClass.getQualifiedName(), false); element.setTypeMappingInfo(nextInfo); element.setXmlMimeType(xmlMimeType); element.setXmlAttachmentRef(xmlAttachmentRef); if (declJavaType != null) { element.setJavaType(helper.getJavaClass(declJavaType)); } Class generatedClass = typeMappingInfoToGeneratedClasses.get(nextInfo); if (generatedClass != null) { element.setJavaType(helper.getJavaClass(generatedClass)); } if (nextInfo.getElementScope() == TypeMappingInfo.ElementScope.Global) { this.getGlobalElements().put(element.getElementName(), element); } else { this.localElements.add(element); } String rootNamespace = element.getElementName().getNamespaceURI(); if(rootNamespace == null) { rootNamespace = XMLConstants.EMPTY_STRING; } if (rootNamespace.equals(XMLConstants.EMPTY_STRING)) { isDefaultNamespaceAllowed = false; } } } } } } /** * Returns an array of Annotations for a given TypeMappingInfo. This array * will either be populated from the TypeMappingInfo's array of annotations, * or based on an xml-element if present. The xml-element will take * precedence over the annotation array; if there is an xml-element the * Array of Annotations will be ignored. * * @param tmInfo * @return */ private java.lang.annotation.Annotation[] getAnnotations(TypeMappingInfo tmInfo) { if (tmInfo.getXmlElement() != null) { ClassLoader loader = helper.getClassLoader(); // create a single ConversionManager for that will be shared by the // proxy objects ConversionManager cMgr = new ConversionManager(); cMgr.setLoader(loader); // unmarshal the node into an XmlElement org.eclipse.persistence.jaxb.xmlmodel.XmlElement xElt = (org.eclipse.persistence.jaxb.xmlmodel.XmlElement) CompilerHelper.getXmlElement(tmInfo.getXmlElement(), loader); List annotations = new ArrayList(); // where applicable, a given dynamic proxy will contain a Map of // method name/return value entries Map<String, Object> components = null; // handle @XmlElement: set 'type' method if (!(xElt.getType().equals("javax.xml.bind.annotation.XmlElement.DEFAULT"))) { components = new HashMap(); components.put(TYPE_METHOD_NAME, xElt.getType()); annotations.add(AnnotationProxy.getProxy(components, XmlElement.class, loader, cMgr)); } // handle @XmlList if (xElt.isXmlList()) { annotations.add(AnnotationProxy.getProxy(components, XmlList.class, loader, cMgr)); } // handle @XmlAttachmentRef if (xElt.isXmlAttachmentRef()) { annotations.add(AnnotationProxy.getProxy(components, XmlAttachmentRef.class, loader, cMgr)); } // handle @XmlMimeType: set 'value' method if (xElt.getXmlMimeType() != null) { components = new HashMap(); components.put(VALUE_METHOD_NAME, xElt.getXmlMimeType()); annotations.add(AnnotationProxy.getProxy(components, XmlMimeType.class, loader, cMgr)); } // handle @XmlJavaTypeAdapter: set 'type' and 'value' methods if (xElt.getXmlJavaTypeAdapter() != null) { components = new HashMap(); components.put(TYPE_METHOD_NAME, xElt.getXmlJavaTypeAdapter().getType()); components.put(VALUE_METHOD_NAME, xElt.getXmlJavaTypeAdapter().getValue()); annotations.add(AnnotationProxy.getProxy(components, XmlJavaTypeAdapter.class, loader, cMgr)); } // return the newly created array of dynamic proxy objects return (java.lang.annotation.Annotation[]) annotations.toArray(new java.lang.annotation.Annotation[annotations.size()]); } // no xml-element set on the info, (i.e. no xml overrides) so return the // array of Annotation objects return tmInfo.getAnnotations(); } /** * Initialize maps, lists, etc. Typically called prior to processing a set * of classes via preBuildTypeInfo, postBuildTypeInfo, processJavaClasses. */ void init(JavaClass[] classes, TypeMappingInfo[] typeMappingInfos) { typeInfoClasses = new ArrayList<JavaClass>(); typeInfo = new HashMap<String, TypeInfo>(); typeQNames = new ArrayList<QName>(); userDefinedSchemaTypes = new HashMap<String, QName>(); if (packageToNamespaceMappings == null) { packageToNamespaceMappings = new HashMap<String, NamespaceInfo>(); } this.factoryMethods = new HashMap<String, JavaMethod>(); this.xmlRegistries = new HashMap<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry>(); this.namespaceResolver = new NamespaceResolver(); this.xmlRootElements = new HashMap<String, ElementDeclaration>(); arrayClassesToGeneratedClasses = new HashMap<String, Class>(); collectionClassesToGeneratedClasses = new HashMap<java.lang.reflect.Type, Class>(); generatedClassesToArrayClasses = new HashMap<Class, JavaClass>(); generatedClassesToCollectionClasses = new HashMap<Class, java.lang.reflect.Type>(); typeMappingInfoToGeneratedClasses = new HashMap<TypeMappingInfo, Class>(); typeMappingInfoToSchemaType = new HashMap<TypeMappingInfo, QName>(); elementDeclarations = new HashMap<String, HashMap<QName, ElementDeclaration>>(); HashMap globalElements = new HashMap<QName, ElementDeclaration>(); elementDeclarations.put(XmlElementDecl.GLOBAL.class.getName(), globalElements); localElements = new ArrayList<ElementDeclaration>(); javaClassToTypeMappingInfos = new HashMap<JavaClass, TypeMappingInfo>(); if (typeMappingInfos != null) { for (int i = 0; i < typeMappingInfos.length; i++) { javaClassToTypeMappingInfos.put(classes[i], typeMappingInfos[i]); } } typeMappingInfoToAdapterClasses = new HashMap<TypeMappingInfo, Class>(); if (typeMappingInfos != null) { for (TypeMappingInfo next : typeMappingInfos) { java.lang.annotation.Annotation[] annotations = getAnnotations(next); if (annotations != null) { for (java.lang.annotation.Annotation nextAnnotation : annotations) { if (nextAnnotation instanceof XmlJavaTypeAdapter) { typeMappingInfoToAdapterClasses.put(next, ((XmlJavaTypeAdapter) nextAnnotation).value()); } } } } } } /** * Process class level annotations only. It is assumed that a call to init() * has been made prior to calling this method. After the types created via * this method have been modified (if necessary) postBuildTypeInfo and * processJavaClasses should be called to finish processing. * * @param javaClasses * @return */ public Map<String, TypeInfo> preBuildTypeInfo(JavaClass[] javaClasses) { for (JavaClass javaClass : javaClasses) { if (javaClass == null || !shouldGenerateTypeInfo(javaClass) || isXmlRegistry(javaClass) || javaClass.isArray()) { continue; } TypeInfo info = typeInfo.get(javaClass.getQualifiedName()); if (info != null) { if (info.isPreBuilt()) { continue; } } if (javaClass.isEnum()) { info = new EnumTypeInfo(helper); } else { info = new TypeInfo(helper); } info.setJavaClassName(javaClass.getQualifiedName()); info.setPreBuilt(true); // handle @XmlTransient if (helper.isAnnotationPresent(javaClass, XmlTransient.class)) { info.setXmlTransient(true); } // handle @XmlInlineBinaryData if (helper.isAnnotationPresent(javaClass, XmlInlineBinaryData.class)) { info.setInlineBinaryData(true); } // handle @XmlRootElement processXmlRootElement(javaClass, info); // handle @XmlSeeAlso processXmlSeeAlso(javaClass, info); NamespaceInfo packageNamespace = getNamespaceInfoForPackage(javaClass); // handle @XmlType preProcessXmlType(javaClass, info, packageNamespace); // handle @XmlAccessorType preProcessXmlAccessorType(javaClass, info, packageNamespace); // handle @XmlAccessorOrder preProcessXmlAccessorOrder(javaClass, info, packageNamespace); // handle package level @XmlJavaTypeAdapters processPackageLevelAdapters(javaClass, info); // handle class level @XmlJavaTypeAdapters processClassLevelAdapters(javaClass, info); // handle descriptor customizer preProcessCustomizer(javaClass, info); // handle package level @XmlSchemaType(s) processSchemaTypes(javaClass, info); // handle class extractor if (helper.isAnnotationPresent(javaClass, XmlClassExtractor.class)) { XmlClassExtractor classExtractor = (XmlClassExtractor) helper.getAnnotation(javaClass, XmlClassExtractor.class); info.setClassExtractorName(classExtractor.value().getName()); } // handle user properties if (helper.isAnnotationPresent(javaClass, XmlProperties.class)) { XmlProperties xmlProperties = (XmlProperties) helper.getAnnotation(javaClass, XmlProperties.class); Map<Object, Object> propertiesMap = createUserPropertiesMap(xmlProperties.value()); info.setUserProperties(propertiesMap); } else if (helper.isAnnotationPresent(javaClass, XmlProperty.class)) { XmlProperty xmlProperty = (XmlProperty) helper.getAnnotation(javaClass, XmlProperty.class); Map<Object, Object> propertiesMap = createUserPropertiesMap(new XmlProperty[] { xmlProperty }); info.setUserProperties(propertiesMap); } // handle class indicator field name if (helper.isAnnotationPresent(javaClass, XmlDiscriminatorNode.class)) { XmlDiscriminatorNode xmlDiscriminatorNode = (XmlDiscriminatorNode) helper.getAnnotation(javaClass, XmlDiscriminatorNode.class); info.setXmlDiscriminatorNode(xmlDiscriminatorNode.value()); } // handle class indicator if (helper.isAnnotationPresent(javaClass, XmlDiscriminatorValue.class)) { XmlDiscriminatorValue xmlDiscriminatorValue = (XmlDiscriminatorValue) helper.getAnnotation(javaClass, XmlDiscriminatorValue.class); info.setXmlDiscriminatorValue(xmlDiscriminatorValue.value()); } typeInfoClasses.add(javaClass); typeInfo.put(info.getJavaClassName(), info); } return typeInfo; } /** * Process any additional classes (i.e. inner classes, @XmlSeeAlso, * @XmlRegistry, etc.) for a given set of JavaClasses, then complete * building all of the required TypeInfo objects. This method * is typically called after init and preBuildTypeInfo have * been called. * * @param javaClasses * @return updated array of JavaClasses, made up of the original classes * plus any additional ones */ public JavaClass[] postBuildTypeInfo(JavaClass[] javaClasses) { if (javaClasses.length == 0) { return javaClasses; } // create type info instances for any additional classes javaClasses = processAdditionalClasses(javaClasses); preBuildTypeInfo(javaClasses); updateGlobalElements(javaClasses); buildTypeInfo(javaClasses); return javaClasses; } /** * INTERNAL: * * Complete building TypeInfo objects for a given set of JavaClass * instances. This method assumes that init, preBuildTypeInfo, and * postBuildTypeInfo have been called. * * @param allClasses * @return */ private Map<String, TypeInfo> buildTypeInfo(JavaClass[] allClasses) { for (JavaClass javaClass : allClasses) { if (javaClass == null) { continue; } TypeInfo info = typeInfo.get(javaClass.getQualifiedName()); if (info == null || info.isPostBuilt()) { continue; } info.setPostBuilt(true); // handle factory methods processFactoryMethods(javaClass, info); NamespaceInfo packageNamespace = getNamespaceInfoForPackage(javaClass); // handle @XmlAccessorType postProcessXmlAccessorType(info, packageNamespace); // handle @XmlType postProcessXmlType(javaClass, info, packageNamespace); // handle @XmlEnum if (info.isEnumerationType()) { addEnumTypeInfo(javaClass, ((EnumTypeInfo) info)); continue; } // process schema type name processTypeQName(javaClass, info, packageNamespace); // handle superclass if necessary JavaClass superClass = (JavaClass) javaClass.getSuperclass(); if (shouldGenerateTypeInfo(superClass)) { JavaClass[] jClassArray = new JavaClass[] { superClass }; buildNewTypeInfo(jClassArray); } // add properties info.setProperties(getPropertiesForClass(javaClass, info)); // process properties processTypeInfoProperties(javaClass, info); // handle @XmlAccessorOrder postProcessXmlAccessorOrder(info, packageNamespace); validatePropOrderForInfo(info); } return typeInfo; } /** * Perform any final generation and/or validation operations on TypeInfo * properties. * */ public void finalizeProperties() { ArrayList<JavaClass> jClasses = getTypeInfoClasses(); for (JavaClass jClass : jClasses) { TypeInfo tInfo = getTypeInfo().get(jClass.getQualifiedName()); // don't need to validate props on a transient class at this point if (tInfo.isTransient()) { continue; } if(!jClass.isInterface() && !tInfo.isEnumerationType() && !jClass.isAbstract()) { if (tInfo.getFactoryMethodName() == null && tInfo.getObjectFactoryClassName() == null) { JavaConstructor zeroArgConstructor = jClass.getDeclaredConstructor(new JavaClass[] {}); if (zeroArgConstructor == null) { if(tInfo.isSetXmlJavaTypeAdapter()) { tInfo.setTransient(true); } else { throw org.eclipse.persistence.exceptions.JAXBException.factoryMethodOrConstructorRequired(jClass.getName()); } } } } // validate XmlValue if (tInfo.getXmlValueProperty() != null) { validateXmlValueFieldOrProperty(jClass, tInfo.getXmlValueProperty()); } for (Property property : tInfo.getPropertyList()) { // need to check for transient reference class JavaClass typeClass = property.getActualType(); TypeInfo targetInfo = typeInfo.get(typeClass.getQualifiedName()); if (targetInfo != null && targetInfo.isTransient()) { throw JAXBException.invalidReferenceToTransientClass(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName()); } // only one XmlValue is allowed per class, and if there is one only XmlAttributes are allowed if (tInfo.isSetXmlValueProperty()) { if (property.isXmlValue() && !(tInfo.getXmlValueProperty().getPropertyName().equals(property.getPropertyName()))) { throw JAXBException.xmlValueAlreadySet(property.getPropertyName(), tInfo.getXmlValueProperty().getPropertyName(), jClass.getName()); } if (!property.isXmlValue() && !property.isAttribute() && !property.isInverseReference() && !property.isTransient()) { throw JAXBException.propertyOrFieldShouldBeAnAttribute(property.getPropertyName()); } } // validate XmlIDREF if (property.isXmlIdRef()) { // the target class must have an associated TypeInfo unless it is Object if (targetInfo == null && !typeClass.getQualifiedName().equals(JAVA_LANG_OBJECT)) { throw JAXBException.invalidIDREFClass(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName()); } // if the property is an XmlIDREF, the target must have an XmlID set if (targetInfo != null && targetInfo.getIDProperty() == null) { throw JAXBException.invalidIdRef(property.getPropertyName(), typeClass.getQualifiedName()); } } // there can only be one XmlID per type info if (property.isXmlId() && tInfo.getIDProperty() != null && !(tInfo.getIDProperty().getPropertyName().equals(property.getPropertyName()))) { throw JAXBException.idAlreadySet(property.getPropertyName(), tInfo.getIDProperty().getPropertyName(), jClass.getName()); } // there can only be one XmlAnyAttribute per type info if (property.isAnyAttribute() && tInfo.isSetAnyAttributePropertyName() && !(tInfo.getAnyAttributePropertyName().equals(property.getPropertyName()))) { throw JAXBException.multipleAnyAttributeMapping(jClass.getName()); } // there can only be one XmlAnyElement per type info if (property.isAny() && tInfo.isSetAnyElementPropertyName() && !(tInfo.getAnyElementPropertyName().equals(property.getPropertyName()))) { throw JAXBException.xmlAnyElementAlreadySet(property.getPropertyName(), tInfo.getAnyElementPropertyName(), jClass.getName()); } // an XmlAttachmentRef can only appear on a DataHandler property if (property.isSwaAttachmentRef() && !areEquals(property.getActualType(), JAVAX_ACTIVATION_DATAHANDLER)) { throw JAXBException.invalidAttributeRef(property.getPropertyName(), jClass.getQualifiedName()); } // an XmlElementWrapper can only appear on a Collection or Array if (property.getXmlElementWrapper() != null) { if (!isCollectionType(property) && !property.getType().isArray()) { throw JAXBException.invalidElementWrapper(property.getPropertyName()); } } // handle XmlElementRef(s) - validate and build the required ElementDeclaration object if (property.isReference()) { processReferenceProperty(property, tInfo, jClass); } // handle XmlTransformation - validate transformer class/method if (property.isXmlTransformation()) { processXmlTransformationProperty(property); } // validate XmlJoinNodes if (property.isSetXmlJoinNodes()) { // the target class must have an associated TypeInfo if (targetInfo == null) { throw JAXBException.invalidXmlJoinNodeReferencedClass(property.getPropertyName(), typeClass.getQualifiedName()); } // validate each referencedXmlPath - target TypeInfo should // have XmlID/XmlKey property with matching XmlPath if (targetInfo.getIDProperty() == null && targetInfo.getXmlKeyProperties() == null) { throw JAXBException.noKeyOrIDPropertyOnJoinTarget(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName()); } for (org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode : property.getXmlJoinNodes().getXmlJoinNode()) { String refXPath = xmlJoinNode.getReferencedXmlPath(); if (targetInfo.getIDProperty() != null && refXPath.equals(targetInfo.getIDProperty().getXmlPath())) { continue; } boolean matched = false; if (targetInfo.getXmlKeyProperties() != null) { for (Property xmlkeyProperty : targetInfo.getXmlKeyProperties()) { if (refXPath.equals(xmlkeyProperty.getXmlPath())) { matched = true; break; } } } if (!matched) { throw JAXBException.invalidReferencedXmlPathOnJoin(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName(), refXPath); } } } } } } /** * Process a given TypeInfo instance's properties. * * @param info */ private void processTypeInfoProperties(JavaClass javaClass, TypeInfo info) { ArrayList<Property> properties = info.getPropertyList(); for (Property property : properties) { // handle @XmlID processXmlID(property, javaClass, info); // handle @XmlIDREF - validate these properties after processing of // all types is completed processXmlIDREF(property); if(property.isMap()) { JavaClass keyType = property.getKeyType(); if (shouldGenerateTypeInfo(keyType)) { JavaClass[] jClassArray = new JavaClass[] { keyType }; buildNewTypeInfo(jClassArray); } JavaClass valueType = property.getValueType(); if (shouldGenerateTypeInfo(valueType)) { JavaClass[] jClassArray = new JavaClass[] { valueType }; buildNewTypeInfo(jClassArray); } } } } void processPropertyTypes(JavaClass[] classes) { for (JavaClass next:classes) { TypeInfo info = getTypeInfo().get(next.getQualifiedName()); if(info != null) { for (Property property : info.getPropertyList()) { JavaClass type = property.getActualType(); if (!(this.typeInfo.containsKey(type.getQualifiedName())) && shouldGenerateTypeInfo(type)) { JavaClass[] jClassArray = new JavaClass[] { type }; buildNewTypeInfo(jClassArray); } if(property.isChoice()) { processChoiceProperty(property, info, next, type); for(Property choiceProp:property.getChoiceProperties()) { type = choiceProp.getActualType(); if (!(this.typeInfo.containsKey(type.getQualifiedName())) && shouldGenerateTypeInfo(type)) { JavaClass[] jClassArray = new JavaClass[] { type }; buildNewTypeInfo(jClassArray); } } } } } } } /** * This method was initially designed to handle processing one or more * JavaClass instances. Over time its functionality has been broken apart * and handled in different methods. Its sole purpose now is to check for * callback methods. * * @param classes * this paramater can and should be null as it is not used */ public void processJavaClasses(JavaClass[] classes) { checkForCallbackMethods(); } /** * Process any additional classes, such as inner classes, @XmlRegistry or * from @XmlSeeAlso. * * @param classes * @return */ private JavaClass[] processAdditionalClasses(JavaClass[] classes) { ArrayList<JavaClass> extraClasses = new ArrayList<JavaClass>(); ArrayList<JavaClass> classesToProcess = new ArrayList<JavaClass>(); for (JavaClass jClass : classes) { Class xmlElementType = null; JavaClass javaClass = jClass; TypeMappingInfo tmi = javaClassToTypeMappingInfos.get(javaClass); if (tmi != null) { Class adapterClass = this.typeMappingInfoToAdapterClasses.get(tmi); if (adapterClass != null) { JavaClass adapterJavaClass = helper.getJavaClass(adapterClass); JavaClass newType = helper.getJavaClass(Object.class); // look for marshal method for (Object nextMethod : adapterJavaClass.getDeclaredMethods()) { JavaMethod method = (JavaMethod) nextMethod; if (method.getName().equals("marshal")) { JavaClass returnType = method.getReturnType(); if (!returnType.getQualifiedName().equals(newType.getQualifiedName())) { newType = (JavaClass) returnType; break; } } } javaClass = newType; } java.lang.annotation.Annotation[] annotations = getAnnotations(tmi); if (annotations != null) { for (int j = 0; j < annotations.length; j++) { java.lang.annotation.Annotation nextAnnotation = annotations[j]; if (nextAnnotation != null) { if (nextAnnotation instanceof XmlElement) { XmlElement javaAnnotation = (XmlElement) nextAnnotation; if (javaAnnotation.type() != XmlElement.DEFAULT.class) { xmlElementType = javaAnnotation.type(); } } } } } } if (areEquals(javaClass, byte[].class) || areEquals(javaClass, Byte[].class) || areEquals(javaClass, JAVAX_ACTIVATION_DATAHANDLER) || areEquals(javaClass, Source.class) || areEquals(javaClass, Image.class) || areEquals(javaClass, JAVAX_MAIL_INTERNET_MIMEMULTIPART)) { if (tmi == null || tmi.getXmlTagName() == null) { ElementDeclaration declaration = new ElementDeclaration(null, javaClass, javaClass.getQualifiedName(), false, XmlElementDecl.GLOBAL.class); declaration.setTypeMappingInfo(tmi); getGlobalElements().put(null, declaration); } } else if (javaClass.isArray()) { if (!helper.isBuiltInJavaType(javaClass.getComponentType())) { extraClasses.add(javaClass.getComponentType()); } Class generatedClass; if (null == tmi) { generatedClass = arrayClassesToGeneratedClasses.get(javaClass.getName()); } else { generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader()); } if (generatedClass == null) { generatedClass = generateWrapperForArrayClass(javaClass, tmi, xmlElementType); extraClasses.add(helper.getJavaClass(generatedClass)); arrayClassesToGeneratedClasses.put(javaClass.getName(), generatedClass); } generatedClassesToArrayClasses.put(generatedClass, javaClass); typeMappingInfoToGeneratedClasses.put(tmi, generatedClass); } else if (isCollectionType(javaClass)) { JavaClass componentClass; if (javaClass.hasActualTypeArguments()) { componentClass = (JavaClass) javaClass.getActualTypeArguments().toArray()[0]; if (!componentClass.isPrimitive()) { extraClasses.add(componentClass); } } else { componentClass = helper.getJavaClass(Object.class); } Class generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader()); if (generatedClass == null) { generatedClass = generateCollectionValue(javaClass, tmi, xmlElementType); extraClasses.add(helper.getJavaClass(generatedClass)); } typeMappingInfoToGeneratedClasses.put(tmi, generatedClass); } else if (isMapType(javaClass)) { JavaClass keyClass; JavaClass valueClass; if (javaClass.hasActualTypeArguments()) { keyClass = (JavaClass) javaClass.getActualTypeArguments().toArray()[0]; if (!helper.isBuiltInJavaType(keyClass)) { extraClasses.add(keyClass); } valueClass = (JavaClass) javaClass.getActualTypeArguments().toArray()[1]; if (!helper.isBuiltInJavaType(valueClass)) { extraClasses.add(valueClass); } } else { keyClass = helper.getJavaClass(Object.class); valueClass = helper.getJavaClass(Object.class); } Class generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader()); if (generatedClass == null) { generatedClass = generateWrapperForMapClass(javaClass, keyClass, valueClass, tmi); extraClasses.add(helper.getJavaClass(generatedClass)); } typeMappingInfoToGeneratedClasses.put(tmi, generatedClass); } else { // process @XmlRegistry, @XmlSeeAlso and inner classes processClass(javaClass, classesToProcess); } } // process @XmlRegistry, @XmlSeeAlso and inner classes for (JavaClass javaClass : extraClasses) { processClass(javaClass, classesToProcess); } return classesToProcess.toArray(new JavaClass[classesToProcess.size()]); } /** * Adds additional classes to the given List, from inner classes, * * @XmlRegistry or @XmlSeeAlso. * * @param javaClass * @param classesToProcess */ private void processClass(JavaClass javaClass, ArrayList<JavaClass> classesToProcess) { if (shouldGenerateTypeInfo(javaClass)) { if (isXmlRegistry(javaClass)) { this.processObjectFactory(javaClass, classesToProcess); } else { classesToProcess.add(javaClass); // handle @XmlSeeAlso TypeInfo info = typeInfo.get(javaClass.getQualifiedName()); if (info != null && info.isSetXmlSeeAlso()) { for (String jClassName : info.getXmlSeeAlso()) { classesToProcess.add(helper.getJavaClass(jClassName)); } } // handle inner classes for (Iterator<JavaClass> jClassIt = javaClass.getDeclaredClasses().iterator(); jClassIt.hasNext();) { JavaClass innerClass = jClassIt.next(); if (shouldGenerateTypeInfo(innerClass)) { TypeInfo tInfo = typeInfo.get(innerClass.getQualifiedName()); if ((tInfo != null && !tInfo.isTransient()) || !helper.isAnnotationPresent(innerClass, XmlTransient.class)) { classesToProcess.add(innerClass); } } } } } } /** * Process an @XmlSeeAlso annotation. TypeInfo instances will be created for * each class listed. * * @param javaClass */ private void processXmlSeeAlso(JavaClass javaClass, TypeInfo info) { // reflectively load @XmlSeeAlso class to avoid dependency Class xmlSeeAlsoClass = null; Method valueMethod = null; try { xmlSeeAlsoClass = PrivilegedAccessHelper.getClassForName("javax.xml.bind.annotation.XmlSeeAlso"); valueMethod = PrivilegedAccessHelper.getDeclaredMethod(xmlSeeAlsoClass, "value", new Class[] {}); } catch (ClassNotFoundException ex) { // Ignore this exception. If SeeAlso isn't available, don't try to // process } catch (NoSuchMethodException ex) { } if (xmlSeeAlsoClass != null && helper.isAnnotationPresent(javaClass, xmlSeeAlsoClass)) { Object seeAlso = helper.getAnnotation(javaClass, xmlSeeAlsoClass); Class[] values = null; try { values = (Class[]) PrivilegedAccessHelper.invokeMethod(valueMethod, seeAlso, new Object[] {}); } catch (Exception ex) { } List<String> seeAlsoClassNames = new ArrayList<String>(); for (Class next : values) { seeAlsoClassNames.add(next.getName()); } info.setXmlSeeAlso(seeAlsoClassNames); } } /** * Process any factory methods. * * @param javaClass * @param info */ private void processFactoryMethods(JavaClass javaClass, TypeInfo info) { JavaMethod factoryMethod = this.factoryMethods.get(javaClass.getRawName()); if (factoryMethod != null) { // set up factory method info for mappings. info.setFactoryMethodName(factoryMethod.getName()); info.setObjectFactoryClassName(factoryMethod.getOwningClass().getRawName()); JavaClass[] paramTypes = factoryMethod.getParameterTypes(); if (paramTypes != null && paramTypes.length > 0) { String[] paramTypeNames = new String[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { paramTypeNames[i] = paramTypes[i].getRawName(); } info.setFactoryMethodParamTypes(paramTypeNames); } } } /** * Process any package-level @XmlJavaTypeAdapters. * * @param javaClass * @param info */ private void processPackageLevelAdapters(JavaClass javaClass, TypeInfo info) { JavaPackage pack = javaClass.getPackage(); if (helper.isAnnotationPresent(pack, XmlJavaTypeAdapters.class)) { XmlJavaTypeAdapters adapters = (XmlJavaTypeAdapters) helper.getAnnotation(pack, XmlJavaTypeAdapters.class); XmlJavaTypeAdapter[] adapterArray = adapters.value(); for (XmlJavaTypeAdapter next : adapterArray) { processPackageLevelAdapter(next, info); } } if (helper.isAnnotationPresent(pack, XmlJavaTypeAdapter.class)) { XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(pack, XmlJavaTypeAdapter.class); processPackageLevelAdapter(adapter, info); } } private void processPackageLevelAdapter(XmlJavaTypeAdapter next, TypeInfo info) { JavaClass adapterClass = helper.getJavaClass(next.value()); JavaClass boundType = helper.getJavaClass(next.type()); if (boundType != null) { info.addPackageLevelAdapterClass(adapterClass, boundType); } else { getLogger().logWarning(JAXBMetadataLogger.INVALID_BOUND_TYPE, new Object[] { boundType, adapterClass }); } } /** * Process any class-level @XmlJavaTypeAdapters. * * @param javaClass * @param info */ private void processClassLevelAdapters(JavaClass javaClass, TypeInfo info) { if (helper.isAnnotationPresent(javaClass, XmlJavaTypeAdapter.class)) { XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(javaClass, XmlJavaTypeAdapter.class); String boundType = adapter.type().getName(); if (boundType == null || boundType.equals("javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT")) { boundType = javaClass.getRawName(); } org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter(); xja.setValue(adapter.value().getName()); xja.setType(boundType); info.setXmlJavaTypeAdapter(xja); } } /** * Process any @XmlSchemaType(s). * * @param javaClass * @param info */ private void processSchemaTypes(JavaClass javaClass, TypeInfo info) { JavaPackage pack = javaClass.getPackage(); if (helper.isAnnotationPresent(pack, XmlSchemaTypes.class)) { XmlSchemaTypes types = (XmlSchemaTypes) helper.getAnnotation(pack, XmlSchemaTypes.class); XmlSchemaType[] typeArray = types.value(); for (XmlSchemaType next : typeArray) { processSchemaType(next); } } else if (helper.isAnnotationPresent(pack, XmlSchemaType.class)) { processSchemaType((XmlSchemaType) helper.getAnnotation(pack, XmlSchemaType.class)); } } /** * Process @XmlRootElement annotation on a given JavaClass. * * @param javaClass * @param info */ private void processXmlRootElement(JavaClass javaClass, TypeInfo info) { if (helper.isAnnotationPresent(javaClass, XmlRootElement.class)) { XmlRootElement rootElemAnnotation = (XmlRootElement) helper.getAnnotation(javaClass, XmlRootElement.class); org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = new org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement(); xmlRE.setName(rootElemAnnotation.name()); xmlRE.setNamespace(rootElemAnnotation.namespace()); info.setXmlRootElement(xmlRE); } } /** * Process @XmlType annotation on a given JavaClass and update the TypeInfo * for pre-processing. Note that if no @XmlType annotation is present we * still create a new XmlType an set it on the TypeInfo. * * @param javaClass * @param info * @param packageNamespace */ private void preProcessXmlType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) { org.eclipse.persistence.jaxb.xmlmodel.XmlType xmlType = new org.eclipse.persistence.jaxb.xmlmodel.XmlType(); if (helper.isAnnotationPresent(javaClass, XmlType.class)) { XmlType typeAnnotation = (XmlType) helper.getAnnotation(javaClass, XmlType.class); // set name xmlType.setName(typeAnnotation.name()); // set namespace xmlType.setNamespace(typeAnnotation.namespace()); // set propOrder String[] propOrder = typeAnnotation.propOrder(); // handle case where propOrder is an empty array if (propOrder != null) { xmlType.getPropOrder(); } for (String prop : propOrder) { xmlType.getPropOrder().add(prop); } // set factoryClass Class factoryClass = typeAnnotation.factoryClass(); if (factoryClass == DEFAULT.class) { xmlType.setFactoryClass("javax.xml.bind.annotation.XmlType.DEFAULT"); } else { xmlType.setFactoryClass(factoryClass.getCanonicalName()); } // set factoryMethodName xmlType.setFactoryMethod(typeAnnotation.factoryMethod()); } else { // set defaults xmlType.setName(getSchemaTypeNameForClassName(javaClass.getName())); xmlType.setNamespace(packageNamespace.getNamespace()); } info.setXmlType(xmlType); } /** * Process XmlType for a given TypeInfo. Here we assume that the TypeInfo * has an XmlType set - typically via preProcessXmlType or XmlProcessor * override. * * @param javaClass * @param info * @param packageNamespace */ private void postProcessXmlType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) { // assumes that the TypeInfo has an XmlType set from org.eclipse.persistence.jaxb.xmlmodel.XmlType xmlType = info.getXmlType(); // set/validate factoryClass and factoryMethod String factoryClassName = xmlType.getFactoryClass(); String factoryMethodName = xmlType.getFactoryMethod(); if (factoryClassName.equals("javax.xml.bind.annotation.XmlType.DEFAULT")) { if (factoryMethodName != null && !factoryMethodName.equals(EMPTY_STRING)) { // factory method applies to the current class - verify method exists JavaMethod method = javaClass.getDeclaredMethod(factoryMethodName, new JavaClass[] {}); if (method == null) { throw org.eclipse.persistence.exceptions.JAXBException.factoryMethodNotDeclared(factoryMethodName, javaClass.getName()); } info.setFactoryMethodName(factoryMethodName); } } else { if (factoryMethodName == null || factoryMethodName.equals(EMPTY_STRING)) { throw org.eclipse.persistence.exceptions.JAXBException.factoryClassWithoutFactoryMethod(javaClass.getName()); } info.setObjectFactoryClassName(factoryClassName); info.setFactoryMethodName(factoryMethodName); } // figure out type name String typeName = xmlType.getName(); if (typeName.equals(XMLProcessor.DEFAULT)) { typeName = getSchemaTypeNameForClassName(javaClass.getName()); } info.setSchemaTypeName(typeName); // set propOrder if (xmlType.isSetPropOrder()) { List<String> props = xmlType.getPropOrder(); if (props.size() == 0) { info.setPropOrder(new String[0]); } else if (props.get(0).equals(EMPTY_STRING)) { info.setPropOrder(new String[] { EMPTY_STRING }); } else { info.setPropOrder(xmlType.getPropOrder().toArray(new String[xmlType.getPropOrder().size()])); } } // figure out namespace if (xmlType.getNamespace().equals(XMLProcessor.DEFAULT)) { info.setClassNamespace(packageNamespace.getNamespace()); } else { info.setClassNamespace(xmlType.getNamespace()); } } /** * Process @XmlAccessorType annotation on a given JavaClass and update the * TypeInfo for pre-processing. * * @param javaClass * @param info * @param packageNamespace */ private void preProcessXmlAccessorType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) { org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType xmlAccessType; if (helper.isAnnotationPresent(javaClass, XmlAccessorType.class)) { XmlAccessorType accessorType = (XmlAccessorType) helper.getAnnotation(javaClass, XmlAccessorType.class); xmlAccessType = org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType.fromValue(accessorType.value().name()); info.setXmlAccessType(xmlAccessType); } } /** * Post process XmlAccessorType. In some cases, such as @XmlSeeAlso classes, * the access type may not have been set * * @param info */ private void postProcessXmlAccessorType(TypeInfo info, NamespaceInfo packageNamespace) { if (!info.isSetXmlAccessType()) { // use value in package-info.java as last resort - will default if // not set info.setXmlAccessType(org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType.fromValue(packageNamespace.getAccessType().name())); } } /** * Process package and class @XmlAccessorOrder. Class level annotation * overrides a package level annotation. * * @param javaClass * @param info * @param packageNamespace */ private void preProcessXmlAccessorOrder(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) { XmlAccessorOrder order = null; // class level annotation overrides package level annotation if (helper.isAnnotationPresent(javaClass, XmlAccessorOrder.class)) { order = (XmlAccessorOrder) helper.getAnnotation(javaClass, XmlAccessorOrder.class); info.setXmlAccessOrder(XmlAccessOrder.fromValue(order.value().name())); } } /** * Post process XmlAccessorOrder. This method assumes that the given * TypeInfo has already had its order set (via annotations in * preProcessXmlAccessorOrder or via xml metadata override in XMLProcessor). * * @param javaClass * @param info */ private void postProcessXmlAccessorOrder(TypeInfo info, NamespaceInfo packageNamespace) { if (!info.isSetXmlAccessOrder()) { // use value in package-info.java as last resort - will default if // not set info.setXmlAccessOrder(org.eclipse.persistence.jaxb.xmlmodel.XmlAccessOrder.fromValue(packageNamespace.getAccessOrder().name())); } info.orderProperties(); } /** * Process @XmlElement annotation on a given property. * * @param property */ private void processXmlElement(Property property, TypeInfo info) { if (helper.isAnnotationPresent(property.getElement(), XmlElement.class)) { XmlElement element = (XmlElement) helper.getAnnotation(property.getElement(), XmlElement.class); property.setIsRequired(element.required()); property.setNillable(element.nillable()); if (element.type() != XmlElement.DEFAULT.class) { property.setOriginalType(property.getType()); if (isCollectionType(property.getType())) { property.setGenericType(helper.getJavaClass(element.type())); } else { property.setType(helper.getJavaClass(element.type())); } property.setHasXmlElementType(true); } // handle default value if (!element.defaultValue().equals(ELEMENT_DECL_DEFAULT)) { property.setDefaultValue(element.defaultValue()); } validateElementIsInPropOrder(info, property.getPropertyName()); } } /** * Process @XmlID annotation on a given property * * @param property * @param info */ private void processXmlID(Property property, JavaClass javaClass, TypeInfo info) { if (helper.isAnnotationPresent(property.getElement(), XmlID.class)) { property.setIsXmlId(true); info.setIDProperty(property); } } /** * Process @XmlIDREF on a given property. * * @param property */ private void processXmlIDREF(Property property) { if (helper.isAnnotationPresent(property.getElement(), XmlIDREF.class)) { property.setIsXmlIdRef(true); } } /** * Process @XmlJavaTypeAdapter on a given property. * * @param property * @param propertyType */ private void processXmlJavaTypeAdapter(Property property, TypeInfo info, JavaClass javaClass) { JavaClass adapterClass = null; JavaClass ptype = property.getActualType(); if (helper.isAnnotationPresent(property.getElement(), XmlJavaTypeAdapter.class)) { XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(property.getElement(), XmlJavaTypeAdapter.class); org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter(); xja.setValue(adapter.value().getName()); xja.setType(adapter.type().getName()); property.setXmlJavaTypeAdapter(xja); } else { TypeInfo ptypeInfo = typeInfo.get(ptype.getQualifiedName()); boolean newTypeInfoForAdapter = false; if (ptypeInfo == null && shouldGenerateTypeInfo(ptype)) { JavaClass[] jClassArray = new JavaClass[] { ptype }; buildNewTypeInfo(jClassArray); ptypeInfo = typeInfo.get(ptype.getQualifiedName()); newTypeInfoForAdapter = true; } org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xmlJavaTypeAdapter; if (ptypeInfo != null) { if (null != (xmlJavaTypeAdapter = ptypeInfo.getXmlJavaTypeAdapter())) { try { property.setXmlJavaTypeAdapter(xmlJavaTypeAdapter); } catch (JAXBException e) { throw JAXBException.invalidTypeAdapterClass(xmlJavaTypeAdapter.getValue(), javaClass.getName()); } } else { if(newTypeInfoForAdapter) { removeTypeInfo(ptype.getQualifiedName(), ptypeInfo); } } } if (info.getPackageLevelAdaptersByClass().get(ptype.getQualifiedName()) != null && !property.isSetXmlJavaTypeAdapter()) { adapterClass = info.getPackageLevelAdapterClass(ptype); org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter(); xja.setValue(adapterClass.getQualifiedName()); xja.setType(ptype.getQualifiedName()); property.setXmlJavaTypeAdapter(xja); } } } private void removeTypeInfo(String qualifiedName, TypeInfo info) { this.typeInfo.remove(qualifiedName); String typeName = info.getSchemaTypeName(); if (typeName != null && !(EMPTY_STRING.equals(typeName))) { QName typeQName = new QName(info.getClassNamespace(), typeName); this.typeQNames.remove(typeQName); } for(JavaClass next:this.typeInfoClasses) { if(next.getQualifiedName().equals(info.getJavaClassName())) { this.typeInfoClasses.remove(next); break; } } } /** * Store a QName (if necessary) based on a given TypeInfo's schema type * name. * * @param javaClass * @param info */ private void processTypeQName(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) { String typeName = info.getSchemaTypeName(); if (typeName != null && !(EMPTY_STRING.equals(typeName))) { QName typeQName = new QName(info.getClassNamespace(), typeName); boolean containsQName = typeQNames.contains(typeQName); if (containsQName) { throw JAXBException.nameCollision(typeQName.getNamespaceURI(), typeQName.getLocalPart()); } else { typeQNames.add(typeQName); } } } public boolean shouldGenerateTypeInfo(JavaClass javaClass) { if (javaClass == null || javaClass.isPrimitive() || javaClass.isAnnotation() || ORG_W3C_DOM.equals(javaClass.getPackageName())) { return false; } if (userDefinedSchemaTypes.get(javaClass.getQualifiedName()) != null) { return false; } if (javaClass.isArray()) { String javaClassName = javaClass.getName(); if (!(javaClassName.equals(ClassConstants.ABYTE.getName()) || javaClassName.equals(ClassConstants.APBYTE.getName()))) { return true; } } if (helper.isBuiltInJavaType(javaClass)) { return false; } if (isCollectionType(javaClass) || isMapType(javaClass)) { return false; } return true; } public ArrayList<Property> getPropertiesForClass(JavaClass cls, TypeInfo info) { ArrayList<Property> returnList = new ArrayList<Property>(); if (!info.isTransient()) { JavaClass superClass = cls.getSuperclass(); if (null != superClass) { TypeInfo superClassInfo = typeInfo.get(superClass.getQualifiedName()); while (superClassInfo != null && superClassInfo.isTransient()) { List<Property> superProps = getPublicMemberPropertiesForClass(superClass, superClassInfo); returnList.addAll(0, superProps); superClass = superClass.getSuperclass(); superClassInfo = typeInfo.get(superClass.getQualifiedName()); } } } if (info.isTransient()) { returnList.addAll(getNoAccessTypePropertiesForClass(cls, info)); } else if (info.getXmlAccessType() == XmlAccessType.FIELD) { returnList.addAll(getFieldPropertiesForClass(cls, info, false)); } else if (info.getXmlAccessType() == XmlAccessType.PROPERTY) { returnList.addAll(getPropertyPropertiesForClass(cls, info, false)); } else if (info.getXmlAccessType() == XmlAccessType.PUBLIC_MEMBER) { returnList.addAll(getPublicMemberPropertiesForClass(cls, info)); } else { returnList.addAll(getNoAccessTypePropertiesForClass(cls, info)); } return returnList; } public ArrayList<Property> getFieldPropertiesForClass(JavaClass cls, TypeInfo info, boolean onlyPublic) { ArrayList<Property> properties = new ArrayList<Property>(); if (cls == null) { return properties; } for (Iterator<JavaField> fieldIt = cls.getDeclaredFields().iterator(); fieldIt.hasNext();) { JavaField nextField = fieldIt.next(); int modifiers = nextField.getModifiers(); if (!helper.isAnnotationPresent(nextField, XmlTransient.class)) { if (!Modifier.isTransient(modifiers) && ((Modifier.isPublic(nextField.getModifiers()) && onlyPublic) || !onlyPublic)) { if (!Modifier.isStatic(modifiers)) { Property property = buildNewProperty(info, cls, nextField, nextField.getName(), nextField.getResolvedType()); properties.add(property); } else if (helper.isAnnotationPresent(nextField, XmlAttribute.class)) { try { Property property = buildNewProperty(info, cls, nextField, nextField.getName(), nextField.getResolvedType()); Object value = ((JavaFieldImpl) nextField).get(null); if(value != null) { String stringValue = (String) XMLConversionManager.getDefaultXMLManager().convertObject(value, String.class, property.getSchemaType()); property.setFixedValue(stringValue); } else { property.setWriteOnly(true); } properties.add(property); } catch (ClassCastException e) { // do Nothing } catch (IllegalAccessException e) { // do Nothing } } } } else { // If a property is marked transient ensure it doesn't exist in // the propOrder List<String> propOrderList = Arrays.asList(info.getPropOrder()); if (propOrderList.contains(nextField.getName())) { throw JAXBException.transientInProporder(nextField.getName()); } } } return properties; } /* * Create a new Property Object and process the annotations that are common * to fields and methods */ private Property buildNewProperty(TypeInfo info, JavaClass cls, JavaHasAnnotations javaHasAnnotations, String propertyName, JavaClass ptype) { Property property = null; if (helper.isAnnotationPresent(javaHasAnnotations, XmlElements.class)) { property = buildChoiceProperty(javaHasAnnotations); } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlElementRef.class) || helper.isAnnotationPresent(javaHasAnnotations, XmlElementRefs.class)) { property = buildReferenceProperty(info, javaHasAnnotations, propertyName, ptype); if (helper.isAnnotationPresent(javaHasAnnotations, XmlAnyElement.class)) { XmlAnyElement anyElement = (XmlAnyElement) helper.getAnnotation(javaHasAnnotations, XmlAnyElement.class); property.setIsAny(true); if (anyElement.value() != null) { property.setDomHandlerClassName(anyElement.value().getName()); } property.setLax(anyElement.lax()); info.setAnyElementPropertyName(propertyName); } } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlAnyElement.class)) { XmlAnyElement anyElement = (XmlAnyElement) helper.getAnnotation(javaHasAnnotations, XmlAnyElement.class); property = new Property(helper); property.setIsAny(true); if (anyElement.value() != null) { property.setDomHandlerClassName(anyElement.value().getName()); } property.setLax(anyElement.lax()); info.setAnyElementPropertyName(propertyName); } else if (helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlTransformation.class) || helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlReadTransformer.class) || helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlWriteTransformer.class) || helper.isAnnotationPresent(javaHasAnnotations, XmlWriteTransformers.class)) { property = buildTransformationProperty(javaHasAnnotations, cls); } else { property = new Property(helper); } property.setPropertyName(propertyName); property.setElement(javaHasAnnotations); // if there is a TypeInfo for ptype check it for transient, otherwise // check the class TypeInfo pTypeInfo = typeInfo.get(ptype.getQualifiedName()); if ((pTypeInfo != null && !pTypeInfo.isTransient()) || !helper.isAnnotationPresent(ptype, XmlTransient.class)) { property.setType(ptype); } else { JavaClass parent = ptype.getSuperclass(); while (parent != null) { if (parent.getName().equals(JAVA_LANG_OBJECT)) { property.setType(parent); break; } // if there is a TypeInfo for parent check it for transient, // otherwise check the class TypeInfo parentTypeInfo = typeInfo.get(parent.getQualifiedName()); if ((parentTypeInfo != null && !parentTypeInfo.isTransient()) || !helper.isAnnotationPresent(parent, XmlTransient.class)) { property.setType(parent); break; } parent = parent.getSuperclass(); } } processPropertyAnnotations(info, cls, javaHasAnnotations, property); if (helper.isAnnotationPresent(javaHasAnnotations, XmlPath.class)) { XmlPath xmlPath = (XmlPath) helper.getAnnotation(javaHasAnnotations, XmlPath.class); property.setXmlPath(xmlPath.value()); // set schema name String schemaName = XMLProcessor.getNameFromXPath(xmlPath.value(), property.getPropertyName(), property.isAttribute()); QName qName; NamespaceInfo nsInfo = getNamespaceInfoForPackage(cls); if (nsInfo.isElementFormQualified()) { qName = new QName(nsInfo.getNamespace(), schemaName); } else { qName = new QName(schemaName); } property.setSchemaName(qName); } else { property.setSchemaName(getQNameForProperty(propertyName, javaHasAnnotations, getNamespaceInfoForPackage(cls), info.getClassNamespace())); } ptype = property.getActualType(); if (ptype.isPrimitive()) { property.setIsRequired(true); } // apply class level adapters - don't override property level adapter if (!property.isSetXmlJavaTypeAdapter()) { TypeInfo refClassInfo = getTypeInfo().get(ptype.getQualifiedName()); if (refClassInfo != null && refClassInfo.isSetXmlJavaTypeAdapter()) { org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xmlJavaTypeAdapter = null; try { xmlJavaTypeAdapter = refClassInfo.getXmlJavaTypeAdapter(); property.setXmlJavaTypeAdapter(refClassInfo.getXmlJavaTypeAdapter()); } catch (JAXBException e) { throw JAXBException.invalidTypeAdapterClass(xmlJavaTypeAdapter.getValue(), cls.getName()); } } } return property; } /** * Build a new 'choice' property. Here, we flag a new property as a 'choice' * and create/set an XmlModel XmlElements object based on the @XmlElements * annotation. * * Validation and building of the XmlElement properties will be done during * finalizeProperties in the processChoiceProperty method. * * @param javaHasAnnotations * @return */ private Property buildChoiceProperty(JavaHasAnnotations javaHasAnnotations) { Property choiceProperty = new Property(helper); choiceProperty.setChoice(true); boolean isIdRef = helper.isAnnotationPresent(javaHasAnnotations, XmlIDREF.class); choiceProperty.setIsXmlIdRef(isIdRef); // build an XmlElement to set on the Property org.eclipse.persistence.jaxb.xmlmodel.XmlElements xmlElements = new org.eclipse.persistence.jaxb.xmlmodel.XmlElements(); XmlElement[] elements = ((XmlElements) helper.getAnnotation(javaHasAnnotations, XmlElements.class)).value(); for (int i = 0; i < elements.length; i++) { XmlElement next = elements[i]; org.eclipse.persistence.jaxb.xmlmodel.XmlElement xmlElement = new org.eclipse.persistence.jaxb.xmlmodel.XmlElement(); xmlElement.setDefaultValue(next.defaultValue()); xmlElement.setName(next.name()); xmlElement.setNamespace(next.namespace()); xmlElement.setNillable(next.nillable()); xmlElement.setRequired(next.required()); xmlElement.setType(next.type().getName()); xmlElements.getXmlElement().add(xmlElement); } choiceProperty.setXmlElements(xmlElements); // handle XmlElementsJoinNodes if (helper.isAnnotationPresent(javaHasAnnotations, XmlElementsJoinNodes.class)) { org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes; org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode; List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes> xmlJoinNodesList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes>(); List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode> xmlJoinNodeList = null; for (XmlJoinNodes xmlJNs : ((XmlElementsJoinNodes) helper.getAnnotation(javaHasAnnotations, XmlElementsJoinNodes.class)).value()) { xmlJoinNodeList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode>(); for (XmlJoinNode xmlJN : xmlJNs.value()) { xmlJoinNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode(); xmlJoinNode.setXmlPath(xmlJN.xmlPath()); xmlJoinNode.setReferencedXmlPath(xmlJN.referencedXmlPath()); xmlJoinNodeList.add(xmlJoinNode); } if (xmlJoinNodeList.size() > 0) { xmlJoinNodes = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes(); xmlJoinNodes.setXmlJoinNode(xmlJoinNodeList); xmlJoinNodesList.add(xmlJoinNodes); } } choiceProperty.setXmlJoinNodesList(xmlJoinNodesList); } return choiceProperty; } private Property buildTransformationProperty(JavaHasAnnotations javaHasAnnotations, JavaClass cls) { Property property = new Property(helper); org.eclipse.persistence.oxm.annotations.XmlTransformation transformationAnnotation = (org.eclipse.persistence.oxm.annotations.XmlTransformation) helper.getAnnotation(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlTransformation.class); XmlTransformation transformation = new XmlTransformation(); if (transformationAnnotation != null) { transformation.setOptional(transformationAnnotation.optional()); } // Read Transformer org.eclipse.persistence.oxm.annotations.XmlReadTransformer readTransformer = (org.eclipse.persistence.oxm.annotations.XmlReadTransformer) helper.getAnnotation(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlReadTransformer.class); if (readTransformer != null) { org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlReadTransformer xmlReadTransformer = new org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlReadTransformer(); if (!(readTransformer.transformerClass() == AttributeTransformer.class)) { xmlReadTransformer.setTransformerClass(readTransformer.transformerClass().getName()); } else if (!(readTransformer.method().equals(EMPTY_STRING))) { xmlReadTransformer.setMethod(readTransformer.method()); } transformation.setXmlReadTransformer(xmlReadTransformer); } // Handle Write Transformers org.eclipse.persistence.oxm.annotations.XmlWriteTransformer[] transformers = null; if (helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlWriteTransformer.class)) { org.eclipse.persistence.oxm.annotations.XmlWriteTransformer writeTransformer = (org.eclipse.persistence.oxm.annotations.XmlWriteTransformer) helper.getAnnotation(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlWriteTransformer.class); transformers = new org.eclipse.persistence.oxm.annotations.XmlWriteTransformer[] { writeTransformer }; } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlWriteTransformers.class)) { XmlWriteTransformers writeTransformers = (XmlWriteTransformers) helper.getAnnotation(javaHasAnnotations, XmlWriteTransformers.class); transformers = writeTransformers.value(); } if (transformers != null) { for (org.eclipse.persistence.oxm.annotations.XmlWriteTransformer next : transformers) { org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransformer xmlWriteTransformer = new org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransformer(); if (!(next.transformerClass() == FieldTransformer.class)) { xmlWriteTransformer.setTransformerClass(next.transformerClass().getName()); } else if (!(next.method().equals(EMPTY_STRING))) { xmlWriteTransformer.setMethod(next.method()); } xmlWriteTransformer.setXmlPath(next.xmlPath()); transformation.getXmlWriteTransformer().add(xmlWriteTransformer); } } property.setXmlTransformation(transformation); property.setIsXmlTransformation(true); return property; } /** * Complete creation of a 'choice' property. Here, a Property is created for * each XmlElement in the XmlElements list. Validation is performed as well. * Each created Property is added to the owning Property's list of choice * properties. * * @param choiceProperty * @param info * @param cls * @param propertyType */ private void processChoiceProperty(Property choiceProperty, TypeInfo info, JavaClass cls, JavaClass propertyType) { String propertyName = choiceProperty.getPropertyName(); validateElementIsInPropOrder(info, propertyName); // validate XmlElementsXmlJoinNodes (if set) if (choiceProperty.isSetXmlJoinNodesList()) { // there must be one XmlJoinNodes entry per XmlElement if (choiceProperty.getXmlElements().getXmlElement().size() != choiceProperty.getXmlJoinNodesList().size()) { throw JAXBException.incorrectNumberOfXmlJoinNodesOnXmlElements(propertyName, cls.getQualifiedName()); } } XmlPath[] paths = null; if (helper.isAnnotationPresent(choiceProperty.getElement(), XmlPaths.class)) { XmlPaths pathAnnotation = (XmlPaths) helper.getAnnotation(choiceProperty.getElement(), XmlPaths.class); paths = pathAnnotation.value(); } ArrayList<Property> choiceProperties = new ArrayList<Property>(); for (int i = 0; i < choiceProperty.getXmlElements().getXmlElement().size(); i++) { org.eclipse.persistence.jaxb.xmlmodel.XmlElement next = choiceProperty.getXmlElements().getXmlElement().get(i); Property choiceProp = new Property(helper); String name; String namespace; // handle XmlPath - if xml-path is set, we ignore name/namespace if (paths != null && next.getXmlPath() == null) { // Only set the path, if the path hasn't already been set from xml XmlPath nextPath = paths[i]; next.setXmlPath(nextPath.value()); } if (next.getXmlPath() != null) { choiceProp.setXmlPath(next.getXmlPath()); boolean isAttribute = next.getXmlPath().contains(AT_SIGN); // validate attribute - must be in nested path, not at root if (isAttribute && !next.getXmlPath().contains(SLASH)) { throw JAXBException.invalidXmlPathWithAttribute(propertyName, cls.getQualifiedName(), next.getXmlPath()); } choiceProp.setIsAttribute(isAttribute); name = XMLProcessor.getNameFromXPath(next.getXmlPath(), propertyName, isAttribute); namespace = XMLProcessor.DEFAULT; } else { // no xml-path, so use name/namespace from xml-element name = next.getName(); namespace = next.getNamespace(); } if (name == null || name.equals(XMLProcessor.DEFAULT)) { if (next.getJavaAttribute() != null) { name = next.getJavaAttribute(); } else { name = propertyName; } } // if the property has xml-idref, the target type of each // xml-element in the list must have an xml-id property if (choiceProperty.isXmlIdRef()) { TypeInfo tInfo = typeInfo.get(next.getType()); if (tInfo == null || !tInfo.isIDSet()) { throw JAXBException.invalidXmlElementInXmlElementsList(propertyName, name); } } QName qName = null; if (!namespace.equals(XMLProcessor.DEFAULT)) { qName = new QName(namespace, name); } else { NamespaceInfo namespaceInfo = getNamespaceInfoForPackage(cls); if (namespaceInfo.isElementFormQualified()) { qName = new QName(namespaceInfo.getNamespace(), name); } else { qName = new QName(name); } } choiceProp.setPropertyName(name); // figure out the property's type - note that for DEFAULT, if from XML the value will // be "XmlElement.DEFAULT", and from annotations the value will be "XmlElement$DEFAULT" if (next.getType().equals("javax.xml.bind.annotation.XmlElement.DEFAULT") || next.getType().equals("javax.xml.bind.annotation.XmlElement$DEFAULT")) { choiceProp.setType(propertyType); } else { choiceProp.setType(helper.getJavaClass(next.getType())); } // handle case of XmlJoinNodes w/XmlElements if (choiceProperty.isSetXmlJoinNodesList()) { // assumes one corresponding xml-join-nodes entry per xml-element org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes = choiceProperty.getXmlJoinNodesList().get(i); if (xmlJoinNodes != null) { choiceProp.setXmlJoinNodes(xmlJoinNodes); // set type if (!xmlJoinNodes.getType().equals(XMLProcessor.DEFAULT)) { JavaClass pType = helper.getJavaClass(xmlJoinNodes.getType()); if (isCollectionType(choiceProp.getType())) { choiceProp.setGenericType(pType); } else { choiceProp.setType(pType); } } } } choiceProp.setSchemaName(qName); choiceProp.setSchemaType(getSchemaTypeFor(choiceProp.getType())); choiceProp.setIsXmlIdRef(choiceProperty.isXmlIdRef()); choiceProp.setXmlElementWrapper(choiceProperty.getXmlElementWrapper()); choiceProperties.add(choiceProp); if (!(this.typeInfo.containsKey(choiceProp.getType().getQualifiedName())) && shouldGenerateTypeInfo(choiceProp.getType())) { JavaClass[] jClassArray = new JavaClass[] { choiceProp.getType() }; buildNewTypeInfo(jClassArray); } } choiceProperty.setChoiceProperties(choiceProperties); } /** * Build a reference property. Here we will build a list of XML model * XmlElementRef objects, based on the @XmlElement(s) annotation, to store * on the Property. Processing of the elements and validation will be * performed during the finalize property phase via the * processReferenceProperty method. * * @param info * @param javaHasAnnotations * @param propertyName * @param ptype * @return */ private Property buildReferenceProperty(TypeInfo info, JavaHasAnnotations javaHasAnnotations, String propertyName, JavaClass ptype) { Property property = new Property(helper); property.setType(ptype); XmlElementRef[] elementRefs; XmlElementRef ref = (XmlElementRef) helper.getAnnotation(javaHasAnnotations, XmlElementRef.class); if (ref != null) { elementRefs = new XmlElementRef[] { ref }; } else { XmlElementRefs refs = (XmlElementRefs) helper.getAnnotation(javaHasAnnotations, XmlElementRefs.class); elementRefs = refs.value(); info.setElementRefsPropertyName(propertyName); } List<org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef> eltRefs = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef>(); for (XmlElementRef nextRef : elementRefs) { org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef eltRef = new org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef(); eltRef.setName(nextRef.name()); eltRef.setNamespace(nextRef.namespace()); eltRef.setType(nextRef.type().getName()); eltRefs.add(eltRef); } property.setIsReference(true); property.setXmlElementRefs(eltRefs); return property; } /** * Build a reference property. * * @param property * @param info * @param javaHasAnnotations * @return */ private Property processReferenceProperty(Property property, TypeInfo info, JavaClass cls) { String propertyName = property.getPropertyName(); validateElementIsInPropOrder(info, propertyName); for (org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef nextRef : property.getXmlElementRefs()) { JavaClass type = property.getType(); String typeName = type.getQualifiedName(); if (isCollectionType(property)) { if (type.hasActualTypeArguments()) { type = property.getGenericType(); typeName = type.getQualifiedName(); } } // for DEFAULT, if from XML the type will be "XmlElementRef.DEFAULT", // and from annotations the value will be "XmlElementref$DEFAULT" if (!(nextRef.getType().equals("javax.xml.bind.annotation.XmlElementRef.DEFAULT") || nextRef.getType().equals("javax.xml.bind.annotation.XmlElementRef$DEFAULT"))) { typeName = nextRef.getType(); type = helper.getJavaClass(typeName); } boolean missingReference = true; for (Entry<String, ElementDeclaration> entry : xmlRootElements.entrySet()) { ElementDeclaration entryValue = entry.getValue(); if (type.isAssignableFrom(entryValue.getJavaType())) { addReferencedElement(property, entryValue); missingReference = false; } } if (missingReference) { String name = nextRef.getName(); String namespace = nextRef.getNamespace(); if (namespace.equals(XMLProcessor.DEFAULT)) { namespace = EMPTY_STRING; } QName qname = new QName(namespace, name); JavaClass scopeClass = cls; ElementDeclaration referencedElement = null; while (!(scopeClass.getName().equals(JAVA_LANG_OBJECT))) { HashMap<QName, ElementDeclaration> elements = getElementDeclarationsForScope(scopeClass.getName()); if (elements != null) { referencedElement = elements.get(qname); } if (referencedElement != null) { break; } scopeClass = scopeClass.getSuperclass(); } if (referencedElement == null) { referencedElement = this.getGlobalElements().get(qname); } if (referencedElement != null) { addReferencedElement(property, referencedElement); } else { throw org.eclipse.persistence.exceptions.JAXBException.invalidElementRef(property.getPropertyName(), cls.getName()); } } } return property; } private void processPropertyAnnotations(TypeInfo info, JavaClass cls, JavaHasAnnotations javaHasAnnotations, Property property) { // Check for mixed context if (helper.isAnnotationPresent(javaHasAnnotations, XmlMixed.class)) { info.setMixed(true); property.setMixedContent(true); } if (helper.isAnnotationPresent(javaHasAnnotations, XmlContainerProperty.class)) { XmlContainerProperty container = (XmlContainerProperty) helper.getAnnotation(javaHasAnnotations, XmlContainerProperty.class); property.setInverseReferencePropertyName(container.value()); property.setInverseReferencePropertyGetMethodName(container.getMethodName()); property.setInverseReferencePropertySetMethodName(container.setMethodName()); } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlInverseReference.class)) { XmlInverseReference inverseReference = (XmlInverseReference) helper.getAnnotation(javaHasAnnotations, XmlInverseReference.class); property.setInverseReferencePropertyName(inverseReference.mappedBy()); TypeInfo targetInfo = this.getTypeInfo().get(property.getActualType().getName()); if (targetInfo != null && targetInfo.getXmlAccessType() == XmlAccessType.PROPERTY) { String propName = property.getPropertyName(); propName = Character.toUpperCase(propName.charAt(0)) + propName.substring(1); property.setInverseReferencePropertyGetMethodName("get" + propName); property.setInverseReferencePropertySetMethodName("set" + propName); } property.setInverseReference(true); } processXmlJavaTypeAdapter(property, info, cls); processXmlElement(property, info); JavaClass ptype = property.getActualType(); if (helper.isAnnotationPresent(property.getElement(), XmlAttachmentRef.class) && areEquals(ptype, JAVAX_ACTIVATION_DATAHANDLER)) { property.setIsSwaAttachmentRef(true); property.setSchemaType(XMLConstants.SWA_REF_QNAME); } else if (isMtomAttachment(property)) { property.setIsMtomAttachment(true); property.setSchemaType(XMLConstants.BASE_64_BINARY_QNAME); } if (helper.isAnnotationPresent(property.getElement(), XmlMimeType.class)) { property.setMimeType(((XmlMimeType) helper.getAnnotation(property.getElement(), XmlMimeType.class)).value()); } // set indicator for inlining binary data - setting this to true on a // non-binary data type won't have any affect if (helper.isAnnotationPresent(property.getElement(), XmlInlineBinaryData.class) || info.isBinaryDataToBeInlined()) { property.setisInlineBinaryData(true); } // Get schema-type info if specified and set it on the property for // later use: if (helper.isAnnotationPresent(property.getElement(), XmlSchemaType.class)) { XmlSchemaType schemaType = (XmlSchemaType) helper.getAnnotation(property.getElement(), XmlSchemaType.class); QName schemaTypeQname = new QName(schemaType.namespace(), schemaType.name()); property.setSchemaType(schemaTypeQname); } if (helper.isAnnotationPresent(property.getElement(), XmlAttribute.class)) { property.setIsAttribute(true); property.setIsRequired(((XmlAttribute) helper.getAnnotation(property.getElement(), XmlAttribute.class)).required()); } if (helper.isAnnotationPresent(property.getElement(), XmlAnyAttribute.class)) { if (info.isSetAnyAttributePropertyName()) { throw org.eclipse.persistence.exceptions.JAXBException.multipleAnyAttributeMapping(cls.getName()); } if (!property.getType().getName().equals("java.util.Map")) { throw org.eclipse.persistence.exceptions.JAXBException.anyAttributeOnNonMap(property.getPropertyName()); } property.setIsAnyAttribute(true); info.setAnyAttributePropertyName(property.getPropertyName()); } // Make sure XmlElementWrapper annotation is on a collection or array if (helper.isAnnotationPresent(property.getElement(), XmlElementWrapper.class)) { XmlElementWrapper wrapper = (XmlElementWrapper) helper.getAnnotation(property.getElement(), XmlElementWrapper.class); org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper xmlEltWrapper = new org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper(); xmlEltWrapper.setName(wrapper.name()); xmlEltWrapper.setNamespace(wrapper.namespace()); xmlEltWrapper.setNillable(wrapper.nillable()); xmlEltWrapper.setRequired(wrapper.required()); property.setXmlElementWrapper(xmlEltWrapper); } if (helper.isAnnotationPresent(property.getElement(), XmlList.class)) { // Make sure XmlList annotation is on a collection or array if (!isCollectionType(property) && !property.getType().isArray()) { throw JAXBException.invalidList(property.getPropertyName()); } property.setIsXmlList(true); } if (helper.isAnnotationPresent(property.getElement(), XmlValue.class)) { property.setIsXmlValue(true); info.setXmlValueProperty(property); } if (helper.isAnnotationPresent(property.getElement(), XmlReadOnly.class)) { property.setReadOnly(true); } if (helper.isAnnotationPresent(property.getElement(), XmlWriteOnly.class)) { property.setWriteOnly(true); } if (helper.isAnnotationPresent(property.getElement(), XmlCDATA.class)) { property.setCdata(true); } if (helper.isAnnotationPresent(property.getElement(), XmlAccessMethods.class)) { XmlAccessMethods accessMethods = (XmlAccessMethods) helper.getAnnotation(property.getElement(), XmlAccessMethods.class); if (!(accessMethods.getMethodName().equals(EMPTY_STRING))) { property.setGetMethodName(accessMethods.getMethodName()); } if (!(accessMethods.setMethodName().equals(EMPTY_STRING))) { property.setSetMethodName(accessMethods.setMethodName()); } if (!(property.isMethodProperty())) { property.setMethodProperty(true); } } // handle user properties if (helper.isAnnotationPresent(property.getElement(), XmlProperties.class)) { XmlProperties xmlProperties = (XmlProperties) helper.getAnnotation(property.getElement(), XmlProperties.class); Map<Object, Object> propertiesMap = createUserPropertiesMap(xmlProperties.value()); property.setUserProperties(propertiesMap); } else if (helper.isAnnotationPresent(property.getElement(), XmlProperty.class)) { XmlProperty xmlProperty = (XmlProperty) helper.getAnnotation(property.getElement(), XmlProperty.class); Map<Object, Object> propertiesMap = createUserPropertiesMap(new XmlProperty[] { xmlProperty }); property.setUserProperties(propertiesMap); } // handle XmlKey if (helper.isAnnotationPresent(property.getElement(), XmlKey.class)) { info.addXmlKeyProperty(property); } // handle XmlJoinNode(s) processXmlJoinNodes(property); processXmlNullPolicy(property); } /** * Process XmlJoinNode(s) for a given Property. An * org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNode(s) will be * created/populated using the annotation, and set on the Property for later * processing. * * It is assumed that for a single join node XmlJoinNode will be used, and * for multiple join nodes XmlJoinNodes will be used. * * @param property * Property that may contain @XmlJoinNodes/@XmlJoinNode */ private void processXmlJoinNodes(Property property) { List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode> xmlJoinNodeList; org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode; org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes; // handle XmlJoinNodes if (helper.isAnnotationPresent(property.getElement(), XmlJoinNodes.class)) { xmlJoinNodeList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode>(); for (XmlJoinNode xmlJN : ((XmlJoinNodes) helper.getAnnotation(property.getElement(), XmlJoinNodes.class)).value()) { xmlJoinNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode(); xmlJoinNode.setXmlPath(xmlJN.xmlPath()); xmlJoinNode.setReferencedXmlPath(xmlJN.referencedXmlPath()); xmlJoinNodeList.add(xmlJoinNode); } xmlJoinNodes = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes(); xmlJoinNodes.setXmlJoinNode(xmlJoinNodeList); property.setXmlJoinNodes(xmlJoinNodes); } // handle XmlJoinNode else if (helper.isAnnotationPresent(property.getElement(), XmlJoinNode.class)) { XmlJoinNode xmlJN = (XmlJoinNode) helper.getAnnotation(property.getElement(), XmlJoinNode.class); xmlJoinNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode(); xmlJoinNode.setXmlPath(xmlJN.xmlPath()); xmlJoinNode.setReferencedXmlPath(xmlJN.referencedXmlPath()); xmlJoinNodeList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode>(); xmlJoinNodeList.add(xmlJoinNode); xmlJoinNodes = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes(); xmlJoinNodes.setXmlJoinNode(xmlJoinNodeList); property.setXmlJoinNodes(xmlJoinNodes); } } /** * Responsible for validating transformer settings on a given property. * Validates that for field transformers either a transformer class OR * method name is set (not both) and that an xml-path is set. Validates that * for attribute transformers either a transformer class OR method name is * set (not both). * * @param property */ private void processXmlTransformationProperty(Property property) { if (property.isSetXmlTransformation()) { XmlTransformation xmlTransformation = property.getXmlTransformation(); // validate transformer(s) if (xmlTransformation.isSetXmlReadTransformer()) { // validate read transformer XmlReadTransformer readTransformer = xmlTransformation.getXmlReadTransformer(); if (readTransformer.isSetTransformerClass()) { // handle read transformer class if (readTransformer.isSetMethod()) { // cannot have both class and method set throw JAXBException.readTransformerHasBothClassAndMethod(property.getPropertyName()); } } else { // handle read transformer method if (!readTransformer.isSetMethod()) { // require class or method to be set throw JAXBException.readTransformerHasNeitherClassNorMethod(property.getPropertyName()); } } } if (xmlTransformation.isSetXmlWriteTransformers()) { // handle write transformer(s) for (XmlWriteTransformer writeTransformer : xmlTransformation.getXmlWriteTransformer()) { // must have an xml-path set if (!writeTransformer.isSetXmlPath()) { throw JAXBException.writeTransformerHasNoXmlPath(property.getPropertyName()); } if (writeTransformer.isSetTransformerClass()) { // handle write transformer class if (writeTransformer.isSetMethod()) { // cannot have both class and method set throw JAXBException.writeTransformerHasBothClassAndMethod(property.getPropertyName(), writeTransformer.getXmlPath()); } } else { // handle write transformer method if (!writeTransformer.isSetMethod()) { // require class or method to be set throw JAXBException.writeTransformerHasNeitherClassNorMethod(property.getPropertyName(), writeTransformer.getXmlPath()); } } } } } } /** * Compares a JavaModel JavaClass to a Class. Equality is based on the raw * name of the JavaClass compared to the canonical name of the Class. * * @param src * @param tgt * @return */ protected boolean areEquals(JavaClass src, Class tgt) { if (src == null || tgt == null) { return false; } return src.getRawName().equals(tgt.getCanonicalName()); } private void processXmlNullPolicy(Property property) { if (helper.isAnnotationPresent(property.getElement(), XmlNullPolicy.class)) { XmlNullPolicy nullPolicy = (XmlNullPolicy) helper.getAnnotation(property.getElement(), XmlNullPolicy.class); org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy policy = new org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy(); policy.setEmptyNodeRepresentsNull(nullPolicy.emptyNodeRepresentsNull()); policy.setIsSetPerformedForAbsentNode(nullPolicy.isSetPerformedForAbsentNode()); policy.setXsiNilRepresentsNull(new Boolean(nullPolicy.xsiNilRepresentsNull())); policy.setNullRepresentationForXml(org.eclipse.persistence.jaxb.xmlmodel.XmlMarshalNullRepresentation.valueOf(nullPolicy.nullRepresentationForXml().toString())); property.setNullPolicy(policy); } else if (helper.isAnnotationPresent(property.getElement(), XmlIsSetNullPolicy.class)) { XmlIsSetNullPolicy nullPolicy = (XmlIsSetNullPolicy) helper.getAnnotation(property.getElement(), XmlIsSetNullPolicy.class); org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy policy = new org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy(); policy.setEmptyNodeRepresentsNull(nullPolicy.emptyNodeRepresentsNull()); policy.setXsiNilRepresentsNull(new Boolean(nullPolicy.xsiNilRepresentsNull())); policy.setNullRepresentationForXml(org.eclipse.persistence.jaxb.xmlmodel.XmlMarshalNullRepresentation.valueOf(nullPolicy.nullRepresentationForXml().toString())); policy.setIsSetMethodName(nullPolicy.isSetMethodName()); for (XmlParameter next : nullPolicy.isSetParameters()) { org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy.IsSetParameter param = new org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy.IsSetParameter(); param.setValue(next.value()); param.setType(next.type().getName()); policy.getIsSetParameter().add(param); } property.setNullPolicy(policy); } } /** * Compares a JavaModel JavaClass to a Class. Equality is based on the raw * name of the JavaClass compared to the canonical name of the Class. * * @param src * @param tgt * @return */ protected boolean areEquals(JavaClass src, String tgtCanonicalName) { if (src == null || tgtCanonicalName == null) { return false; } return src.getRawName().equals(tgtCanonicalName); } public ArrayList<Property> getPropertyPropertiesForClass(JavaClass cls, TypeInfo info, boolean onlyPublic) { ArrayList<Property> properties = new ArrayList<Property>(); if (cls == null) { return properties; } // First collect all the getters and setters ArrayList<JavaMethod> propertyMethods = new ArrayList<JavaMethod>(); for (JavaMethod next : new ArrayList<JavaMethod>(cls.getDeclaredMethods())) { if (((next.getName().startsWith("get") && next.getName().length() > 3) || (next.getName().startsWith("is") && next.getName().length() > 2)) && next.getParameterTypes().length == 0 && next.getReturnType() != helper.getJavaClass(java.lang.Void.class)) { int modifiers = next.getModifiers(); if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && ((onlyPublic && Modifier.isPublic(next.getModifiers())) || !onlyPublic)) { propertyMethods.add(next); } } else if (next.getName().startsWith("set") && next.getName().length() > 3 && next.getParameterTypes().length == 1) { int modifiers = next.getModifiers(); if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && ((onlyPublic && Modifier.isPublic(next.getModifiers())) || !onlyPublic)) { propertyMethods.add(next); } } } // Next iterate over the getters and find their setter methods, add // whichever one is // annotated to the properties list. If neither is, use the getter // keep track of property names to avoid processing the same property // twice (for getter and setter) ArrayList<String> propertyNames = new ArrayList<String>(); for (int i = 0; i < propertyMethods.size(); i++) { boolean isPropertyTransient = false; JavaMethod nextMethod = propertyMethods.get(i); String propertyName = EMPTY_STRING; JavaMethod getMethod; JavaMethod setMethod; JavaMethod propertyMethod = null; if (!nextMethod.getName().startsWith("set")) { if (nextMethod.getName().startsWith("get")) { propertyName = nextMethod.getName().substring(3); } else if (nextMethod.getName().startsWith("is")) { propertyName = nextMethod.getName().substring(2); } getMethod = nextMethod; String setMethodName = "set" + propertyName; // use the JavaBean API to correctly decapitalize the first // character, if necessary propertyName = Introspector.decapitalize(propertyName); JavaClass[] paramTypes = { (JavaClass) getMethod.getReturnType() }; setMethod = cls.getDeclaredMethod(setMethodName, paramTypes); if (setMethod != null && !setMethod.getAnnotations().isEmpty()) { // use the set method if it exists and is annotated if (!helper.isAnnotationPresent(setMethod, XmlTransient.class)) { propertyMethod = setMethod; } else { isPropertyTransient = true; } } else { if (!helper.isAnnotationPresent(getMethod, XmlTransient.class)) { propertyMethod = getMethod; } else { isPropertyTransient = true; } } } else { propertyName = nextMethod.getName().substring(3); setMethod = nextMethod; String getMethodName = "get" + propertyName; getMethod = cls.getDeclaredMethod(getMethodName, new JavaClass[] {}); if (getMethod == null) { // try is instead of get getMethodName = "is" + propertyName; getMethod = cls.getDeclaredMethod(getMethodName, new JavaClass[] {}); } if (getMethod != null && !getMethod.getAnnotations().isEmpty()) { // use the set method if it exists and is annotated if (!helper.isAnnotationPresent(getMethod, XmlTransient.class)) { propertyMethod = getMethod; } else { isPropertyTransient = true; } } else { if (!helper.isAnnotationPresent(setMethod, XmlTransient.class)) { propertyMethod = setMethod; } else { isPropertyTransient = true; } } // use the JavaBean API to correctly decapitalize the first // character, if necessary propertyName = Introspector.decapitalize(propertyName); } JavaClass ptype = null; if (getMethod != null) { ptype = (JavaClass) getMethod.getReturnType(); } else { ptype = setMethod.getParameterTypes()[0]; } if (!propertyNames.contains(propertyName)) { propertyNames.add(propertyName); Property property = buildNewProperty(info, cls, propertyMethod, propertyName, ptype); property.setTransient(isPropertyTransient); if (getMethod != null) { property.setOriginalGetMethodName(getMethod.getName()); if (property.getGetMethodName() == null) { property.setGetMethodName(getMethod.getName()); } } if (setMethod != null) { property.setOriginalSetMethodName(setMethod.getName()); if (property.getSetMethodName() == null) { property.setSetMethodName(setMethod.getName()); } } property.setMethodProperty(true); if (!helper.isAnnotationPresent(property.getElement(), XmlTransient.class)) { properties.add(property); } else { // If a property is marked transient ensure it doesn't exist // in the propOrder List<String> propOrderList = Arrays.asList(info.getPropOrder()); if (propOrderList.contains(propertyName)) { throw JAXBException.transientInProporder(propertyName); } property.setTransient(true); } } } // default to alphabetical ordering // RI compliancy Collections.sort(properties, new PropertyComparitor()); return properties; } public ArrayList getPublicMemberPropertiesForClass(JavaClass cls, TypeInfo info) { ArrayList<Property> fieldProperties = getFieldPropertiesForClass(cls, info, false); ArrayList<Property> methodProperties = getPropertyPropertiesForClass(cls, info, false); // filter out non-public properties that aren't annotated ArrayList<Property> publicFieldProperties = new ArrayList<Property>(); ArrayList<Property> publicMethodProperties = new ArrayList<Property>(); for (Property next : fieldProperties) { if (Modifier.isPublic(((JavaField) next.getElement()).getModifiers())) { publicFieldProperties.add(next); } else { if (hasJAXBAnnotations(next.getElement())) { publicFieldProperties.add(next); } } } for (Property next : methodProperties) { if (next.getElement() != null) { if (Modifier.isPublic(((JavaMethod) next.getElement()).getModifiers())) { publicMethodProperties.add(next); } else { if (hasJAXBAnnotations(next.getElement())) { publicMethodProperties.add(next); } } } } // Not sure who should win if a property exists for both or the correct // order if (publicFieldProperties.size() >= 0 && publicMethodProperties.size() == 0) { return publicFieldProperties; } else if (publicMethodProperties.size() > 0 && publicFieldProperties.size() == 0) { return publicMethodProperties; } else { // add any non-duplicate method properties to the collection. // - in the case of a collision if one is annotated use it, // otherwise // use the field. HashMap fieldPropertyMap = getPropertyMapFromArrayList(publicFieldProperties); for (int i = 0; i < publicMethodProperties.size(); i++) { Property next = (Property) publicMethodProperties.get(i); if (fieldPropertyMap.get(next.getPropertyName()) == null) { publicFieldProperties.add(next); } } return publicFieldProperties; } } public HashMap getPropertyMapFromArrayList(ArrayList<Property> props) { HashMap propMap = new HashMap(props.size()); Iterator propIter = props.iterator(); while (propIter.hasNext()) { Property next = (Property) propIter.next(); propMap.put(next.getPropertyName(), next); } return propMap; } public ArrayList getNoAccessTypePropertiesForClass(JavaClass cls, TypeInfo info) { ArrayList list = new ArrayList(); if (cls == null) { return list; } ArrayList fieldProperties = getFieldPropertiesForClass(cls, info, false); ArrayList methodProperties = getPropertyPropertiesForClass(cls, info, false); // Iterate over the field and method properties. If ANYTHING contains an // annotation and // doesn't appear in the other list, add it to the final list for (int i = 0; i < fieldProperties.size(); i++) { Property next = (Property) fieldProperties.get(i); JavaHasAnnotations elem = next.getElement(); if (!hasJAXBAnnotations(elem)) { next.setTransient(true); } list.add(next); } for (int i = 0; i < methodProperties.size(); i++) { Property next = (Property) methodProperties.get(i); JavaHasAnnotations elem = next.getElement(); if (!hasJAXBAnnotations(elem)) { next.setTransient(true); } list.add(next); } return list; } /** * Use name, namespace and type information to setup a user-defined schema * type. This method will typically be called when processing an * * @XmlSchemaType(s) annotation or xml-schema-type(s) metadata. * * @param name * @param namespace * @param jClassQualifiedName */ public void processSchemaType(String name, String namespace, String jClassQualifiedName) { this.userDefinedSchemaTypes.put(jClassQualifiedName, new QName(namespace, name)); } public void processSchemaType(XmlSchemaType type) { JavaClass jClass = helper.getJavaClass(type.type()); if (jClass == null) { return; } processSchemaType(type.name(), type.namespace(), jClass.getQualifiedName()); } public void addEnumTypeInfo(JavaClass javaClass, EnumTypeInfo info) { if (javaClass == null) { return; } info.setClassName(javaClass.getQualifiedName()); Class restrictionClass = String.class; if (helper.isAnnotationPresent(javaClass, XmlEnum.class)) { XmlEnum xmlEnum = (XmlEnum) helper.getAnnotation(javaClass, XmlEnum.class); restrictionClass = xmlEnum.value(); } QName restrictionBase = getSchemaTypeFor(helper.getJavaClass(restrictionClass)); info.setRestrictionBase(restrictionBase); for (Iterator<JavaField> fieldIt = javaClass.getDeclaredFields().iterator(); fieldIt.hasNext();) { JavaField field = fieldIt.next(); if (field.isEnumConstant()) { String enumValue = field.getName(); if (helper.isAnnotationPresent(field, XmlEnumValue.class)) { enumValue = ((XmlEnumValue) helper.getAnnotation(field, XmlEnumValue.class)).value(); } info.addJavaFieldToXmlEnumValuePair(field.getName(), enumValue); } } } private String decapitalize(String javaName) { // return Introspector.decapitalize(name); Spec Compliant // RI compliancy char[] name = javaName.toCharArray(); int i = 0; while (i < name.length && Character.isUpperCase(name[i])) { i++; } if (i > 0) { name[0] = Character.toLowerCase(name[0]); for (int j = 1; j < i - 1; j++) { name[j] = Character.toLowerCase(name[j]); } return new String(name); } else { return javaName; } } public String getSchemaTypeNameForClassName(String className) { String typeName = EMPTY_STRING; if (className.indexOf('$') != -1) { typeName = decapitalize(className.substring(className.lastIndexOf('$') + 1)); } else { typeName = decapitalize(className.substring(className.lastIndexOf('.') + 1)); } // now capitalize any characters that occur after a "break" boolean inBreak = false; StringBuffer toReturn = new StringBuffer(typeName.length()); for (int i = 0; i < typeName.length(); i++) { char next = typeName.charAt(i); if (Character.isDigit(next)) { if (!inBreak) { inBreak = true; } toReturn.append(next); } else { if (inBreak) { toReturn.append(Character.toUpperCase(next)); } else { toReturn.append(next); } } } return toReturn.toString(); } public QName getSchemaTypeOrNullFor(JavaClass javaClass) { if (javaClass == null) { return null; } // check user defined types first QName schemaType = (QName) userDefinedSchemaTypes.get(javaClass.getQualifiedName()); if (schemaType == null) { schemaType = (QName) helper.getXMLToJavaTypeMap().get(javaClass.getRawName()); } return schemaType; } public QName getSchemaTypeFor(JavaClass javaClass) { QName schemaType = getSchemaTypeOrNullFor(javaClass); if (schemaType == null) { return XMLConstants.ANY_SIMPLE_TYPE_QNAME; } return schemaType; } public boolean isCollectionType(Property field) { return isCollectionType(field.getType()); } public boolean isCollectionType(JavaClass type) { if (helper.getJavaClass(java.util.Collection.class).isAssignableFrom(type) || helper.getJavaClass(java.util.List.class).isAssignableFrom(type) || helper.getJavaClass(java.util.Set.class).isAssignableFrom(type)) { return true; } return false; } public NamespaceInfo processNamespaceInformation(XmlSchema xmlSchema) { NamespaceInfo info = new NamespaceInfo(); info.setNamespaceResolver(new NamespaceResolver()); String packageNamespace = null; if (xmlSchema != null) { String namespaceMapping = xmlSchema.namespace(); if (!(namespaceMapping.equals(EMPTY_STRING) || namespaceMapping.equals(XMLProcessor.DEFAULT))) { packageNamespace = namespaceMapping; } else if (namespaceMapping.equals(XMLProcessor.DEFAULT)) { packageNamespace = this.defaultTargetNamespace; } info.setNamespace(packageNamespace); XmlNs[] xmlns = xmlSchema.xmlns(); for (int i = 0; i < xmlns.length; i++) { XmlNs next = xmlns[i]; info.getNamespaceResolver().put(next.prefix(), next.namespaceURI()); } info.setAttributeFormQualified(xmlSchema.attributeFormDefault() == XmlNsForm.QUALIFIED); info.setElementFormQualified(xmlSchema.elementFormDefault() == XmlNsForm.QUALIFIED); // reflectively load XmlSchema class to avoid dependency try { Method locationMethod = PrivilegedAccessHelper.getDeclaredMethod(XmlSchema.class, "location", new Class[] {}); String location = (String) PrivilegedAccessHelper.invokeMethod(locationMethod, xmlSchema, new Object[] {}); if (location != null) { if (location.equals("##generate")) { location = null; } else if (location.equals(EMPTY_STRING)) { location = null; } } info.setLocation(location); } catch (Exception ex) { } } else { info.setNamespace(defaultTargetNamespace); } if (!info.isElementFormQualified() || info.isAttributeFormQualified()) { isDefaultNamespaceAllowed = false; } return info; } public HashMap<String, TypeInfo> getTypeInfo() { return typeInfo; } public ArrayList<JavaClass> getTypeInfoClasses() { return typeInfoClasses; } public HashMap<String, QName> getUserDefinedSchemaTypes() { return userDefinedSchemaTypes; } public NamespaceResolver getNamespaceResolver() { return namespaceResolver; } public String getSchemaTypeNameFor(JavaClass javaClass, XmlType xmlType) { String typeName = EMPTY_STRING; if (javaClass == null) { return typeName; } if (helper.isAnnotationPresent(javaClass, XmlType.class)) { // Figure out what kind of type we have // figure out type name XmlType typeAnnotation = (XmlType) helper.getAnnotation(javaClass, XmlType.class); typeName = typeAnnotation.name(); if (typeName.equals("#default")) { typeName = getSchemaTypeNameForClassName(javaClass.getName()); } } else { typeName = getSchemaTypeNameForClassName(javaClass.getName()); } return typeName; } public QName getQNameForProperty(String defaultName, JavaHasAnnotations element, NamespaceInfo namespaceInfo, String uri) { String name = XMLProcessor.DEFAULT; String namespace = XMLProcessor.DEFAULT; QName qName = null; if (helper.isAnnotationPresent(element, XmlAttribute.class)) { XmlAttribute xmlAttribute = (XmlAttribute) helper.getAnnotation(element, XmlAttribute.class); name = xmlAttribute.name(); namespace = xmlAttribute.namespace(); if (name.equals(XMLProcessor.DEFAULT)) { name = defaultName; } if (!namespace.equals(XMLProcessor.DEFAULT)) { qName = new QName(namespace, name); isDefaultNamespaceAllowed = false; } else { if (namespaceInfo.isAttributeFormQualified()) { qName = new QName(uri, name); } else { qName = new QName(name); } } } else { if (helper.isAnnotationPresent(element, XmlElement.class)) { XmlElement xmlElement = (XmlElement) helper.getAnnotation(element, XmlElement.class); name = xmlElement.name(); namespace = xmlElement.namespace(); } if (name.equals(XMLProcessor.DEFAULT)) { name = defaultName; } if (!namespace.equals(XMLProcessor.DEFAULT)) { qName = new QName(namespace, name); if (namespace.equals(XMLConstants.EMPTY_STRING)) { isDefaultNamespaceAllowed = false; } } else { if (namespaceInfo.isElementFormQualified()) { qName = new QName(uri, name); } else { qName = new QName(name); } } } return qName; } public HashMap<String, NamespaceInfo> getPackageToNamespaceMappings() { return packageToNamespaceMappings; } /** * Add a package name/NamespaceInfo entry to the map. This method will * lazy-load the map if necessary. * * @return */ public void addPackageToNamespaceMapping(String packageName, NamespaceInfo nsInfo) { if (packageToNamespaceMappings == null) { packageToNamespaceMappings = new HashMap<String, NamespaceInfo>(); } packageToNamespaceMappings.put(packageName, nsInfo); } public NamespaceInfo getNamespaceInfoForPackage(JavaClass javaClass) { String packageName = javaClass.getPackageName(); NamespaceInfo packageNamespace = packageToNamespaceMappings.get(packageName); if (packageNamespace == null) { packageNamespace = getNamespaceInfoForPackage(javaClass.getPackage(), packageName); } return packageNamespace; } public NamespaceInfo getNamespaceInfoForPackage(JavaPackage pack, String packageName) { NamespaceInfo packageNamespace = packageToNamespaceMappings.get(packageName); if (packageNamespace == null) { XmlSchema xmlSchema = (XmlSchema) helper.getAnnotation(pack, XmlSchema.class); packageNamespace = processNamespaceInformation(xmlSchema); // if it's still null, generate based on package name if (packageNamespace.getNamespace() == null) { packageNamespace.setNamespace(EMPTY_STRING); } if (helper.isAnnotationPresent(pack, XmlAccessorType.class)) { XmlAccessorType xmlAccessorType = (XmlAccessorType) helper.getAnnotation(pack, XmlAccessorType.class); packageNamespace.setAccessType(XmlAccessType.fromValue(xmlAccessorType.value().name())); } if (helper.isAnnotationPresent(pack, XmlAccessorOrder.class)) { XmlAccessorOrder xmlAccessorOrder = (XmlAccessorOrder) helper.getAnnotation(pack, XmlAccessorOrder.class); packageNamespace.setAccessOrder(XmlAccessOrder.fromValue(xmlAccessorOrder.value().name())); } packageToNamespaceMappings.put(packageName, packageNamespace); } return packageNamespace; } private void checkForCallbackMethods() { for (JavaClass next : typeInfoClasses) { if (next == null) { continue; } JavaClass unmarshallerCls = helper.getJavaClass(Unmarshaller.class); JavaClass marshallerCls = helper.getJavaClass(Marshaller.class); JavaClass objectCls = helper.getJavaClass(Object.class); JavaClass[] unmarshalParams = new JavaClass[] { unmarshallerCls, objectCls }; JavaClass[] marshalParams = new JavaClass[] { marshallerCls }; UnmarshalCallback unmarshalCallback = null; MarshalCallback marshalCallback = null; // look for before unmarshal callback if (next.getMethod("beforeUnmarshal", unmarshalParams) != null) { unmarshalCallback = new UnmarshalCallback(); unmarshalCallback.setDomainClassName(next.getQualifiedName()); unmarshalCallback.setHasBeforeUnmarshalCallback(); } // look for after unmarshal callback if (next.getMethod("afterUnmarshal", unmarshalParams) != null) { if (unmarshalCallback == null) { unmarshalCallback = new UnmarshalCallback(); unmarshalCallback.setDomainClassName(next.getQualifiedName()); } unmarshalCallback.setHasAfterUnmarshalCallback(); } // if before/after unmarshal callback was found, add the callback to // the list if (unmarshalCallback != null) { if (this.unmarshalCallbacks == null) { this.unmarshalCallbacks = new HashMap<String, UnmarshalCallback>(); } unmarshalCallbacks.put(next.getQualifiedName(), unmarshalCallback); } // look for before marshal callback if (next.getMethod("beforeMarshal", marshalParams) != null) { marshalCallback = new MarshalCallback(); marshalCallback.setDomainClassName(next.getQualifiedName()); marshalCallback.setHasBeforeMarshalCallback(); } // look for after marshal callback if (next.getMethod("afterMarshal", marshalParams) != null) { if (marshalCallback == null) { marshalCallback = new MarshalCallback(); marshalCallback.setDomainClassName(next.getQualifiedName()); } marshalCallback.setHasAfterMarshalCallback(); } // if before/after marshal callback was found, add the callback to // the list if (marshalCallback != null) { if (this.marshalCallbacks == null) { this.marshalCallbacks = new HashMap<String, MarshalCallback>(); } marshalCallbacks.put(next.getQualifiedName(), marshalCallback); } } } public HashMap<String, MarshalCallback> getMarshalCallbacks() { return this.marshalCallbacks; } public HashMap<String, UnmarshalCallback> getUnmarshalCallbacks() { return this.unmarshalCallbacks; } public JavaClass[] processObjectFactory(JavaClass objectFactoryClass, ArrayList<JavaClass> classes) { // if there is an xml-registry from XML for this JavaClass, create a map // of method names to XmlElementDecl objects to simplify processing // later on in this method Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl> elemDecls = new HashMap<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl>(); org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry xmlReg = xmlRegistries.get(objectFactoryClass.getQualifiedName()); if (xmlReg != null) { // process xml-element-decl entries for (org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl xmlElementDecl : xmlReg.getXmlElementDecl()) { // key each element-decl on method name elemDecls.put(xmlElementDecl.getJavaMethod(), xmlElementDecl); } } Collection methods = objectFactoryClass.getDeclaredMethods(); Iterator methodsIter = methods.iterator(); NamespaceInfo namespaceInfo = getNamespaceInfoForPackage(objectFactoryClass); while (methodsIter.hasNext()) { JavaMethod next = (JavaMethod) methodsIter.next(); if (next.getName().startsWith(CREATE)) { JavaClass type = next.getReturnType(); if (JAVAX_XML_BIND_JAXBELEMENT.equals(type.getName())) { Object[] actutalTypeArguments = next.getReturnType().getActualTypeArguments().toArray(); if(actutalTypeArguments.length == 0) { type = helper.getJavaClass(Object.class); } else { type = (JavaClass) next.getReturnType().getActualTypeArguments().toArray()[0]; } } else { this.factoryMethods.put(next.getReturnType().getRawName(), next); } // if there's an XmlElementDecl for this method from XML, use it // - otherwise look for an annotation org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl xmlEltDecl = elemDecls.get(next.getName()); if (xmlEltDecl != null || helper.isAnnotationPresent(next, XmlElementDecl.class)) { QName qname; QName substitutionHead = null; String url; String localName; String defaultValue = null; Class scopeClass = javax.xml.bind.annotation.XmlElementDecl.GLOBAL.class; if (xmlEltDecl != null) { url = xmlEltDecl.getNamespace(); localName = xmlEltDecl.getName(); String scopeClassName = xmlEltDecl.getScope(); if (!scopeClassName.equals(ELEMENT_DECL_GLOBAL)) { JavaClass jScopeClass = helper.getJavaClass(scopeClassName); if (jScopeClass != null) { scopeClass = helper.getClassForJavaClass(jScopeClass); if (scopeClass == null) { scopeClass = javax.xml.bind.annotation.XmlElementDecl.GLOBAL.class; } } } if (!xmlEltDecl.getSubstitutionHeadName().equals(EMPTY_STRING)) { String subHeadLocal = xmlEltDecl.getSubstitutionHeadName(); String subHeadNamespace = xmlEltDecl.getSubstitutionHeadNamespace(); if (subHeadNamespace.equals(XMLProcessor.DEFAULT)) { subHeadNamespace = namespaceInfo.getNamespace(); } substitutionHead = new QName(subHeadNamespace, subHeadLocal); } if (!(xmlEltDecl.getDefaultValue().length() == 1 && xmlEltDecl.getDefaultValue().startsWith(ELEMENT_DECL_DEFAULT))) { defaultValue = xmlEltDecl.getDefaultValue(); } } else { // there was no xml-element-decl for this method in XML, // so use the annotation XmlElementDecl elementDecl = (XmlElementDecl) helper.getAnnotation(next, XmlElementDecl.class); url = elementDecl.namespace(); localName = elementDecl.name(); scopeClass = elementDecl.scope(); if (!elementDecl.substitutionHeadName().equals(EMPTY_STRING)) { String subHeadLocal = elementDecl.substitutionHeadName(); String subHeadNamespace = elementDecl.substitutionHeadNamespace(); if (subHeadNamespace.equals(XMLProcessor.DEFAULT)) { subHeadNamespace = namespaceInfo.getNamespace(); } substitutionHead = new QName(subHeadNamespace, subHeadLocal); } if (!(elementDecl.defaultValue().length() == 1 && elementDecl.defaultValue().startsWith(ELEMENT_DECL_DEFAULT))) { defaultValue = elementDecl.defaultValue(); } } if (XMLProcessor.DEFAULT.equals(url)) { url = namespaceInfo.getNamespace(); } qname = new QName(url, localName); boolean isList = false; if (JAVA_UTIL_LIST.equals(type.getName())) { isList = true; if (type.hasActualTypeArguments()) { type = (JavaClass) type.getActualTypeArguments().toArray()[0]; } } ElementDeclaration declaration = new ElementDeclaration(qname, type, type.getQualifiedName(), isList, scopeClass); if (substitutionHead != null) { declaration.setSubstitutionHead(substitutionHead); } if (defaultValue != null) { declaration.setDefaultValue(defaultValue); } if (helper.isAnnotationPresent(next, XmlJavaTypeAdapter.class)) { XmlJavaTypeAdapter typeAdapter = (XmlJavaTypeAdapter) helper.getAnnotation(next, XmlJavaTypeAdapter.class); Class typeAdapterClass = typeAdapter.value(); declaration.setJavaTypeAdapterClass(typeAdapterClass); Class declJavaType = CompilerHelper.getTypeFromAdapterClass(typeAdapterClass); declaration.setJavaType(helper.getJavaClass(declJavaType)); declaration.setAdaptedJavaType(type); } HashMap<QName, ElementDeclaration> elements = getElementDeclarationsForScope(scopeClass.getName()); if (elements == null) { elements = new HashMap<QName, ElementDeclaration>(); this.elementDeclarations.put(scopeClass.getName(), elements); } elements.put(qname, declaration); } if (!helper.isBuiltInJavaType(type) && !helper.classExistsInArray(type, classes)) { classes.add(type); } } } if (classes.size() > 0) { return classes.toArray(new JavaClass[classes.size()]); } else { return new JavaClass[0]; } } /** * Lazy load and return the map of global elements. * * @return */ public HashMap<QName, ElementDeclaration> getGlobalElements() { return this.elementDeclarations.get(XmlElementDecl.GLOBAL.class.getName()); } public void updateGlobalElements(JavaClass[] classesToProcess) { // Once all the global element declarations have been created, make sure // that any ones that have // a substitution head set are added to the list of substitutable // elements on the declaration for that // head. // Look for XmlRootElement declarations for (JavaClass javaClass : classesToProcess) { TypeInfo info = typeInfo.get(javaClass.getQualifiedName()); if (info == null) { continue; } if (!info.isTransient() && info.isSetXmlRootElement()) { org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = info.getXmlRootElement(); NamespaceInfo namespaceInfo; namespaceInfo = getNamespaceInfoForPackage(javaClass); String elementName = xmlRE.getName(); if (elementName.equals(XMLProcessor.DEFAULT) || elementName.equals(EMPTY_STRING)) { if (javaClass.getName().indexOf("$") != -1) { elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf('$') + 1)); } else { elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf('.') + 1)); } // TCK Compliancy if (elementName.length() >= 3) { int idx = elementName.length() - 1; char ch = elementName.charAt(idx - 1); if (Character.isDigit(ch)) { char lastCh = Character.toUpperCase(elementName.charAt(idx)); elementName = elementName.substring(0, idx) + lastCh; } } } String rootNamespace = xmlRE.getNamespace(); QName rootElemName = null; if (rootNamespace.equals(XMLProcessor.DEFAULT)) { if (namespaceInfo == null) { rootElemName = new QName(elementName); } else { String rootNS = namespaceInfo.getNamespace(); rootElemName = new QName(rootNS, elementName); if (rootNS.equals(XMLConstants.EMPTY_STRING)) { isDefaultNamespaceAllowed = false; } } } else { rootElemName = new QName(rootNamespace, elementName); if (rootNamespace.equals(XMLConstants.EMPTY_STRING)) { isDefaultNamespaceAllowed = false; } } ElementDeclaration declaration = new ElementDeclaration(rootElemName, javaClass, javaClass.getQualifiedName(), false); declaration.setIsXmlRootElement(true); this.getGlobalElements().put(rootElemName, declaration); this.xmlRootElements.put(javaClass.getQualifiedName(), declaration); } } Iterator<QName> elementQnames = this.getGlobalElements().keySet().iterator(); while (elementQnames.hasNext()) { QName next = elementQnames.next(); ElementDeclaration nextDeclaration = this.getGlobalElements().get(next); QName substitutionHead = nextDeclaration.getSubstitutionHead(); while (substitutionHead != null) { ElementDeclaration rootDeclaration = this.getGlobalElements().get(substitutionHead); rootDeclaration.addSubstitutableElement(nextDeclaration); substitutionHead = rootDeclaration.getSubstitutionHead(); } } } private void addReferencedElement(Property property, ElementDeclaration referencedElement) { property.addReferencedElement(referencedElement); if (referencedElement.getSubstitutableElements() != null && referencedElement.getSubstitutableElements().size() > 0) { for (ElementDeclaration substitutable : referencedElement.getSubstitutableElements()) { addReferencedElement(property, substitutable); } } } /** * Returns true if the field or method passed in is annotated with JAXB * annotations. */ private boolean hasJAXBAnnotations(JavaHasAnnotations elem) { if (helper.isAnnotationPresent(elem, XmlElement.class) || helper.isAnnotationPresent(elem, XmlAttribute.class) || helper.isAnnotationPresent(elem, XmlAnyElement.class) || helper.isAnnotationPresent(elem, XmlAnyAttribute.class) || helper.isAnnotationPresent(elem, XmlValue.class) || helper.isAnnotationPresent(elem, XmlElements.class) || helper.isAnnotationPresent(elem, XmlElementRef.class) || helper.isAnnotationPresent(elem, XmlElementRefs.class) || helper.isAnnotationPresent(elem, XmlID.class) || helper.isAnnotationPresent(elem, XmlSchemaType.class) || helper.isAnnotationPresent(elem, XmlElementWrapper.class) || helper.isAnnotationPresent(elem, XmlList.class) || helper.isAnnotationPresent(elem, XmlMimeType.class) || helper.isAnnotationPresent(elem, XmlIDREF.class) || helper.isAnnotationPresent(elem, XmlPath.class) || helper.isAnnotationPresent(elem, XmlPaths.class) || helper.isAnnotationPresent(elem, XmlInverseReference.class) || helper.isAnnotationPresent(elem, XmlReadOnly.class) || helper.isAnnotationPresent(elem, XmlWriteOnly.class) || helper.isAnnotationPresent(elem, XmlCDATA.class) || helper.isAnnotationPresent(elem, XmlAccessMethods.class) || helper.isAnnotationPresent(elem, XmlNullPolicy.class)) { return true; } return false; } private void validateElementIsInPropOrder(TypeInfo info, String name) { if (info.isTransient()) { return; } // If a property is marked with XMLElement, XMLElements, XMLElementRef // or XMLElementRefs // and propOrder is not empty then it must be in the proporder list String[] propOrder = info.getPropOrder(); if (propOrder.length > 0) { if (propOrder.length == 1 && propOrder[0].equals(EMPTY_STRING)) { return; } List<String> propOrderList = Arrays.asList(info.getPropOrder()); if (!propOrderList.contains(name)) { throw JAXBException.missingPropertyInPropOrder(name); } } } private void validatePropOrderForInfo(TypeInfo info) { if (info.isTransient()) { return; } // Ensure that all properties in the propOrder list actually exist String[] propOrder = info.getPropOrder(); int propOrderLength = propOrder.length; if (propOrderLength > 0) { for (int i = 1; i < propOrderLength; i++) { String nextPropName = propOrder[i]; if (!nextPropName.equals(EMPTY_STRING) && !info.getPropertyNames().contains(nextPropName)) { throw JAXBException.nonExistentPropertyInPropOrder(nextPropName); } } } } private void validateXmlValueFieldOrProperty(JavaClass cls, Property property) { JavaClass ptype = property.getActualType(); String propName = property.getPropertyName(); JavaClass parent = cls.getSuperclass(); while (parent != null && !(parent.getQualifiedName().equals(JAVA_LANG_OBJECT))) { TypeInfo parentTypeInfo = typeInfo.get(parent.getQualifiedName()); if (parentTypeInfo != null || shouldGenerateTypeInfo(parent)) { throw JAXBException.propertyOrFieldCannotBeXmlValue(propName); } parent = parent.getSuperclass(); } QName schemaQName = getSchemaTypeOrNullFor(ptype); if (schemaQName == null) { TypeInfo refInfo = typeInfo.get(ptype.getQualifiedName()); if (refInfo != null) { if (!refInfo.isPostBuilt()) { postBuildTypeInfo(new JavaClass[] { ptype }); } } else if (shouldGenerateTypeInfo(ptype)) { JavaClass[] jClasses = new JavaClass[] { ptype }; buildNewTypeInfo(jClasses); refInfo = typeInfo.get(ptype.getQualifiedName()); } if (refInfo != null && !refInfo.isEnumerationType() && refInfo.getXmlValueProperty() == null) { throw JAXBException.invalidTypeForXmlValueField(propName); } } } public boolean isMapType(JavaClass type) { return helper.getJavaClass(java.util.Map.class).isAssignableFrom(type); } private Class generateWrapperForMapClass(JavaClass mapClass, JavaClass keyClass, JavaClass valueClass, TypeMappingInfo typeMappingInfo) { String packageName = "jaxb.dev.java.net"; NamespaceResolver combinedNamespaceResolver = new NamespaceResolver(); if (!helper.isBuiltInJavaType(keyClass)) { String keyPackageName = keyClass.getPackageName(); packageName = packageName + "." + keyPackageName; NamespaceInfo keyNamespaceInfo = getNamespaceInfoForPackage(keyClass); if (keyNamespaceInfo != null) { java.util.Vector<Namespace> namespaces = keyNamespaceInfo.getNamespaceResolver().getNamespaces(); for (Namespace n : namespaces) { combinedNamespaceResolver.put(n.getPrefix(), n.getNamespaceURI()); } } } if (!helper.isBuiltInJavaType(valueClass)) { String valuePackageName = valueClass.getPackageName(); packageName = packageName + "." + valuePackageName; NamespaceInfo valueNamespaceInfo = getNamespaceInfoForPackage(valueClass); if (valueNamespaceInfo != null) { java.util.Vector<Namespace> namespaces = valueNamespaceInfo.getNamespaceResolver().getNamespaces(); for (Namespace n : namespaces) { combinedNamespaceResolver.put(n.getPrefix(), n.getNamespaceURI()); } } } String namespace = this.defaultTargetNamespace; if (namespace == null) { namespace = EMPTY_STRING; } NamespaceInfo namespaceInfo = packageToNamespaceMappings.get(mapClass.getPackageName()); if (namespaceInfo == null) { namespaceInfo = getPackageToNamespaceMappings().get(packageName); } else { if (namespaceInfo.getNamespace() != null) { namespace = namespaceInfo.getNamespace(); } getPackageToNamespaceMappings().put(packageName, namespaceInfo); } if (namespaceInfo == null) { namespaceInfo = new NamespaceInfo(); namespaceInfo.setNamespace(namespace); namespaceInfo.setNamespaceResolver(combinedNamespaceResolver); getPackageToNamespaceMappings().put(packageName, namespaceInfo); } int beginIndex = keyClass.getName().lastIndexOf(".") + 1; String keyName = keyClass.getName().substring(beginIndex); int dollarIndex = keyName.indexOf('$'); if (dollarIndex > -1) { keyName = keyName.substring(dollarIndex + 1); } beginIndex = valueClass.getName().lastIndexOf(".") + 1; String valueName = valueClass.getName().substring(beginIndex); dollarIndex = valueName.indexOf('$'); if (dollarIndex > -1) { valueName = valueName.substring(dollarIndex + 1); } String collectionClassShortName = mapClass.getRawName().substring(mapClass.getRawName().lastIndexOf('.') + 1); String suggestedClassName = keyName + valueName + collectionClassShortName; String qualifiedClassName = packageName + "." + suggestedClassName; qualifiedClassName = getNextAvailableClassName(qualifiedClassName); String qualifiedInternalClassName = qualifiedClassName.replace('.', '/'); String internalKeyName = keyClass.getQualifiedName().replace('.', '/'); String internalValueName = valueClass.getQualifiedName().replace('.', '/'); Type mapType = Type.getType("L" + mapClass.getRawName().replace('.', '/') + ";"); ClassWriter cw = new ClassWriter(false); CodeVisitor cv; cw.visit(Constants.V1_5, Constants.ACC_PUBLIC + Constants.ACC_SUPER, qualifiedInternalClassName, "org/eclipse/persistence/internal/jaxb/many/MapValue", null, "StringEmployeeMap.java"); // FIELD ATTRIBUTES RuntimeVisibleAnnotations fieldAttrs1 = new RuntimeVisibleAnnotations(); if (typeMappingInfo != null) { java.lang.annotation.Annotation[] annotations = typeMappingInfo.getAnnotations(); if (annotations != null) { for (int i = 0; i < annotations.length; i++) { java.lang.annotation.Annotation nextAnnotation = annotations[i]; if (nextAnnotation != null && !(nextAnnotation instanceof XmlElement) && !(nextAnnotation instanceof XmlJavaTypeAdapter)) { String annotationClassName = nextAnnotation.annotationType().getName(); Annotation fieldAttrs1ann0 = new Annotation("L" + annotationClassName.replace('.', '/') + ";"); fieldAttrs1.annotations.add(fieldAttrs1ann0); for (Method next : nextAnnotation.annotationType().getDeclaredMethods()) { try { Object nextValue = next.invoke(nextAnnotation, new Object[] {}); if (nextValue instanceof Class) { Type nextType = Type.getType("L" + ((Class) nextValue).getName().replace('.', '/') + ";"); nextValue = nextType; } fieldAttrs1ann0.add(next.getName(), nextValue); } catch (InvocationTargetException ex) { // ignore the invocation target exception here. } catch (IllegalAccessException ex) { } } } } } } // FIELD ATTRIBUTES SignatureAttribute fieldAttrs2 = new SignatureAttribute("L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;"); fieldAttrs1.next = fieldAttrs2; cw.visitField(Constants.ACC_PUBLIC, "entry", "L" + mapType.getInternalName() + ";", null, fieldAttrs1); cv = cw.visitMethod(Constants.ACC_PUBLIC, "<init>", "()V", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitMethodInsn(Constants.INVOKESPECIAL, "org/eclipse/persistence/internal/jaxb/many/MapValue", "<init>", "()V"); cv.visitInsn(Constants.RETURN); cv.visitMaxs(1, 1); // METHOD ATTRIBUTES RuntimeVisibleAnnotations methodAttrs1 = new RuntimeVisibleAnnotations(); Annotation methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;"); methodAttrs1.annotations.add(methodAttrs1ann0); SignatureAttribute methodAttrs2 = new SignatureAttribute("(L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;)V"); methodAttrs1.next = methodAttrs2; cv = cw.visitMethod(Constants.ACC_PUBLIC, "setItem", "(L" + mapType.getInternalName() + ";)V", null, methodAttrs1); Label l0 = new Label(); cv.visitLabel(l0); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitVarInsn(Constants.ALOAD, 1); cv.visitFieldInsn(Constants.PUTFIELD, qualifiedInternalClassName, "entry", "L" + mapType.getInternalName() + ";"); cv.visitInsn(Constants.RETURN); Label l1 = new Label(); cv.visitLabel(l1); // CODE ATTRIBUTE LocalVariableTypeTableAttribute cvAttr = new LocalVariableTypeTableAttribute(); cv.visitAttribute(cvAttr); cv.visitMaxs(2, 2); // METHOD ATTRIBUTES methodAttrs1 = new RuntimeVisibleAnnotations(); methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;"); methodAttrs1.annotations.add(methodAttrs1ann0); methodAttrs2 = new SignatureAttribute("()L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;"); methodAttrs1.next = methodAttrs2; cv = cw.visitMethod(Constants.ACC_PUBLIC, "getItem", "()L" + mapType.getInternalName() + ";", null, methodAttrs1); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitFieldInsn(Constants.GETFIELD, qualifiedInternalClassName, "entry", "L" + mapType.getInternalName() + ";"); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "getItem", "()Ljava/lang/Object;", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "getItem", "()L" + mapType.getInternalName() + ";"); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "setItem", "(Ljava/lang/Object;)V", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitVarInsn(Constants.ALOAD, 1); cv.visitTypeInsn(Constants.CHECKCAST, mapType.getInternalName()); cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "setItem", "(L" + mapType.getInternalName() + ";)V"); cv.visitInsn(Constants.RETURN); cv.visitMaxs(2, 2); // CLASS ATTRIBUTE RuntimeVisibleAnnotations annotationsAttr = new RuntimeVisibleAnnotations(); Annotation attrann0 = new Annotation("Ljavax/xml/bind/annotation/XmlType;"); attrann0.add("namespace", namespace); annotationsAttr.annotations.add(attrann0); cw.visitAttribute(annotationsAttr); SignatureAttribute attr = new SignatureAttribute("Lorg/eclipse/persistence/internal/jaxb/many/MapValue<L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;>;"); cw.visitAttribute(attr); cw.visitEnd(); byte[] classBytes = cw.toByteArray(); return generateClassFromBytes(qualifiedClassName, classBytes); } private Class generateWrapperForArrayClass(JavaClass arrayClass, TypeMappingInfo typeMappingInfo, Class xmlElementType) { JavaClass componentClass = null; if (typeMappingInfo != null && xmlElementType != null) { componentClass = helper.getJavaClass(xmlElementType); } else { componentClass = arrayClass.getComponentType(); } if (componentClass.isArray()) { Class nestedArrayClass = generateWrapperForArrayClass(componentClass, typeMappingInfo, xmlElementType); arrayClassesToGeneratedClasses.put(componentClass.getName(), nestedArrayClass); return generateArrayValue(arrayClass, componentClass, helper.getJavaClass(nestedArrayClass), typeMappingInfo); } else { return generateArrayValue(arrayClass, componentClass, componentClass, typeMappingInfo); } } private Class generateArrayValue(JavaClass arrayClass, JavaClass componentClass, JavaClass nestedClass, TypeMappingInfo typeMappingInfo) { String packageName; String qualifiedClassName; if (componentClass.isArray()) { packageName = componentClass.getPackageName(); qualifiedClassName = nestedClass.getQualifiedName() + ARRAY_CLASS_NAME_SUFFIX; } else { if (componentClass.isPrimitive()) { packageName = ARRAY_PACKAGE_NAME; qualifiedClassName = packageName + "." + componentClass.getName() + ARRAY_CLASS_NAME_SUFFIX; } else { packageName = ARRAY_PACKAGE_NAME + "." + componentClass.getPackageName(); if (componentClass.isMemberClass()) { qualifiedClassName = componentClass.getName(); qualifiedClassName = qualifiedClassName.substring(qualifiedClassName.indexOf('$') + 1); qualifiedClassName = ARRAY_PACKAGE_NAME + "." + componentClass.getPackageName() + "." + qualifiedClassName + ARRAY_CLASS_NAME_SUFFIX; } else { qualifiedClassName = ARRAY_PACKAGE_NAME + "." + componentClass.getQualifiedName() + ARRAY_CLASS_NAME_SUFFIX; } } if (componentClass.isPrimitive() || helper.isBuiltInJavaType(componentClass)) { NamespaceInfo namespaceInfo = getPackageToNamespaceMappings().get(packageName); if (namespaceInfo == null) { namespaceInfo = new NamespaceInfo(); namespaceInfo.setNamespace(ARRAY_NAMESPACE); namespaceInfo.setNamespaceResolver(new NamespaceResolver()); getPackageToNamespaceMappings().put(packageName, namespaceInfo); } } else { NamespaceInfo namespaceInfo = getNamespaceInfoForPackage(componentClass.getPackage(), componentClass.getPackageName()); getPackageToNamespaceMappings().put(packageName, namespaceInfo); } } String qualifiedInternalClassName = qualifiedClassName.replace('.', '/'); String superClassName; if (componentClass.isArray()) { superClassName = "org/eclipse/persistence/internal/jaxb/many/MultiDimensionalArrayValue"; } else { superClassName = "org/eclipse/persistence/internal/jaxb/many/ArrayValue"; } ClassWriter cw = new ClassWriter(false); cw.visit(Constants.V1_5, Constants.ACC_PUBLIC + Constants.ACC_SUPER, qualifiedInternalClassName, superClassName, null, null); CodeVisitor cv = cw.visitMethod(Constants.ACC_PUBLIC, "<init>", "()V", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitMethodInsn(Constants.INVOKESPECIAL, superClassName, "<init>", "()V"); cv.visitInsn(Constants.RETURN); cv.visitMaxs(1, 1); if (componentClass.isArray()) { cv = cw.visitMethod(Constants.ACC_PROTECTED, "adaptedClass", "()Ljava/lang/Class;", null, null); cv.visitLdcInsn(Type.getType("L" + nestedClass.getQualifiedName().replace('.', '/') + ";")); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); } cv = cw.visitMethod(Constants.ACC_PROTECTED, "componentClass", "()Ljava/lang/Class;", null, null); JavaClass baseComponentClass = getBaseComponentType(componentClass); if (baseComponentClass.isPrimitive()) { cv.visitFieldInsn(Constants.GETSTATIC, getObjectType(baseComponentClass).getQualifiedName().replace('.', '/'), "TYPE", "Ljava/lang/Class;"); } else { cv.visitLdcInsn(Type.getType("L" + baseComponentClass.getQualifiedName().replace('.', '/') + ";")); } cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); RuntimeVisibleAnnotations getAdaptedValueMethodAnnotations = new RuntimeVisibleAnnotations(); Annotation xmlElementAnnotation = new Annotation("Ljavax/xml/bind/annotation/XmlElement;"); xmlElementAnnotation.add("name", "item"); xmlElementAnnotation.add("type", Type.getType("L" + getObjectType(nestedClass).getName().replace('.', '/') + ";")); getAdaptedValueMethodAnnotations.annotations.add(xmlElementAnnotation); cv = cw.visitMethod(Constants.ACC_PUBLIC, "getAdaptedValue", "()Ljava/util/List;", null, getAdaptedValueMethodAnnotations); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitFieldInsn(Constants.GETFIELD, qualifiedInternalClassName, "adaptedValue", "Ljava/util/List;"); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); return generateClassFromBytes(qualifiedClassName, cw.toByteArray()); } private JavaClass getBaseComponentType(JavaClass javaClass) { JavaClass componentType = javaClass.getComponentType(); if (null == componentType) { return javaClass; } if (!componentType.isArray()) { return componentType; } return getBaseComponentType(componentType); } private JavaClass getObjectType(JavaClass javaClass) { if (javaClass.isPrimitive()) { String primitiveClassName = javaClass.getRawName(); Class primitiveClass = getPrimitiveClass(primitiveClassName); return helper.getJavaClass(getObjectClass(primitiveClass)); } return javaClass; } private Class generateCollectionValue(JavaClass collectionClass, TypeMappingInfo typeMappingInfo, Class xmlElementType) { JavaClass componentClass; if (typeMappingInfo != null && xmlElementType != null) { componentClass = helper.getJavaClass(xmlElementType); } else if (collectionClass.hasActualTypeArguments()) { componentClass = ((JavaClass) collectionClass.getActualTypeArguments().toArray()[0]); } else { componentClass = helper.getJavaClass(Object.class); } if (componentClass.isPrimitive()) { Class primitiveClass = getPrimitiveClass(componentClass.getRawName()); componentClass = helper.getJavaClass(getObjectClass(primitiveClass)); } NamespaceInfo namespaceInfo = packageToNamespaceMappings.get(collectionClass.getPackageName()); String namespace = EMPTY_STRING; if (this.defaultTargetNamespace != null) { namespace = this.defaultTargetNamespace; } NamespaceInfo componentNamespaceInfo = getNamespaceInfoForPackage(componentClass); String packageName = componentClass.getPackageName(); packageName = "jaxb.dev.java.net." + packageName; if (namespaceInfo == null) { namespaceInfo = getPackageToNamespaceMappings().get(packageName); } else { getPackageToNamespaceMappings().put(packageName, namespaceInfo); if (namespaceInfo.getNamespace() != null) { namespace = namespaceInfo.getNamespace(); } } if (namespaceInfo == null) { if (componentNamespaceInfo != null) { namespaceInfo = componentNamespaceInfo; } else { namespaceInfo = new NamespaceInfo(); namespaceInfo.setNamespaceResolver(new NamespaceResolver()); } getPackageToNamespaceMappings().put(packageName, namespaceInfo); } String name = componentClass.getName(); Type componentType = Type.getType("L" + componentClass.getName().replace('.', '/') + ";"); String componentTypeInternalName = null; if (name.equals("[B")) { name = "byteArray"; componentTypeInternalName = componentType.getInternalName(); } else if (name.equals("[Ljava.lang.Byte;")) { name = "ByteArray"; componentTypeInternalName = componentType.getInternalName() + ";"; } else { componentTypeInternalName = "L" + componentType.getInternalName() + ";"; } int beginIndex = name.lastIndexOf('.') + 1; name = name.substring(beginIndex); int dollarIndex = name.indexOf('$'); if (dollarIndex > -1) { name = name.substring(dollarIndex + 1); } String collectionClassRawName = collectionClass.getRawName(); String collectionClassShortName = collectionClassRawName.substring(collectionClassRawName.lastIndexOf('.') + 1); String suggestedClassName = collectionClassShortName + "Of" + name; String qualifiedClassName = packageName + "." + suggestedClassName; qualifiedClassName = getNextAvailableClassName(qualifiedClassName); String className = qualifiedClassName.substring(qualifiedClassName.lastIndexOf('.') + 1); Type collectionType = Type.getType("L" + collectionClassRawName.replace('.', '/') + ";"); String qualifiedInternalClassName = qualifiedClassName.replace('.', '/'); ClassWriter cw = new ClassWriter(false); CodeVisitor cv; cw.visit(Constants.V1_5, Constants.ACC_PUBLIC + Constants.ACC_SUPER, qualifiedInternalClassName, "org/eclipse/persistence/internal/jaxb/many/CollectionValue", null, className.replace('.', '/') + ".java"); // FIELD ATTRIBUTES RuntimeVisibleAnnotations fieldAttrs1 = new RuntimeVisibleAnnotations(); if (typeMappingInfo != null) { java.lang.annotation.Annotation[] annotations = getAnnotations(typeMappingInfo); if (annotations != null) { for (int i = 0; i < annotations.length; i++) { java.lang.annotation.Annotation nextAnnotation = annotations[i]; if (nextAnnotation != null && !(nextAnnotation instanceof XmlElement) && !(nextAnnotation instanceof XmlJavaTypeAdapter)) { String annotationClassName = nextAnnotation.annotationType().getName(); Annotation fieldAttrs1ann0 = new Annotation("L" + annotationClassName.replace('.', '/') + ";"); fieldAttrs1.annotations.add(fieldAttrs1ann0); for (Method next : nextAnnotation.annotationType().getDeclaredMethods()) { try { Object nextValue = next.invoke(nextAnnotation, new Object[] {}); if (nextValue instanceof Class) { Type nextType = Type.getType("L" + ((Class) nextValue).getName().replace('.', '/') + ";"); nextValue = nextType; } fieldAttrs1ann0.add(next.getName(), nextValue); } catch (InvocationTargetException ex) { // ignore the invocation target exception here. } catch (IllegalAccessException ex) { } } } } } } SignatureAttribute fieldAttrs2 = new SignatureAttribute("L" + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;"); fieldAttrs1.next = fieldAttrs2; cw.visitField(Constants.ACC_PUBLIC, "item", "L" + collectionType.getInternalName() + ";", null, fieldAttrs1); cv = cw.visitMethod(Constants.ACC_PUBLIC, "<init>", "()V", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitMethodInsn(Constants.INVOKESPECIAL, "org/eclipse/persistence/internal/jaxb/many/CollectionValue", "<init>", "()V"); cv.visitInsn(Constants.RETURN); cv.visitMaxs(1, 1); // METHOD ATTRIBUTES RuntimeVisibleAnnotations methodAttrs1 = new RuntimeVisibleAnnotations(); Annotation methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;"); methodAttrs1.annotations.add(methodAttrs1ann0); SignatureAttribute methodAttrs2 = new SignatureAttribute("(L" + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;)V"); methodAttrs1.next = methodAttrs2; cv = cw.visitMethod(Constants.ACC_PUBLIC, "setItem", "(L" + collectionType.getInternalName() + ";)V", null, methodAttrs1); Label l0 = new Label(); cv.visitLabel(l0); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitVarInsn(Constants.ALOAD, 1); cv.visitFieldInsn(Constants.PUTFIELD, qualifiedInternalClassName, "item", "L" + collectionType.getInternalName() + ";"); cv.visitInsn(Constants.RETURN); Label l1 = new Label(); cv.visitLabel(l1); // CODE ATTRIBUTE LocalVariableTypeTableAttribute cvAttr = new LocalVariableTypeTableAttribute(); cv.visitAttribute(cvAttr); cv.visitMaxs(2, 2); // METHOD ATTRIBUTES methodAttrs1 = new RuntimeVisibleAnnotations(); methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;"); methodAttrs1.annotations.add(methodAttrs1ann0); methodAttrs2 = new SignatureAttribute("()L" + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;"); methodAttrs1.next = methodAttrs2; cv = cw.visitMethod(Constants.ACC_PUBLIC, "getItem", "()L" + collectionType.getInternalName() + ";", null, methodAttrs1); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitFieldInsn(Constants.GETFIELD, qualifiedInternalClassName, "item", "L" + collectionType.getInternalName() + ";"); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "getItem", "()Ljava/lang/Object;", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "getItem", "()L" + collectionType.getInternalName() + ";"); cv.visitInsn(Constants.ARETURN); cv.visitMaxs(1, 1); cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "setItem", "(Ljava/lang/Object;)V", null, null); cv.visitVarInsn(Constants.ALOAD, 0); cv.visitVarInsn(Constants.ALOAD, 1); cv.visitTypeInsn(Constants.CHECKCAST, EMPTY_STRING + collectionType.getInternalName() + EMPTY_STRING); cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "setItem", "(L" + collectionType.getInternalName() + ";)V"); cv.visitInsn(Constants.RETURN); cv.visitMaxs(2, 2); // CLASS ATRIBUTE // CLASS ATTRIBUTE RuntimeVisibleAnnotations annotationsAttr = new RuntimeVisibleAnnotations(); Annotation attrann0 = new Annotation("Ljavax/xml/bind/annotation/XmlType;"); attrann0.add("namespace", namespace); annotationsAttr.annotations.add(attrann0); cw.visitAttribute(annotationsAttr); SignatureAttribute attr = new SignatureAttribute("Lorg/eclipse/persistence/internal/jaxb/many/CollectionValue<L" + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;>;"); cw.visitAttribute(attr); cw.visitEnd(); byte[] classBytes = cw.toByteArray(); return generateClassFromBytes(qualifiedClassName, classBytes); } private Class generateClassFromBytes(String className, byte[] classBytes) { JaxbClassLoader loader = (JaxbClassLoader) helper.getClassLoader(); Class generatedClass = loader.generateClass(className, classBytes); return generatedClass; } /** * Inner class used for ordering a list of Properties alphabetically by * property name. * */ class PropertyComparitor implements Comparator<Property> { public int compare(Property p1, Property p2) { return p1.getPropertyName().compareTo(p2.getPropertyName()); } } private String getNextAvailableClassName(String suggestedName) { int counter = 1; return getNextAvailableClassName(suggestedName, suggestedName, counter); } private String getNextAvailableClassName(String suggestedBaseName, String suggestedName, int counter) { Iterator<Class> iter = typeMappingInfoToGeneratedClasses.values().iterator(); while (iter.hasNext()) { Class nextClass = iter.next(); if (nextClass.getName().equals(suggestedName)) { counter = counter + 1; return getNextAvailableClassName(suggestedBaseName, suggestedBaseName + counter, counter); } } return suggestedName; } private Class getPrimitiveClass(String primitiveClassName) { return ConversionManager.getDefaultManager().convertClassNameToClass(primitiveClassName); } private Class getObjectClass(Class primitiveClass) { return ConversionManager.getDefaultManager().getObjectClass(primitiveClass); } public Map<java.lang.reflect.Type, Class> getCollectionClassesToGeneratedClasses() { return collectionClassesToGeneratedClasses; } public Map<String, Class> getArrayClassesToGeneratedClasses() { return arrayClassesToGeneratedClasses; } public Map<Class, java.lang.reflect.Type> getGeneratedClassesToCollectionClasses() { return generatedClassesToCollectionClasses; } public Map<Class, JavaClass> getGeneratedClassesToArrayClasses() { return generatedClassesToArrayClasses; } /** * Convenience method for returning all of the TypeInfo objects for a given * package name. * * This method is inefficient as we need to iterate over the entire typeinfo * map for each call. We should eventually store the TypeInfos in a Map * based on package name, i.e.: * * Map<String, Map<String, TypeInfo>> * * @param packageName * @return List of TypeInfo objects for a given package name */ public Map<String, TypeInfo> getTypeInfosForPackage(String packageName) { Map<String, TypeInfo> typeInfos = new HashMap<String, TypeInfo>(); ArrayList<JavaClass> jClasses = getTypeInfoClasses(); for (JavaClass jClass : jClasses) { if (jClass.getPackageName().equals(packageName)) { String key = jClass.getQualifiedName(); typeInfos.put(key, typeInfo.get(key)); } } return typeInfos; } /** * Set namespace override info from XML bindings file. This will typically * be called from the XMLProcessor. * * @param packageToNamespaceMappings */ public void setPackageToNamespaceMappings(HashMap<String, NamespaceInfo> packageToNamespaceMappings) { this.packageToNamespaceMappings = packageToNamespaceMappings; } public SchemaTypeInfo addClass(JavaClass javaClass) { if (javaClass == null) { return null; } else if (helper.isAnnotationPresent(javaClass, XmlTransient.class)) { return null; } if (typeInfo == null) { // this is the first class. Initialize all the properties this.typeInfoClasses = new ArrayList<JavaClass>(); this.typeInfo = new HashMap<String, TypeInfo>(); this.typeQNames = new ArrayList<QName>(); this.userDefinedSchemaTypes = new HashMap<String, QName>(); this.packageToNamespaceMappings = new HashMap<String, NamespaceInfo>(); this.namespaceResolver = new NamespaceResolver(); } JavaClass[] jClasses = new JavaClass[] { javaClass }; buildNewTypeInfo(jClasses); TypeInfo info = typeInfo.get(javaClass.getQualifiedName()); NamespaceInfo namespaceInfo; String packageName = javaClass.getPackageName(); namespaceInfo = this.packageToNamespaceMappings.get(packageName); SchemaTypeInfo schemaInfo = new SchemaTypeInfo(); schemaInfo.setSchemaTypeName(new QName(info.getClassNamespace(), info.getSchemaTypeName())); if (info.isSetXmlRootElement()) { org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = info.getXmlRootElement(); String elementName = xmlRE.getName(); if (elementName.equals(XMLProcessor.DEFAULT) || elementName.equals(EMPTY_STRING)) { if (javaClass.getName().indexOf("$") != -1) { elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf('$') + 1)); } else { elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf('.') + 1)); } // TCK Compliancy if (elementName.length() >= 3) { int idx = elementName.length() - 1; char ch = elementName.charAt(idx - 1); if (Character.isDigit(ch)) { char lastCh = Character.toUpperCase(elementName.charAt(idx)); elementName = elementName.substring(0, idx) + lastCh; } } } String rootNamespace = xmlRE.getNamespace(); QName rootElemName = null; if (rootNamespace.equals(XMLProcessor.DEFAULT)) { rootElemName = new QName(namespaceInfo.getNamespace(), elementName); } else { rootElemName = new QName(rootNamespace, elementName); } schemaInfo.getGlobalElementDeclarations().add(rootElemName); ElementDeclaration declaration = new ElementDeclaration(rootElemName, javaClass, javaClass.getRawName(), false); this.getGlobalElements().put(rootElemName, declaration); } return schemaInfo; } /** * Convenience method which class pre and postBuildTypeInfo for a given set * of JavaClasses. * * @param javaClasses */ public void buildNewTypeInfo(JavaClass[] javaClasses) { preBuildTypeInfo(javaClasses); postBuildTypeInfo(javaClasses); processPropertyTypes(javaClasses); } /** * Pre-process a descriptor customizer. Here, the given JavaClass is checked * for the existence of an @XmlCustomizer annotation. * * Note that the post processing of the descriptor customizers will take * place in MappingsGenerator's generateProject method, after the * descriptors and mappings have been generated. * * @param jClass * @param tInfo * @see XmlCustomizer * @see MappingsGenerator */ private void preProcessCustomizer(JavaClass jClass, TypeInfo tInfo) { XmlCustomizer xmlCustomizer = (XmlCustomizer) helper.getAnnotation(jClass, XmlCustomizer.class); if (xmlCustomizer != null) { tInfo.setXmlCustomizer(xmlCustomizer.value().getName()); } } /** * Lazy load the metadata logger. * * @return */ private JAXBMetadataLogger getLogger() { if (logger == null) { logger = new JAXBMetadataLogger(); } return logger; } /** * Return the Helper object set on this processor. * * @return */ Helper getHelper() { return this.helper; } public boolean isDefaultNamespaceAllowed() { return isDefaultNamespaceAllowed; } public List<ElementDeclaration> getLocalElements() { return this.localElements; } public Map<TypeMappingInfo, Class> getTypeMappingInfoToGeneratedClasses() { return this.typeMappingInfoToGeneratedClasses; } public Map<TypeMappingInfo, Class> getTypeMappingInfoToAdapterClasses() { return this.typeMappingInfoToAdapterClasses; } /** * Add an XmlRegistry to ObjectFactory class name pair to the map. * * @param factoryClassName * ObjectFactory class name * @param xmlReg * org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry instance */ public void addXmlRegistry(String factoryClassName, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry xmlReg) { this.xmlRegistries.put(factoryClassName, xmlReg); } /** * Convenience method for determining if a given JavaClass should be * processed as an ObjectFactory class. * * @param javaClass * @return true if the JavaClass is annotated with @XmlRegistry or the map * of XmlRegistries contains a key equal to the JavaClass' qualified * name */ private boolean isXmlRegistry(JavaClass javaClass) { return (helper.isAnnotationPresent(javaClass, XmlRegistry.class) || xmlRegistries.get(javaClass.getQualifiedName()) != null); } public Map<TypeMappingInfo, QName> getTypeMappingInfoToSchemaType() { return this.typeMappingInfoToSchemaType; } String getDefaultTargetNamespace() { return this.defaultTargetNamespace; } void setDefaultTargetNamespace(String defaultTargetNamespace) { this.defaultTargetNamespace = defaultTargetNamespace; } public void setDefaultNamespaceAllowed(boolean isDefaultNamespaceAllowed) { this.isDefaultNamespaceAllowed = isDefaultNamespaceAllowed; } HashMap<QName, ElementDeclaration> getElementDeclarationsForScope(String scopeClassName) { return this.elementDeclarations.get(scopeClassName); } private Map<Object, Object> createUserPropertiesMap(XmlProperty[] properties) { Map<Object, Object> propMap = new HashMap<Object, Object>(); for (XmlProperty prop : properties) { Object pvalue = prop.value(); if (!(prop.valueType() == String.class)) { pvalue = XMLConversionManager.getDefaultXMLManager().convertObject(prop.value(), prop.valueType()); } propMap.put(prop.name(), pvalue); } return propMap; } /** * Indicates if a given Property represents an MTOM attachment. Will return true * if the given Property's actual type is one of: * * - DataHandler * - byte[] * - Byte[] * - Image * - Source * - MimeMultipart * * @param property * @return */ public boolean isMtomAttachment(Property property) { JavaClass ptype = property.getActualType(); return (areEquals(ptype, JAVAX_ACTIVATION_DATAHANDLER) || areEquals(ptype, byte[].class) || areEquals(ptype, Byte[].class) || areEquals(ptype, Image.class) || areEquals(ptype, Source.class) || areEquals(ptype, JAVAX_MAIL_INTERNET_MIMEMULTIPART)); } }
package com.hellblazer.CoRE.example.orderProcessing; import javax.persistence.EntityManager; import com.hellblazer.CoRE.attribute.Attribute; import com.hellblazer.CoRE.attribute.ValueType; import com.hellblazer.CoRE.event.MetaProtocol; import com.hellblazer.CoRE.event.ProductChildSequencingAuthorization; import com.hellblazer.CoRE.event.ProductParentSequencingAuthorization; import com.hellblazer.CoRE.event.ProductSiblingSequencingAuthorization; import com.hellblazer.CoRE.event.Protocol; import com.hellblazer.CoRE.event.ProtocolAttribute; import com.hellblazer.CoRE.event.StatusCode; import com.hellblazer.CoRE.location.Location; import com.hellblazer.CoRE.meta.Kernel; import com.hellblazer.CoRE.meta.Model; import com.hellblazer.CoRE.meta.models.ModelImpl; import com.hellblazer.CoRE.network.NetworkInference; import com.hellblazer.CoRE.network.Relationship; import com.hellblazer.CoRE.product.Product; import com.hellblazer.CoRE.resource.Resource; import com.hellblazer.CoRE.resource.ResourceNetwork; /** * @author hhildebrand * */ public class ExampleLoader { public Relationship area; public Relationship areaOf; public Relationship city; public Relationship cityOf; public Relationship customerType; public Relationship customerTypeOf; public Relationship region; public Relationship regionOf; public Relationship state; public Relationship stateOf; public Relationship salesTaxStatus; public Relationship salesTaxStatusOf; public Relationship storageType; public Relationship storageTypeOf; public Relationship street; public Relationship streetOf; private Relationship notApplicableRelationship; private Relationship sameRelationship; private Relationship anyRelationship; public StatusCode unset; public StatusCode abandoned; public StatusCode completed; public StatusCode failure; public StatusCode active; public StatusCode available; public StatusCode pickCompleted; public StatusCode waitingOnFee; public StatusCode waitingOnPricing; public StatusCode waitingOnPurchaseOrder; private StatusCode creditChecked; public Product abc486; public Product checkCredit; public Product checkLetterOfCredit; public Product chemB; public Product deliver; public Product discount; public Product frozen; public Product fee; public Product printCustomsDeclaration; public Product printPurchaseOrder; public Product roomTemp; public Product pick; public Product salesTax; public Product ship; public Product nonExempt; private Product anyProduct; private Product sameProduct; public Location bht378; public Location bin1; public Location bin15; public Location dc; public Location east_coast; public Location euro; public Location france; public Location paris; public Location rsb225; public Location factory1; public Location us; public Location wash; private Location anyLocation; public Resource billingComputer; public Resource core; public Resource cpu; public Resource creditDept; public Resource exempt; public Resource externalCust; public Resource factory1Resource; public Resource georgeTownUniversity; public Resource manufacturer; public Resource nonExemptResource; public Resource orderFullfillment; public Resource orgA; private Resource anyResource; public Attribute priceAttribute; public Attribute taxRateAttribute; public Attribute discountAttribute; private final EntityManager em; private final Kernel kernel; private final Model model; public ExampleLoader(EntityManager em) throws Exception { this.em = em; model = new ModelImpl(em); kernel = model.getKernel(); core = kernel.getCore(); sameProduct = kernel.getSameProduct(); anyProduct = kernel.getAnyProduct(); anyResource = kernel.getAnyResource(); anyLocation = kernel.getAnyLocation(); sameRelationship = kernel.getSameRelationship(); anyRelationship = kernel.getAnyRelationship(); notApplicableRelationship = kernel.getNotApplicableRelationship(); unset = kernel.getUnset(); } public void createAttributes() { priceAttribute = new Attribute("price", "price", core, ValueType.NUMERIC); em.persist(priceAttribute); taxRateAttribute = new Attribute("tax rate", "tax rate", core, ValueType.NUMERIC); em.persist(taxRateAttribute); discountAttribute = new Attribute("discount", "discount", core, ValueType.NUMERIC); em.persist(discountAttribute); } public void createLocationNetworks() { model.getLocationModel().link(bin1, area, factory1, core); model.getLocationModel().link(bin15, area, factory1, core); model.getLocationModel().link(factory1, street, bht378, core); model.getLocationModel().link(rsb225, city, wash, core); model.getLocationModel().link(bht378, city, wash, core); model.getLocationModel().link(wash, state, dc, core); model.getLocationModel().link(dc, region, east_coast, core); model.getLocationModel().link(east_coast, area, us, core); model.getLocationModel().link(paris, region, france, core); model.getLocationModel().link(france, area, euro, core); } public void createLocations() { rsb225 = new Location("225RSB", "225 Reiss Science Bldg", core); em.persist(rsb225); bht378 = new Location("37BHT", "37 Bret Harte Terrace", core); em.persist(bht378); bin1 = new Location("BIN01", "Bin #1", core); em.persist(bin1); bin15 = new Location("BIN15", "Bin #15", core); em.persist(bin15); dc = new Location("DC", "District of Columbia", core); em.persist(dc); east_coast = new Location("EAST_COAST", "East Coast", core); em.persist(east_coast); factory1 = new Location("FACTORY1", "Factory 1", core); em.persist(factory1); france = new Location("FRANCE", "France", core); em.persist(france); paris = new Location("PARIS", "Paris", core); em.persist(paris); us = new Location("US", "U.S. Locations", core); em.persist(us); wash = new Location("WASH", "Washington", core); em.persist(wash); euro = new Location("Euro", "European locations", core); em.persist(euro); } public void createMetaProtocols() { MetaProtocol m1 = new MetaProtocol(deliver, 1, notApplicableRelationship, sameRelationship, sameRelationship, state, area, core); em.persist(m1); MetaProtocol m2 = new MetaProtocol(deliver, 2, notApplicableRelationship, customerType, sameRelationship, area, area, core); em.persist(m2); MetaProtocol m3 = new MetaProtocol(deliver, 3, notApplicableRelationship, customerType, anyRelationship, area, area, core); em.persist(m3); MetaProtocol m4 = new MetaProtocol(deliver, 4, notApplicableRelationship, customerType, sameRelationship, anyRelationship, area, core); em.persist(m4); MetaProtocol m5 = new MetaProtocol(deliver, 5, notApplicableRelationship, salesTaxStatus, sameRelationship, state, anyRelationship, core); em.persist(m5); MetaProtocol m6 = new MetaProtocol(deliver, 6, notApplicableRelationship, anyRelationship, anyRelationship, anyRelationship, anyRelationship, core); em.persist(m6); } public void createProductNetworks() { model.getProductModel().link(abc486, storageType, roomTemp, core); model.getProductModel().link(abc486, salesTaxStatus, nonExempt, core); model.getProductModel().link(chemB, storageType, frozen, core); } public void createProducts() { abc486 = new Product("ABC486", "Laptop Computer", core); em.persist(abc486); frozen = new Product("Frozen", "Frozen products", core); em.persist(frozen); nonExempt = new Product("NonExempt", "Subject to sales tax", core); em.persist(nonExempt); chemB = new Product("ChemB", "Chemical B", core); em.persist(chemB); roomTemp = new Product("RoomTemp", "Room temperature products", core); em.persist(roomTemp); } public void createProductSequencingAuthorizations() { ProductChildSequencingAuthorization activatePick = new ProductChildSequencingAuthorization( core); activatePick.setParent(deliver); activatePick.setStatusCode(active); activatePick.setNextChild(pick); activatePick.setNextChildStatus(available); em.persist(activatePick); ProductSiblingSequencingAuthorization activatePrintCustomsDeclaration = new ProductSiblingSequencingAuthorization( core); activatePrintCustomsDeclaration.setParent(printPurchaseOrder); activatePrintCustomsDeclaration.setStatusCode(completed); activatePrintCustomsDeclaration.setNextSibling(printCustomsDeclaration); activatePrintCustomsDeclaration.setNextSiblingStatus(available); em.persist(activatePrintCustomsDeclaration); ProductParentSequencingAuthorization productPicked = new ProductParentSequencingAuthorization( core); productPicked.setParent(pick); productPicked.setStatusCode(completed); productPicked.setMyParent(deliver); productPicked.setParentStatusToSet(completed); productPicked.setSetIfActiveSiblings(false); em.persist(productPicked); ProductParentSequencingAuthorization checkCreditCompleted = new ProductParentSequencingAuthorization( core); checkCreditCompleted.setParent(checkCredit); checkCreditCompleted.setStatusCode(completed); checkCreditCompleted.setMyParent(pick); checkCreditCompleted.setParentStatusToSet(creditChecked); em.persist(checkCreditCompleted); ProductParentSequencingAuthorization checkLetterOfCreditCompleted = new ProductParentSequencingAuthorization( core); checkLetterOfCreditCompleted.setParent(checkLetterOfCredit); checkLetterOfCreditCompleted.setStatusCode(completed); checkLetterOfCreditCompleted.setMyParent(pick); checkLetterOfCreditCompleted.setParentStatusToSet(creditChecked); em.persist(checkLetterOfCreditCompleted); ProductSiblingSequencingAuthorization activateShip = new ProductSiblingSequencingAuthorization( core); activateShip.setParent(pick); activateShip.setStatusCode(completed); activateShip.setNextSibling(ship); activateShip.setNextSiblingStatus(waitingOnPurchaseOrder); em.persist(activateShip); ProductParentSequencingAuthorization activateShipFromPrintCustomsDeclaration = new ProductParentSequencingAuthorization( core); activateShipFromPrintCustomsDeclaration.setParent(printCustomsDeclaration); activateShipFromPrintCustomsDeclaration.setStatusCode(completed); activateShipFromPrintCustomsDeclaration.setMyParent(ship); activateShipFromPrintCustomsDeclaration.setParentStatusToSet(available); activateShipFromPrintCustomsDeclaration.setSetIfActiveSiblings(false); em.persist(activateShipFromPrintCustomsDeclaration); ProductParentSequencingAuthorization activateShipFromPrintPurchaseOrder = new ProductParentSequencingAuthorization( core); activateShipFromPrintPurchaseOrder.setParent(printPurchaseOrder); activateShipFromPrintPurchaseOrder.setStatusCode(completed); activateShipFromPrintPurchaseOrder.setMyParent(ship); activateShipFromPrintPurchaseOrder.setParentStatusToSet(available); activateShipFromPrintPurchaseOrder.setSetIfActiveSiblings(false); em.persist(activateShipFromPrintPurchaseOrder); ProductChildSequencingAuthorization activatePrintPurchaseOrder = new ProductChildSequencingAuthorization( core); activatePrintPurchaseOrder.setParent(ship); activatePrintPurchaseOrder.setStatusCode(waitingOnPurchaseOrder); activatePrintPurchaseOrder.setNextChild(printPurchaseOrder); activatePrintPurchaseOrder.setNextChildStatus(waitingOnFee); em.persist(activatePrintPurchaseOrder); ProductChildSequencingAuthorization activateFee = new ProductChildSequencingAuthorization( core); activateFee.setParent(printPurchaseOrder); activateFee.setStatusCode(waitingOnFee); activateFee.setNextChild(fee); activateFee.setNextChildStatus(active); em.persist(activateFee); ProductSiblingSequencingAuthorization activateDiscount = new ProductSiblingSequencingAuthorization( core); activateDiscount.setParent(fee); activateDiscount.setStatusCode(completed); activateDiscount.setNextSibling(discount); activateDiscount.setNextSiblingStatus(available); em.persist(activateDiscount); ProductParentSequencingAuthorization activatePrintPurchaseOrderFromFee = new ProductParentSequencingAuthorization( core); activatePrintPurchaseOrderFromFee.setParent(fee); activatePrintPurchaseOrderFromFee.setStatusCode(completed); activatePrintPurchaseOrderFromFee.setMyParent(printPurchaseOrder); activatePrintPurchaseOrderFromFee.setParentStatusToSet(available); activatePrintPurchaseOrderFromFee.setSetIfActiveSiblings(false); em.persist(activatePrintPurchaseOrderFromFee); ProductParentSequencingAuthorization activatePrintPurchaseOrderFromDiscount = new ProductParentSequencingAuthorization( core); activatePrintPurchaseOrderFromDiscount.setParent(discount); activatePrintPurchaseOrderFromDiscount.setStatusCode(completed); activatePrintPurchaseOrderFromDiscount.setMyParent(printPurchaseOrder); activatePrintPurchaseOrderFromDiscount.setParentStatusToSet(available); activatePrintPurchaseOrderFromDiscount.setSetIfActiveSiblings(false); em.persist(activatePrintPurchaseOrderFromDiscount); } public void createProtocols() { Protocol pickProtocol = new Protocol(deliver, anyResource, anyProduct, anyLocation, anyLocation, factory1Resource, pick, sameProduct, core); em.persist(pickProtocol); Protocol chkCreditProtocol = new Protocol(pick, externalCust, anyProduct, us, us, cpu, checkCredit, sameProduct, core); em.persist(chkCreditProtocol); Protocol chkLtrCrdtProtocol = new Protocol(pick, externalCust, anyProduct, euro, us, creditDept, checkLetterOfCredit, sameProduct, core); em.persist(chkLtrCrdtProtocol); Protocol shipProtocol = new Protocol(deliver, anyResource, anyProduct, anyLocation, anyLocation, factory1Resource, ship, sameProduct, true, core); em.persist(shipProtocol); Protocol printCustDeclProtocol = new Protocol(ship, externalCust, abc486, euro, us, cpu, printCustomsDeclaration, sameProduct, core); em.persist(printCustDeclProtocol); Protocol printPoProtocol = new Protocol(ship, externalCust, abc486, euro, us, cpu, printPurchaseOrder, sameProduct, core); em.persist(printPoProtocol); Protocol feeProtocol = new Protocol(printPurchaseOrder, externalCust, abc486, anyLocation, us, billingComputer, fee, sameProduct, core); em.persist(feeProtocol); ProtocolAttribute price = new ProtocolAttribute(priceAttribute, core); price.setNumericValue(1500); price.setProtocol(feeProtocol); em.persist(price); Protocol salesTaxProtocol = new Protocol(fee, nonExemptResource, nonExempt, dc, anyLocation, billingComputer, salesTax, sameProduct, core); em.persist(salesTaxProtocol); ProtocolAttribute taxRate = new ProtocolAttribute(taxRateAttribute, core); taxRate.setNumericValue(0.0575); taxRate.setProtocol(salesTaxProtocol); em.persist(taxRate); Protocol discountProtocol = new Protocol(fee, externalCust, abc486, euro, us, billingComputer, discount, sameProduct, core); em.persist(discountProtocol); ProtocolAttribute euroDiscount = new ProtocolAttribute( discountAttribute, core); euroDiscount.setNumericValue(0.05); euroDiscount.setProtocol(salesTaxProtocol); em.persist(euroDiscount); Protocol gtuDiscountedPriceProtocol = new Protocol( fee, georgeTownUniversity, abc486, dc, us, billingComputer, fee, sameProduct, core); em.persist(gtuDiscountedPriceProtocol); ProtocolAttribute discountedPrice = new ProtocolAttribute( priceAttribute, core); discountedPrice.setNumericValue(1250); discountedPrice.setProtocol(gtuDiscountedPriceProtocol); em.persist(discountedPrice); } public void createRelationships() { area = new Relationship("Area", "A is a member of the economic community B", core, true); em.persist(area); areaOf = new Relationship("Area Of", "A is economic community of B", core, area); area.setInverse(areaOf); em.persist(areaOf); city = new Relationship("City", "A is located in the City B", core, true); em.persist(city); cityOf = new Relationship("City Of", "A is the city of B", core, city); city.setInverse(cityOf); em.persist(cityOf); customerType = new Relationship("Customer Type", "A has customer type of B", core, true); em.persist(customerType); customerTypeOf = new Relationship("Customer Type Of", "A is the customer type of B", core, customerType); customerType.setInverse(customerTypeOf); em.persist(customerTypeOf); region = new Relationship("Region", "A's general region is B", core, true); em.persist(region); regionOf = new Relationship("Region Of", "A is the region of B", core, region); region.setInverse(regionOf); em.persist(regionOf); state = new Relationship("State", "The State of A is B", core, true); em.persist(state); stateOf = new Relationship("State Of", "A is the state of B", core, state); state.setInverse(stateOf); em.persist(stateOf); salesTaxStatus = new Relationship("SalesTaxStatus", "The sales tax status of A is B", core, true); em.persist(salesTaxStatus); salesTaxStatusOf = new Relationship("SalesTaxStatus Of", "A is the sales tax status of B", core, salesTaxStatus); salesTaxStatus.setInverse(salesTaxStatusOf); em.persist(salesTaxStatusOf); storageType = new Relationship( "StorageType", "The type of storage required for A is B", core, true); em.persist(storageType); storageTypeOf = new Relationship("StorageType Of", "A is the storage type of B", core, storageType); storageType.setInverse(storageTypeOf); em.persist(storageTypeOf); street = new Relationship("Street", "The street of A is B", core, true); em.persist(street); streetOf = new Relationship("Street of", "A is the street of B", core, street); street.setInverse(streetOf); em.persist(streetOf); } public void createResourceNetwork() { em.persist(new ResourceNetwork()); } public void createResourceNetworks() { model.getResourceModel().link(georgeTownUniversity, customerType, externalCust, core); model.getResourceModel().link(georgeTownUniversity, salesTaxStatus, exempt, core); model.getResourceModel().link(orgA, customerType, externalCust, core); model.getResourceModel().link(orgA, salesTaxStatus, nonExemptResource, core); } public void createResources() { billingComputer = new Resource("Billing CPU", "The Billing Computer", core); em.persist(billingComputer); cpu = new Resource("CPU", "Computer", core); em.persist(cpu); creditDept = new Resource("Credit", "Credit Department", core); em.persist(creditDept); exempt = new Resource("Exempt", "Exempt from sales taxes", core); em.persist(exempt); externalCust = new Resource("Ext Customer", "External (Paying) Customer", core); em.persist(externalCust); factory1Resource = new Resource("Factory1", "Factory #1", core); em.persist(factory1Resource); georgeTownUniversity = new Resource("GU", "Georgetown University", core); em.persist(georgeTownUniversity); manufacturer = new Resource("MNFR", "Manufacturer", core); em.persist(manufacturer); nonExemptResource = new Resource("NonExempt", "Subject to sales taxes", core); em.persist(nonExemptResource); orgA = new Resource("OrgA", "Organization A", core); em.persist(orgA); orderFullfillment = new Resource("Order Fullfillment", "Order Fullfillment", core); em.persist(orderFullfillment); } public void createServices() { deliver = new Product("Deliver", "Deliver product", core); em.persist(deliver); pick = new Product("Pick", "Pick inventory", core); em.persist(pick); ship = new Product("Ship", "Ship inventory", core); em.persist(ship); checkCredit = new Product("CheckCredit", "Check customer inhouse credit", core); em.persist(checkCredit); checkLetterOfCredit = new Product("CheckLetterOfCredit", "Check customer letter of credit", core); em.persist(checkLetterOfCredit); discount = new Product("Discount", "Compute fee discount ", core); em.persist(discount); fee = new Product("Fee", "Compute fee", core); em.persist(fee); printCustomsDeclaration = new Product("PrintCustomsDeclaration", "Print the customs declaration", core); em.persist(printCustomsDeclaration); printPurchaseOrder = new Product("PrintPurchaseOrder", "Print the purchase order", core); em.persist(printPurchaseOrder); salesTax = new Product("SalesTax", "Compute sales tax", core); em.persist(salesTax); } public void createStatusCodes() { available = new StatusCode("Available", "The job is available for execution", core); em.persist(available); active = new StatusCode("Active", "Working on it now", core); em.persist(active); creditChecked = new StatusCode("Credit Checked", "Credit has been checked", core); em.persist(active); completed = new StatusCode("Credit Check Completed", "Completed Credit Check", core); completed.setPropagateChildren(true); em.persist(completed); completed = new StatusCode("Completed", "Completed Job", core); completed.setPropagateChildren(true); em.persist(completed); failure = new StatusCode("Failure", "Something went wrong", core); failure.setFailParent(true); em.persist(failure); pickCompleted = new StatusCode("Pick Completed", "Pick product has been completed", core); em.persist(pickCompleted); waitingOnPurchaseOrder = new StatusCode( "Waiting on purchase order", "Waiting for purchase order to be completed", core); em.persist(waitingOnPurchaseOrder); waitingOnPricing = new StatusCode( "Waiting on pricing", "Waiting for pricing to be completed", core); em.persist(waitingOnPricing); waitingOnFee = new StatusCode( "Waiting on fee calculation", "Waiting for fee calculation to be completed", core); em.persist(waitingOnFee); abandoned = new StatusCode( "Abandoned", "We were going to do it, something happened in earlier processing that will prevent us. This can be garbage-collected now", core); em.persist(abandoned); } public void load() { createResources(); createAttributes(); createProducts(); createServices(); createLocations(); createRelationships(); createNetworkInferences(); createProductNetworks(); createResourceNetworks(); createLocationNetworks(); createProtocols(); createMetaProtocols(); createStatusCodes(); // createSequencingAuthorizations(); } public void createNetworkInferences() { NetworkInference areaToRegion = new NetworkInference(area, region, region, core); em.persist(areaToRegion); NetworkInference regionToState = new NetworkInference(region, state, region, core); em.persist(regionToState); NetworkInference stateToCity = new NetworkInference(state, city, state, core); em.persist(stateToCity); NetworkInference cityToStreet = new NetworkInference(city, street, city, core); em.persist(cityToStreet); } }
package org.eclipse.mylyn.internal.provisional.commons.ui; import java.net.MalformedURLException; import java.net.URL; import java.util.Calendar; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.mylyn.internal.commons.ui.CommonsUiPlugin; import org.eclipse.mylyn.internal.commons.ui.Messages; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IPluginContribution; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.activities.IIdentifier; import org.eclipse.ui.activities.IWorkbenchActivitySupport; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import org.eclipse.ui.internal.browser.WebBrowserPreference; import org.eclipse.ui.internal.browser.WorkbenchBrowserSupport; /** * @author Mik Kersten * @author Steffen Pingel */ public class WorkbenchUtil { // TODO e3.6 IProgressConstants2#SHOW_IN_TASKBAR_ICON_PROPERTY public static final QualifiedName SHOW_IN_TASKBAR_ICON_PROPERTY = new QualifiedName( "org.eclipse.ui.workbench.progress", "inTaskBarIcon"); //$NON-NLS-1$//$NON-NLS-2$ // FIXME remove this again private static final boolean TEST_MODE; static { String application = System.getProperty("eclipse.application", ""); //$NON-NLS-1$ //$NON-NLS-2$ if (application.length() > 0) { TEST_MODE = application.endsWith("testapplication"); //$NON-NLS-1$ } else { // eclipse 3.3 does not the eclipse.application property String commands = System.getProperty("eclipse.commands", ""); //$NON-NLS-1$ //$NON-NLS-2$ TEST_MODE = commands.contains("testapplication\n"); //$NON-NLS-1$ } } // public static IViewPart getFromActivePerspective(String viewId) { // if (PlatformUI.isWorkbenchRunning()) { // IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); // if (activePage != null) { // return activePage.findView(viewId); // return null; public static IViewPart showViewInActiveWindow(String viewId) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { try { return page.showView(viewId); } catch (PartInitException e) { // ignore } } } return null; } /** * Return the modal shell that is currently open. If there isn't one then return null. * <p> * <b>Note: Applied from patch on bug 99472.</b> * * @param shell * A shell to exclude from the search. May be <code>null</code>. * @return Shell or <code>null</code>. */ private static Shell getModalShellExcluding(Shell shell) { IWorkbench workbench = PlatformUI.getWorkbench(); Shell[] shells = workbench.getDisplay().getShells(); int modal = SWT.APPLICATION_MODAL | SWT.SYSTEM_MODAL | SWT.PRIMARY_MODAL; for (Shell shell2 : shells) { if (shell2.equals(shell)) { break; } // Do not worry about shells that will not block the user. if (shell2.isVisible()) { int style = shell2.getStyle(); if ((style & modal) != 0) { return shell2; } } } return null; } /** * Utility method to get the best parenting possible for a dialog. If there is a modal shell create it so as to * avoid two modal dialogs. If not then return the shell of the active workbench window. If neither can be found * return null. * <p> * <b>Note: Applied from patch on bug 99472.</b> * * @return Shell or <code>null</code> */ public static Shell getShell() { if (!PlatformUI.isWorkbenchRunning() || PlatformUI.getWorkbench().isClosing()) { return null; } Shell modal = getModalShellExcluding(null); if (modal != null) { return modal; } return getNonModalShell(); } /** * Get the active non modal shell. If there isn't one return null. * <p> * <b>Note: Applied from patch on bug 99472.</b> * * @return Shell */ private static Shell getNonModalShell() { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) { IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows(); if (windows.length > 0) { return windows[0].getShell(); } } else { return window.getShell(); } return null; } /** * @return whether the UI is set up to filter contributions (has defined activity categories). */ public static final boolean isFiltering() { return !PlatformUI.getWorkbench().getActivitySupport().getActivityManager().getDefinedActivityIds().isEmpty(); } public static boolean allowUseOf(Object object) { if (!isFiltering()) { return true; } if (object instanceof IPluginContribution) { IPluginContribution contribution = (IPluginContribution) object; if (contribution.getPluginId() != null) { IWorkbenchActivitySupport workbenchActivitySupport = PlatformUI.getWorkbench().getActivitySupport(); IIdentifier identifier = workbenchActivitySupport.getActivityManager().getIdentifier( createUnifiedId(contribution)); return identifier.isEnabled(); } } if (object instanceof String) { IWorkbenchActivitySupport workbenchActivitySupport = PlatformUI.getWorkbench().getActivitySupport(); IIdentifier identifier = workbenchActivitySupport.getActivityManager().getIdentifier((String) object); return identifier.isEnabled(); } return true; } private static final String createUnifiedId(IPluginContribution contribution) { if (contribution.getPluginId() != null) { return contribution.getPluginId() + '/' + contribution.getLocalId(); } return contribution.getLocalId(); } /** * Opens <code>location</code> in a web-browser according to the Eclipse workbench preferences. * * @param location * the url to open * @see #openUrl(String, int) */ public static void openUrl(String location) { openUrl(location, SWT.NONE); } /** * Opens <code>location</code> in a web-browser according to the Eclipse workbench preferences. * * @param location * the url to open * @param customFlags * additional flags that are passed to {@link IWorkbenchBrowserSupport}, pass * {@link IWorkbenchBrowserSupport#AS_EXTERNAL} to force opening external browser */ public static void openUrl(String location, int customFlags) { try { URL url = null; if (location != null) { url = new URL(location); } if (WebBrowserPreference.getBrowserChoice() == WebBrowserPreference.EXTERNAL || (customFlags & IWorkbenchBrowserSupport.AS_EXTERNAL) != 0) { try { IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport(); support.getExternalBrowser().openURL(url); } catch (PartInitException e) { Status status = new Status(IStatus.ERROR, CommonsUiPlugin.ID_PLUGIN, Messages.WorkbenchUtil_Browser_Initialization_Failed); CommonsUiPlugin.getDefault().getLog().log(status); if (!TEST_MODE) { MessageDialog.openError(getShell(), Messages.WorkbenchUtil_Open_Location_Title, status.getMessage()); } } } else { IWebBrowser browser = null; int flags = customFlags; if (WorkbenchBrowserSupport.getInstance().isInternalWebBrowserAvailable()) { flags |= IWorkbenchBrowserSupport.AS_EDITOR | IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.NAVIGATION_BAR; } else { flags |= IWorkbenchBrowserSupport.AS_EXTERNAL | IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.NAVIGATION_BAR; } String generatedId = "org.eclipse.mylyn.web.browser-" + Calendar.getInstance().getTimeInMillis(); //$NON-NLS-1$ browser = WorkbenchBrowserSupport.getInstance().createBrowser(flags, generatedId, null, null); browser.openURL(url); } } catch (PartInitException e) { Status status = new Status(IStatus.ERROR, CommonsUiPlugin.ID_PLUGIN, Messages.WorkbenchUtil_Browser_Initialization_Failed, e); CommonsUiPlugin.getDefault().getLog().log(status); if (!TEST_MODE) { MessageDialog.openError(getShell(), Messages.WorkbenchUtil_Open_Location_Title, status.getMessage()); } } catch (MalformedURLException e) { if (location != null && location.trim().equals("")) { //$NON-NLS-1$ Status status = new Status(IStatus.WARNING, CommonsUiPlugin.ID_PLUGIN, Messages.WorkbenchUtil_No_URL_Error, e); if (!TEST_MODE) { MessageDialog.openWarning(getShell(), Messages.WorkbenchUtil_Open_Location_Title, status.getMessage()); } else { CommonsUiPlugin.getDefault().getLog().log(status); } } else { Status status = new Status(IStatus.ERROR, CommonsUiPlugin.ID_PLUGIN, NLS.bind( Messages.WorkbenchUtil_Invalid_URL_Error, location), e); if (!TEST_MODE) { MessageDialog.openError(getShell(), Messages.WorkbenchUtil_Open_Location_Title, status.getMessage()); } else { CommonsUiPlugin.getDefault().getLog().log(status); } } } } }
package org.eclipse.mylyn.tasks.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.StringFieldEditor; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.mylyn.internal.monitor.core.util.StatusManager; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylyn.tasks.core.IRepositoryConstants; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.TaskRepositoryManager; import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.tasks.ui.TasksUiUtil; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.events.ExpansionAdapter; import org.eclipse.ui.forms.events.ExpansionEvent; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.events.IHyperlinkListener; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.internal.net.ProxyPreferencePage; /** * @author Mik Kersten * @author Rob Elves * @author Steffen Pingel */ public abstract class AbstractRepositorySettingsPage extends WizardPage { protected static final String PREFS_PAGE_ID_NET_PROXY = "org.eclipse.ui.net.NetPreferences"; protected static final String LABEL_REPOSITORY_LABEL = "Label: "; protected static final String LABEL_SERVER = "Server: "; protected static final String LABEL_USER = "User ID: "; protected static final String LABEL_PASSWORD = "Password: "; protected static final String URL_PREFIX_HTTPS = "https: protected static final String URL_PREFIX_HTTP = "http: protected static final String INVALID_REPOSITORY_URL = "Repository url is invalid."; protected static final String INVALID_LOGIN = "Unable to authenticate with repository. Login credentials invalid."; protected AbstractRepositoryConnector connector; protected StringFieldEditor repositoryLabelEditor; protected Combo serverUrlCombo; private String serverVersion = TaskRepository.NO_VERSION_SPECIFIED; protected StringFieldEditor repositoryUserNameEditor; protected StringFieldEditor repositoryPasswordEditor; protected StringFieldEditor httpAuthUserNameEditor; protected StringFieldEditor httpAuthPasswordEditor; protected StringFieldEditor proxyHostnameEditor; protected StringFieldEditor proxyPortEditor; protected StringFieldEditor proxyUserNameEditor; protected StringFieldEditor proxyPasswordEditor; protected TaskRepository repository; private Button validateServerButton; private Combo otherEncodingCombo; private Button defaultEncoding; // private Combo timeZonesCombo; protected Button anonymousButton; private String oldUsername; private String oldPassword; private String oldHttpAuthUserId; private String oldHttpAuthPassword; private boolean needsAnonymousLogin; private boolean needsTimeZone; private boolean needsEncoding; private boolean needsHttpAuth; private boolean needsValidation; protected Composite compositeContainer; private Composite advancedComp; private Composite httpAuthComp; private Composite proxyAuthComp; private ExpandableComposite advancedExpComposite; private ExpandableComposite httpAuthExpComposite; private ExpandableComposite proxyExpComposite; private Set<String> repositoryUrls; private String originalUrl; private Button otherEncoding; private Button httpAuthButton; private boolean needsProxy; private Button systemProxyButton; private String oldProxyUsername = ""; private String oldProxyPassword = ""; // private Button proxyAuthButton; private String oldProxyHostname = ""; private String oldProxyPort = ""; private Button proxyAuthButton; private FormToolkit toolkit = new FormToolkit(Display.getCurrent()); private Hyperlink createAccountHyperlink; private Hyperlink manageAccountHyperlink; public AbstractRepositorySettingsPage(String title, String description, AbstractRepositoryConnectorUi repositoryUi) { super(title); super.setTitle(title); super.setDescription(description); AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector( repositoryUi.getRepositoryType()); this.connector = connector; setNeedsAnonymousLogin(false); setNeedsEncoding(true); setNeedsTimeZone(true); setNeedsProxy(true); setNeedsValidation(true); } @Override public void dispose() { super.dispose(); if (toolkit != null) { if (toolkit.getColors() != null) { toolkit.dispose(); } } } public void createControl(Composite parent) { compositeContainer = new Composite(parent, SWT.NULL); FillLayout layout = new FillLayout(); compositeContainer.setLayout(layout); new Label(compositeContainer, SWT.NONE).setText(LABEL_SERVER); serverUrlCombo = new Combo(compositeContainer, SWT.DROP_DOWN); serverUrlCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { isValidUrl(serverUrlCombo.getText()); if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } }); serverUrlCombo.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { updateHyperlinks(); } }); serverUrlCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { isValidUrl(serverUrlCombo.getText()); if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } }); GridDataFactory.fillDefaults().hint(300, SWT.DEFAULT).grab(true, false).applyTo(serverUrlCombo); repositoryLabelEditor = new StringFieldEditor("", LABEL_REPOSITORY_LABEL, StringFieldEditor.UNLIMITED, compositeContainer) { @Override protected boolean doCheckState() { return true; // return isValidUrl(getStringValue()); } @Override protected void valueChanged() { super.valueChanged(); if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } }; // repositoryLabelEditor.setErrorMessage("error"); if (needsAnonymousLogin()) { anonymousButton = new Button(compositeContainer, SWT.CHECK); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(anonymousButton); anonymousButton.setText("Anonymous Access"); anonymousButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setAnonymous(anonymousButton.getSelection()); isPageComplete(); } }); } repositoryUserNameEditor = new StringFieldEditor("", LABEL_USER, StringFieldEditor.UNLIMITED, compositeContainer) { @Override protected boolean doCheckState() { return true; } @Override protected void valueChanged() { super.valueChanged(); isPageComplete(); if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } }; repositoryPasswordEditor = new RepositoryStringFieldEditor("", LABEL_PASSWORD, StringFieldEditor.UNLIMITED, compositeContainer) { @Override protected boolean doCheckState() { return true; } @Override protected void valueChanged() { super.valueChanged(); isPageComplete(); if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } }; if (needsAnonymousLogin()) { if (repository != null) { setAnonymous(repository.isAnonymous()); } else { setAnonymous(true); } } // TODO: put this back if we can't get the info from all connectors // if (needsTimeZone()) { // Label timeZoneLabel = new Label(container, SWT.NONE); // timeZoneLabel.setText("Repository time zone: "); // timeZonesCombo = new Combo(container, SWT.READ_ONLY); // String[] timeZoneIds = TimeZone.getAvailableIDs(); // Arrays.sort(timeZoneIds); // for (String zone : timeZoneIds) { // timeZonesCombo.add(zone); // boolean setZone = false; // if (repository != null) { // if (timeZonesCombo.indexOf(repository.getTimeZoneId()) > -1) { // timeZonesCombo.select(timeZonesCombo.indexOf(repository.getTimeZoneId())); // setZone = true; // if (!setZone) { // timeZonesCombo.select(timeZonesCombo.indexOf(TimeZone.getDefault().getID())); advancedExpComposite = toolkit.createExpandableComposite(compositeContainer, Section.COMPACT | Section.TWISTIE | Section.TITLE_BAR); advancedExpComposite.clientVerticalSpacing = 0; GridData gridData_2 = new GridData(SWT.FILL, SWT.FILL, true, false); gridData_2.horizontalIndent = -5; advancedExpComposite.setLayoutData(gridData_2); advancedExpComposite.setFont(compositeContainer.getFont()); advancedExpComposite.setBackground(compositeContainer.getBackground()); advancedExpComposite.setText("Additional Settings"); advancedExpComposite.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent e) { getControl().getShell().pack(); } }); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(advancedExpComposite); advancedComp = toolkit.createComposite(advancedExpComposite, SWT.NONE); GridLayout gridLayout2 = new GridLayout(); gridLayout2.numColumns = 2; gridLayout2.verticalSpacing = 5; advancedComp.setLayout(gridLayout2); advancedComp.setBackground(compositeContainer.getBackground()); advancedExpComposite.setClient(advancedComp); createAdditionalControls(advancedComp); if (needsEncoding()) { Label encodingLabel = new Label(advancedComp, SWT.HORIZONTAL); encodingLabel.setText("Character Encoding:"); GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.TOP).applyTo(encodingLabel); Composite encodingContainer = new Composite(advancedComp, SWT.NONE); GridLayout gridLayout = new GridLayout(2, false); gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; encodingContainer.setLayout(gridLayout); defaultEncoding = new Button(encodingContainer, SWT.RADIO); defaultEncoding.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); defaultEncoding.setText("Default (" + TaskRepository.DEFAULT_CHARACTER_ENCODING + ")"); defaultEncoding.setSelection(true); otherEncoding = new Button(encodingContainer, SWT.RADIO); otherEncoding.setText("Other:"); otherEncodingCombo = new Combo(encodingContainer, SWT.READ_ONLY); for (String encoding : Charset.availableCharsets().keySet()) { if (!encoding.equals(TaskRepository.DEFAULT_CHARACTER_ENCODING)) { otherEncodingCombo.add(encoding); } } setDefaultEncoding(); otherEncoding.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (otherEncoding.getSelection()) { defaultEncoding.setSelection(false); otherEncodingCombo.setEnabled(true); } else { defaultEncoding.setSelection(true); otherEncodingCombo.setEnabled(false); } } }); if (repository != null) { try { String repositoryEncoding = repository.getCharacterEncoding(); if (repositoryEncoding != null) { // !repositoryEncoding.equals(defaultEncoding)) if (otherEncodingCombo.getItemCount() > 0 && otherEncodingCombo.indexOf(repositoryEncoding) > -1) { otherEncodingCombo.setEnabled(true); otherEncoding.setSelection(true); defaultEncoding.setSelection(false); otherEncodingCombo.select(otherEncodingCombo.indexOf(repositoryEncoding)); } else { setDefaultEncoding(); } } } catch (Throwable t) { StatusManager.fail(t, "could not set field value for: " + repository, false); } } } if (needsHttpAuth()) { httpAuthExpComposite = toolkit.createExpandableComposite(compositeContainer, Section.COMPACT | Section.TWISTIE | Section.TITLE_BAR); httpAuthExpComposite.clientVerticalSpacing = 0; gridData_2 = new GridData(SWT.FILL, SWT.FILL, true, false); gridData_2.horizontalIndent = -5; httpAuthExpComposite.setLayoutData(gridData_2); httpAuthExpComposite.setFont(compositeContainer.getFont()); httpAuthExpComposite.setBackground(compositeContainer.getBackground()); httpAuthExpComposite.setText("Http Authentication"); httpAuthExpComposite.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent e) { getControl().getShell().pack(); } }); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(httpAuthExpComposite); httpAuthComp = toolkit.createComposite(httpAuthExpComposite, SWT.NONE); gridLayout2 = new GridLayout(); gridLayout2.numColumns = 2; gridLayout2.verticalSpacing = 0; httpAuthComp.setLayout(gridLayout2); httpAuthComp.setBackground(compositeContainer.getBackground()); httpAuthExpComposite.setClient(httpAuthComp); httpAuthButton = new Button(httpAuthComp, SWT.CHECK); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.TOP).span(2, SWT.DEFAULT).applyTo(httpAuthButton); httpAuthButton.setText("Enabled"); httpAuthButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { setHttpAuth(httpAuthButton.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) { // ignore } }); httpAuthUserNameEditor = new StringFieldEditor("", "User ID: ", StringFieldEditor.UNLIMITED, httpAuthComp) { @Override protected boolean doCheckState() { return true; } @Override protected void valueChanged() { super.valueChanged(); if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } }; httpAuthPasswordEditor = new RepositoryStringFieldEditor("", "Password: ", StringFieldEditor.UNLIMITED, httpAuthComp); ((RepositoryStringFieldEditor) httpAuthPasswordEditor).getTextControl().setEchoChar('*'); // httpAuthGroup.setEnabled(httpAuthButton.getSelection()); httpAuthUserNameEditor.setEnabled(httpAuthButton.getSelection(), httpAuthComp); httpAuthPasswordEditor.setEnabled(httpAuthButton.getSelection(), httpAuthComp); setHttpAuth(oldHttpAuthPassword != null && oldHttpAuthUserId != null && !oldHttpAuthPassword.equals("") && !oldHttpAuthUserId.equals("")); httpAuthExpComposite.setExpanded(httpAuthButton.getSelection()); } if (repository != null) { originalUrl = repository.getUrl(); oldUsername = repository.getUserName(); oldPassword = repository.getPassword(); if (repository.getHttpUser() != null && repository.getHttpPassword() != null) { oldHttpAuthUserId = repository.getHttpUser(); oldHttpAuthPassword = repository.getHttpPassword(); } else { oldHttpAuthPassword = ""; oldHttpAuthUserId = ""; } oldProxyHostname = repository.getProperty(TaskRepository.PROXY_HOSTNAME); oldProxyPort = repository.getProperty(TaskRepository.PROXY_PORT); if (oldProxyHostname == null) oldProxyHostname = ""; if (oldProxyPort == null) oldProxyPort = ""; oldProxyUsername = repository.getProxyUsername(); oldProxyPassword = repository.getProxyPassword(); if (oldProxyUsername == null) oldProxyUsername = ""; if (oldProxyPassword == null) oldProxyPassword = ""; try { String repositoryLabel = repository.getProperty(IRepositoryConstants.PROPERTY_LABEL); if (repositoryLabel != null && repositoryLabel.length() > 0) { // repositoryLabelCombo.add(repositoryLabel); // repositoryLabelCombo.select(0); repositoryLabelEditor.setStringValue(repositoryLabel); } serverUrlCombo.setText(repository.getUrl()); repositoryUserNameEditor.setStringValue(repository.getUserName()); repositoryPasswordEditor.setStringValue(repository.getPassword()); } catch (Throwable t) { StatusManager.fail(t, "could not set field value for: " + repository, false); } } else { oldUsername = ""; oldPassword = ""; oldHttpAuthPassword = ""; oldHttpAuthUserId = ""; } if (needsProxy()) { addProxySection(); } Composite managementComposite = new Composite(compositeContainer, SWT.NULL); GridLayout managementLayout = new GridLayout(4, false); managementLayout.marginHeight = 0; managementLayout.marginWidth = 0; managementLayout.horizontalSpacing = 10; managementComposite.setLayout(managementLayout); managementComposite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 2, 1)); if (needsValidation()) { validateServerButton = new Button(managementComposite, SWT.PUSH); GridDataFactory.swtDefaults().span(2, SWT.DEFAULT).grab(false, false).applyTo(validateServerButton); validateServerButton.setText("Validate Settings"); validateServerButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { validateSettings(); } }); } createAccountHyperlink = toolkit.createHyperlink(managementComposite, "Create new account", SWT.NONE); createAccountHyperlink.setBackground(managementComposite.getBackground()); createAccountHyperlink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { // TaskRepository repository = getRepository(); TaskRepository repository = createTaskRepository(); // if (repository == null && getServerUrl() != null && getServerUrl().length() > 0) { // repository = createTaskRepository(); if (repository != null) { String accountCreationUrl = TasksUiPlugin.getRepositoryUi(connector.getRepositoryType()) .getAccountCreationUrl(repository); if (accountCreationUrl != null) { TasksUiUtil.openUrl(accountCreationUrl, false); } } } }); manageAccountHyperlink = toolkit.createHyperlink(managementComposite, "Change account settings", SWT.NONE); manageAccountHyperlink.setBackground(managementComposite.getBackground()); manageAccountHyperlink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { TaskRepository repository = getRepository(); if (repository == null && getServerUrl() != null && getServerUrl().length() > 0) { repository = createTaskRepository(); } if (repository != null) { String accountManagementUrl = TasksUiPlugin.getRepositoryUi(connector.getRepositoryType()) .getAccountManagementUrl(repository); if (accountManagementUrl != null) { TasksUiUtil.openUrl(accountManagementUrl, false); } } } }); // bug 131656: must set echo char after setting value on Mac ((RepositoryStringFieldEditor) repositoryPasswordEditor).getTextControl().setEchoChar('*'); if (needsAnonymousLogin()) { // do this after username and password widgets have been intialized if (repository != null) { setAnonymous(isAnonymousAccess()); } } updateHyperlinks(); setControl(compositeContainer); } private void addProxySection() { proxyExpComposite = toolkit.createExpandableComposite(compositeContainer, Section.COMPACT | Section.TWISTIE | Section.TITLE_BAR); proxyExpComposite.clientVerticalSpacing = 0; GridData gridData_2 = new GridData(SWT.FILL, SWT.FILL, true, false); gridData_2.horizontalIndent = -5; proxyExpComposite.setLayoutData(gridData_2); proxyExpComposite.setFont(compositeContainer.getFont()); proxyExpComposite.setBackground(compositeContainer.getBackground()); proxyExpComposite.setText("Proxy Server Configuration"); proxyExpComposite.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent e) { getControl().getShell().pack(); } }); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(proxyExpComposite); proxyAuthComp = toolkit.createComposite(proxyExpComposite, SWT.NONE); GridLayout gridLayout2 = new GridLayout(); gridLayout2.numColumns = 2; gridLayout2.verticalSpacing = 0; proxyAuthComp.setLayout(gridLayout2); proxyAuthComp.setBackground(compositeContainer.getBackground()); proxyExpComposite.setClient(proxyAuthComp); Composite settingsComposite = new Composite(proxyAuthComp, SWT.NULL); GridLayout gridLayout3 = new GridLayout(); gridLayout3.numColumns = 2; gridLayout3.verticalSpacing = 0; settingsComposite.setLayout(gridLayout3); systemProxyButton = new Button(settingsComposite, SWT.CHECK); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.TOP).span(2, SWT.DEFAULT).applyTo(settingsComposite); systemProxyButton.setText("Use global Network Connections preferences"); Hyperlink changeProxySettingsLink = toolkit.createHyperlink(settingsComposite, "Change Settings", SWT.NULL); changeProxySettingsLink.setBackground(compositeContainer.getBackground()); changeProxySettingsLink.addHyperlinkListener(new IHyperlinkListener() { public void linkActivated(HyperlinkEvent e) { ProxyPreferencePage page = new ProxyPreferencePage(); page.init(PlatformUI.getWorkbench()); TasksUiUtil.showPreferencePage(PREFS_PAGE_ID_NET_PROXY, page); } public void linkEntered(HyperlinkEvent e) { // ignore } public void linkExited(HyperlinkEvent e) { // ignore } }); systemProxyButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { setUseDefaultProxy(systemProxyButton.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) { // ignore } }); proxyHostnameEditor = new StringFieldEditor("", "Proxy host address: ", StringFieldEditor.UNLIMITED, proxyAuthComp) { @Override protected boolean doCheckState() { return true; } @Override protected void valueChanged() { super.valueChanged(); if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } }; proxyHostnameEditor.setStringValue(oldProxyHostname); proxyPortEditor = new RepositoryStringFieldEditor("", "Proxy host port: ", StringFieldEditor.UNLIMITED, proxyAuthComp); proxyPortEditor.setStringValue(oldProxyPort); proxyHostnameEditor.setEnabled(systemProxyButton.getSelection(), proxyAuthComp); proxyPortEditor.setEnabled(systemProxyButton.getSelection(), proxyAuthComp); proxyAuthButton = new Button(proxyAuthComp, SWT.CHECK); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.TOP).span(2, SWT.DEFAULT).applyTo(proxyAuthButton); proxyAuthButton.setText("Enable proxy authentication"); proxyAuthButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { setProxyAuth(proxyAuthButton.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) { // ignore } }); proxyUserNameEditor = new StringFieldEditor("", "User ID: ", StringFieldEditor.UNLIMITED, proxyAuthComp) { @Override protected boolean doCheckState() { return true; } @Override protected void valueChanged() { super.valueChanged(); if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } }; proxyPasswordEditor = new RepositoryStringFieldEditor("", "Password: ", StringFieldEditor.UNLIMITED, proxyAuthComp); ((RepositoryStringFieldEditor) proxyPasswordEditor).getTextControl().setEchoChar('*'); // proxyPasswordEditor.setEnabled(httpAuthButton.getSelection(), // advancedComp); // ((StringFieldEditor) // httpAuthPasswordEditor).setEnabled(httpAuthButton.getSelection(), // advancedComp); setProxyAuth(oldProxyUsername != null && oldProxyPassword != null && !oldProxyUsername.equals("") && !oldProxyPassword.equals("")); setUseDefaultProxy(repository != null ? repository.useDefaultProxy() : true); proxyExpComposite.setExpanded(!systemProxyButton.getSelection()); } protected void setEncoding(String encoding) { if (encoding.equals(TaskRepository.DEFAULT_CHARACTER_ENCODING)) { setDefaultEncoding(); } else { if (otherEncodingCombo.indexOf(encoding) != -1) { defaultEncoding.setSelection(false); otherEncodingCombo.setEnabled(true); otherEncoding.setSelection(true); otherEncodingCombo.select(otherEncodingCombo.indexOf(encoding)); } else { setDefaultEncoding(); } } } private void setDefaultEncoding() { defaultEncoding.setSelection(true); otherEncoding.setSelection(false); otherEncodingCombo.setEnabled(false); if (otherEncodingCombo.getItemCount() > 0) { otherEncodingCombo.select(0); } } public void setAnonymous(boolean selected) { if (!needsAnonymousLogin) { return; } anonymousButton.setSelection(selected); if (selected) { oldUsername = repositoryUserNameEditor.getStringValue(); oldPassword = (repositoryPasswordEditor).getStringValue(); repositoryUserNameEditor.setStringValue(""); (repositoryPasswordEditor).setStringValue(""); } else { repositoryUserNameEditor.setStringValue(oldUsername); (repositoryPasswordEditor).setStringValue(oldPassword); } repositoryUserNameEditor.setEnabled(!selected, compositeContainer); repositoryPasswordEditor.setEnabled(!selected, compositeContainer); if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } public void setHttpAuth(boolean selected) { if (!needsHttpAuth) { return; } httpAuthButton.setSelection(selected); if (!selected) { oldHttpAuthUserId = httpAuthUserNameEditor.getStringValue(); oldHttpAuthPassword = (httpAuthPasswordEditor).getStringValue(); httpAuthUserNameEditor.setStringValue(null); (httpAuthPasswordEditor).setStringValue(null); } else { httpAuthUserNameEditor.setStringValue(oldHttpAuthUserId); (httpAuthPasswordEditor).setStringValue(oldHttpAuthPassword); } httpAuthUserNameEditor.setEnabled(selected, httpAuthComp); (httpAuthPasswordEditor).setEnabled(selected, httpAuthComp); } public void setUseDefaultProxy(boolean selected) { if (!needsProxy) { return; } systemProxyButton.setSelection(selected); if (selected) { oldProxyHostname = proxyHostnameEditor.getStringValue(); oldProxyPort = proxyPortEditor.getStringValue(); // proxyHostnameEditor.setStringValue(null); // proxyPortEditor.setStringValue(null); } else { proxyHostnameEditor.setStringValue(oldProxyHostname); proxyPortEditor.setStringValue(oldProxyPort); } proxyHostnameEditor.setEnabled(!selected, proxyAuthComp); proxyPortEditor.setEnabled(!selected, proxyAuthComp); proxyAuthButton.setEnabled(!selected); setProxyAuth(proxyAuthButton.getSelection()); } public void setProxyAuth(boolean selected) { proxyAuthButton.setSelection(selected); proxyAuthButton.setEnabled(!systemProxyButton.getSelection()); if (!selected) { oldProxyUsername = proxyUserNameEditor.getStringValue(); oldProxyPassword = (proxyPasswordEditor).getStringValue(); proxyUserNameEditor.setStringValue(null); (proxyPasswordEditor).setStringValue(null); } else { proxyUserNameEditor.setStringValue(oldProxyUsername); proxyPasswordEditor.setStringValue(oldProxyPassword); } proxyUserNameEditor.setEnabled(selected && !systemProxyButton.getSelection(), proxyAuthComp); proxyPasswordEditor.setEnabled(selected && !systemProxyButton.getSelection(), proxyAuthComp); } protected abstract void createAdditionalControls(Composite parent); protected abstract boolean isValidUrl(String name); void updateHyperlinks() { if (getServerUrl() != null && getServerUrl().length() > 0) { TaskRepository repository = createTaskRepository(); String accountCreationUrl = TasksUiPlugin.getRepositoryUi(connector.getRepositoryType()) .getAccountCreationUrl(repository); createAccountHyperlink.setEnabled(accountCreationUrl != null); createAccountHyperlink.setVisible(accountCreationUrl != null); String accountManagementUrl = TasksUiPlugin.getRepositoryUi(connector.getRepositoryType()) .getAccountManagementUrl(repository); manageAccountHyperlink.setEnabled(accountManagementUrl != null); manageAccountHyperlink.setVisible(accountManagementUrl != null); } else { createAccountHyperlink.setEnabled(false); createAccountHyperlink.setVisible(false); manageAccountHyperlink.setEnabled(false); manageAccountHyperlink.setVisible(false); } } public String getRepositoryLabel() { return repositoryLabelEditor.getStringValue(); } public String getServerUrl() { return TaskRepositoryManager.stripSlashes(serverUrlCombo.getText()); } public String getUserName() { return repositoryUserNameEditor.getStringValue(); } public String getPassword() { return repositoryPasswordEditor.getStringValue(); } public String getHttpAuthUserId() { if (needsHttpAuth()) { return httpAuthUserNameEditor.getStringValue(); } else { return ""; } } public String getHttpAuthPassword() { if (needsHttpAuth()) { return httpAuthPasswordEditor.getStringValue(); } else { return ""; } } public String getProxyHostname() { if (needsProxy()) { return proxyHostnameEditor.getStringValue(); } else { return ""; } } public String getProxyPort() { if (needsProxy()) { return proxyPortEditor.getStringValue(); } else { return ""; } } public Boolean getUseDefaultProxy() { if (needsProxy()) { return systemProxyButton.getSelection(); } else { return true; } } public String getProxyUsername() { if (needsProxy()) { return proxyUserNameEditor.getStringValue(); } else { return ""; } } public String getProxyPassword() { if (needsProxy()) { return proxyPasswordEditor.getStringValue(); } else { return ""; } } public void init(IWorkbench workbench) { // ignore } public boolean isAnonymousAccess() { if (anonymousButton != null) { return anonymousButton.getSelection(); } else { return false; } } /** * Exposes StringFieldEditor.refreshValidState() * * TODO: is there a better way? */ private static class RepositoryStringFieldEditor extends StringFieldEditor { public RepositoryStringFieldEditor(String name, String labelText, int style, Composite parent) { super(name, labelText, style, parent); } @Override public void refreshValidState() { try { super.refreshValidState(); } catch (Exception e) { StatusManager.log(e, "problem refreshing password field"); } } @Override public Text getTextControl() { return super.getTextControl(); } } @Override public boolean isPageComplete() { String errorMessage = null; String url = getServerUrl(); errorMessage = isUniqueUrl(url); if (errorMessage == null && !isValidUrl(url)) { errorMessage = "Enter a valid server url"; } if (errorMessage == null) { errorMessage = credentialsComplete(); } setErrorMessage(errorMessage); return errorMessage == null; } private String credentialsComplete() { if ((needsAnonymousLogin() && !anonymousButton.getSelection()) && (repositoryUserNameEditor.getStringValue().trim().equals("") || repositoryPasswordEditor.getStringValue() .trim() .equals(""))) { return "Repository user name and password must not be blank"; } return null; } protected String isUniqueUrl(String urlString) { if (!urlString.equals(originalUrl)) { if (repositoryUrls == null) { List<TaskRepository> repositories = TasksUiPlugin.getRepositoryManager().getAllRepositories(); repositoryUrls = new HashSet<String>(repositories.size()); for (TaskRepository repository : repositories) { repositoryUrls.add(repository.getUrl()); } } if (repositoryUrls.contains(urlString)) { return "Repository already exists."; } } return null; } public void setRepository(TaskRepository repository) { this.repository = repository; } public void setVersion(String previousVersion) { if (previousVersion == null) { serverVersion = TaskRepository.NO_VERSION_SPECIFIED; } else { serverVersion = previousVersion; } } public String getVersion() { return serverVersion; } public TaskRepository getRepository() { return repository; } public String getCharacterEncoding() { if (defaultEncoding == null) { return null; } if (defaultEncoding.getSelection()) { return TaskRepository.DEFAULT_CHARACTER_ENCODING; } else { if (otherEncodingCombo.getSelectionIndex() > -1) { return otherEncodingCombo.getItem(otherEncodingCombo.getSelectionIndex()); } else { return TaskRepository.DEFAULT_CHARACTER_ENCODING; } } } // public String getTimeZoneId() { // return (timeZonesCombo != null) ? // timeZonesCombo.getItem(timeZonesCombo.getSelectionIndex()) : null; public TaskRepository createTaskRepository() { // TaskRepository repository = new // TaskRepository(connector.getRepositoryType(), getServerUrl(), // getVersion(), // getCharacterEncoding(), getTimeZoneId()); TaskRepository repository = new TaskRepository(connector.getRepositoryType(), getServerUrl(), getVersion(), getCharacterEncoding(), ""); repository.setRepositoryLabel(getRepositoryLabel()); repository.setAuthenticationCredentials(getUserName(), getPassword()); if (needsAnonymousLogin()) { repository.setAnonymous(anonymousButton.getSelection()); } // repository.setProperty(TaskRepository.AUTH_HTTP_USERNAME, // getHttpAuthUserId()); // repository.setProperty(TaskRepository.AUTH_HTTP_PASSWORD, // getHttpAuthPassword()); if (getHttpAuthUserId().length() > 0 && getHttpAuthPassword().length() > 0) { repository.setHttpAuthenticationCredentials(getHttpAuthUserId(), getHttpAuthPassword()); } repository.setProperty(TaskRepository.PROXY_USEDEFAULT, String.valueOf(getUseDefaultProxy())); repository.setProperty(TaskRepository.PROXY_HOSTNAME, getProxyHostname()); repository.setProperty(TaskRepository.PROXY_PORT, getProxyPort()); if (getProxyUsername().length() > 0 && getProxyPassword().length() > 0) { repository.setProxyAuthenticationCredentials(getProxyUsername(), getProxyPassword()); } // repository.setProperty(TaskRepository.PROXY_USERNAME, // getProxyUsername()); // repository.setProperty(TaskRepository.PROXY_PASSWORD, // getProxyPassword()); // repository.setProperty(TaskRepository.PROXY_USERNAME, // getHttpAuthUserId()); // repository.setProperty(TaskRepository.PROXY_PASSWORD, // getHttpAuthPassword()); return repository; } public AbstractRepositoryConnector getConnector() { return connector; } public boolean needsEncoding() { return needsEncoding; } public boolean needsTimeZone() { return needsTimeZone; } public boolean needsAnonymousLogin() { return needsAnonymousLogin; } public void setNeedsEncoding(boolean needsEncoding) { this.needsEncoding = needsEncoding; } public void setNeedsTimeZone(boolean needsTimeZone) { this.needsTimeZone = needsTimeZone; } public boolean needsHttpAuth() { return this.needsHttpAuth; } public void setNeedsHttpAuth(boolean needsHttpAuth) { this.needsHttpAuth = needsHttpAuth; } public void setNeedsProxy(boolean needsProxy) { this.needsProxy = needsProxy; } public boolean needsProxy() { return this.needsProxy; } public void setNeedsAnonymousLogin(boolean needsAnonymousLogin) { this.needsAnonymousLogin = needsAnonymousLogin; } public void setNeedsValidation(boolean needsValidation) { this.needsValidation = needsValidation; } public boolean needsValidation() { return needsValidation; } public void updateProperties(TaskRepository repository) { // none } /** for testing */ public void setUrl(String url) { serverUrlCombo.setText(url); } /** for testing */ public void setUserId(String id) { repositoryUserNameEditor.setStringValue(id); } /** for testing */ public void setPassword(String pass) { repositoryPasswordEditor.setStringValue(pass); } protected void validateSettings() { final Validator validator = getValidator(createTaskRepository()); if (validator == null) { return; } try { getWizard().getContainer().run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Validating server settings", IProgressMonitor.UNKNOWN); try { validator.run(monitor); if (validator.getStatus() == null) { validator.setStatus(Status.OK_STATUS); } } catch (CoreException e) { validator.setStatus(e.getStatus()); } catch (Exception e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }); } catch (InvocationTargetException e) { StatusManager.fail(e.getCause(), "Internal error validating repository", true); return; } catch (InterruptedException e) { // canceled return; } applyValidatorResult(validator); getWizard().getContainer().updateButtons(); } protected void applyValidatorResult(Validator validator) { IStatus status = validator.getStatus(); String message = status.getMessage(); if (message == null || message.length() == 0) message = null; switch (status.getSeverity()) { case IStatus.OK: if (status == Status.OK_STATUS) { if (getUserName().length() > 0) { message = "Authentication credentials are valid."; } else { message = "Repository is valid."; } } setMessage(message, WizardPage.INFORMATION); break; case IStatus.INFO: setMessage(message, WizardPage.INFORMATION); break; case IStatus.WARNING: setMessage(message, WizardPage.WARNING); break; default: setMessage(message, WizardPage.ERROR); break; } setErrorMessage(null); } protected abstract Validator getValidator(TaskRepository repository); // public for testing public abstract class Validator { private IStatus status; public abstract void run(IProgressMonitor monitor) throws CoreException; public IStatus getStatus() { return status; } public void setStatus(IStatus status) { this.status = status; } } }
package com.redhat.ceylon.eclipse.code.hover; import static com.redhat.ceylon.eclipse.code.browser.BrowserInformationControl.isAvailable; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.appendParametersDescription; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.getDescriptionFor; import static com.redhat.ceylon.eclipse.code.complete.CompletionUtil.getDefaultValueDescription; import static com.redhat.ceylon.eclipse.code.complete.CompletionUtil.getInitalValueDescription; import static com.redhat.ceylon.eclipse.code.editor.Navigation.gotoNode; import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.addPageEpilog; import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.convertToHTMLContent; import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.insertPageProlog; import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.toHex; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getLabel; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getModuleLabel; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getPackageLabel; import static com.redhat.ceylon.eclipse.code.resolve.JavaHyperlinkDetector.getJavaElement; import static com.redhat.ceylon.eclipse.code.resolve.JavaHyperlinkDetector.gotoJavaNode; import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getModelLoader; import static com.redhat.ceylon.eclipse.util.Highlights.CHARS; import static com.redhat.ceylon.eclipse.util.Highlights.NUMBERS; import static com.redhat.ceylon.eclipse.util.Highlights.STRINGS; import static com.redhat.ceylon.eclipse.util.Highlights.getCurrentThemeColor; import static java.lang.Character.codePointCount; import static java.lang.Float.parseFloat; import static java.lang.Integer.parseInt; import static org.eclipse.jdt.internal.ui.JavaPluginImages.setLocalImageDescriptors; import static org.eclipse.jdt.ui.PreferenceConstants.APPEARANCE_JAVADOC_FONT; import static org.eclipse.ui.ISharedImages.IMG_TOOL_BACK; import static org.eclipse.ui.ISharedImages.IMG_TOOL_BACK_DISABLED; import static org.eclipse.ui.ISharedImages.IMG_TOOL_FORWARD; import static org.eclipse.ui.ISharedImages.IMG_TOOL_FORWARD_DISABLED; import static org.eclipse.ui.PlatformUI.getWorkbench; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.text.javadoc.JavadocContentAccess2; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.text.AbstractReusableInformationControlCreator; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IInputChangedListener; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextHoverExtension; import org.eclipse.jface.text.ITextHoverExtension2; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.LocationEvent; import org.eclipse.swt.browser.LocationListener; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import com.github.rjeschke.txtmark.BlockEmitter; import com.github.rjeschke.txtmark.Configuration; import com.github.rjeschke.txtmark.Configuration.Builder; import com.github.rjeschke.txtmark.Processor; import com.github.rjeschke.txtmark.SpanEmitter; import com.redhat.ceylon.cmr.api.JDKUtils; import com.redhat.ceylon.cmr.api.ModuleSearchResult.ModuleDetails; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.NothingType; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedReference; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Referenceable; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.UnionType; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.model.UnknownType; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.AnonymousAnnotation; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.redhat.ceylon.eclipse.code.browser.BrowserInformationControl; import com.redhat.ceylon.eclipse.code.browser.BrowserInput; import com.redhat.ceylon.eclipse.code.correct.ExtractFunctionProposal; import com.redhat.ceylon.eclipse.code.correct.ExtractValueProposal; import com.redhat.ceylon.eclipse.code.correct.SpecifyTypeProposal; import com.redhat.ceylon.eclipse.code.editor.CeylonEditor; import com.redhat.ceylon.eclipse.code.editor.EditorUtil; import com.redhat.ceylon.eclipse.code.html.HTML; import com.redhat.ceylon.eclipse.code.html.HTMLPrinter; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; import com.redhat.ceylon.eclipse.code.search.FindAssignmentsAction; import com.redhat.ceylon.eclipse.code.search.FindReferencesAction; import com.redhat.ceylon.eclipse.code.search.FindRefinementsAction; import com.redhat.ceylon.eclipse.code.search.FindSubtypesAction; import com.redhat.ceylon.eclipse.core.model.CeylonUnit; import com.redhat.ceylon.eclipse.core.model.JDTModelLoader; import com.redhat.ceylon.eclipse.util.Nodes; public class DocumentationHover implements ITextHover, ITextHoverExtension, ITextHoverExtension2 { private CeylonEditor editor; public DocumentationHover(CeylonEditor editor) { this.editor = editor; } public IRegion getHoverRegion(ITextViewer textViewer, int offset) { IDocument document = textViewer.getDocument(); int start= -2; int end= -1; try { int pos= offset; char c; while (pos >= 0) { c= document.getChar(pos); if (!Character.isJavaIdentifierPart(c)) { break; } --pos; } start= pos; pos= offset; int length= document.getLength(); while (pos < length) { c= document.getChar(pos); if (!Character.isJavaIdentifierPart(c)) { break; } ++pos; } end= pos; } catch (BadLocationException x) { } if (start >= -1 && end > -1) { if (start == offset && end == offset) return new Region(offset, 0); else if (start == offset) return new Region(start, end - start); else return new Region(start + 1, end - start - 1); } return null; } final class CeylonLocationListener implements LocationListener { private final BrowserInformationControl control; CeylonLocationListener(BrowserInformationControl control) { this.control = control; } @Override public void changing(LocationEvent event) { String location = event.location; //necessary for windows environment (fix for blank page) if (!"about:blank".equals(location)) { event.doit= false; } handleLink(location); /*else if (location.startsWith("javadoc:")) { final DocBrowserInformationControlInput input = (DocBrowserInformationControlInput) control.getInput(); int beginIndex = input.getHtml().indexOf("javadoc:")+8; final String handle = input.getHtml().substring(beginIndex, input.getHtml().indexOf("\"",beginIndex)); new Job("Fetching Javadoc") { @Override protected IStatus run(IProgressMonitor monitor) { final IJavaElement elem = JavaCore.create(handle); try { final String javadoc = JavadocContentAccess2.getHTMLContent((IMember) elem, true); if (javadoc!=null) { PlatformUI.getWorkbench().getProgressService() .runInUI(editor.getSite().getWorkbenchWindow(), new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { StringBuilder sb = new StringBuilder(); HTMLPrinter.insertPageProlog(sb, 0, getStyleSheet()); appendJavadoc(elem, javadoc, sb); HTMLPrinter.addPageEpilog(sb); control.setInput(new DocBrowserInformationControlInput(input, null, sb.toString(), 0)); } }, null); } } catch (Exception e) { e.printStackTrace(); } return Status.OK_STATUS; } }.schedule(); }*/ } private void handleLink(String location) { if (location.startsWith("dec:")) { Referenceable target = getLinkedModel(editor, location); if (target!=null) { close(control); //FIXME: should have protocol to hide, rather than dispose gotoDeclaration(editor, target); } } else if (location.startsWith("doc:")) { Referenceable target = getLinkedModel(editor, location); if (target!=null) { control.setInput(getHoverInfo(target, control.getInput(), editor, null)); } } else if (location.startsWith("ref:")) { Referenceable target = getLinkedModel(editor, location); close(control); new FindReferencesAction(editor, (Declaration) target).run(); } else if (location.startsWith("sub:")) { Referenceable target = getLinkedModel(editor, location); close(control); new FindSubtypesAction(editor, (Declaration) target).run(); } else if (location.startsWith("act:")) { Referenceable target = getLinkedModel(editor, location); close(control); new FindRefinementsAction(editor, (Declaration) target).run(); } else if (location.startsWith("ass:")) { Referenceable target = getLinkedModel(editor, location); close(control); new FindAssignmentsAction(editor, (Declaration) target).run(); } else if (location.startsWith("stp:")) { close(control); CompilationUnit rn = editor.getParseController().getRootNode(); Node node = Nodes.findNode(rn, Integer.parseInt(location.substring(4))); SpecifyTypeProposal.createProposal(rn, node, editor) .apply(editor.getParseController().getDocument()); } else if (location.startsWith("exv:")) { close(control); new ExtractValueProposal(editor).apply(editor.getParseController().getDocument()); } else if (location.startsWith("exf:")) { close(control); new ExtractFunctionProposal(editor).apply(editor.getParseController().getDocument()); } } @Override public void changed(LocationEvent event) {} } /** * Action to go back to the previous input in the hover control. */ static final class BackAction extends Action { private final BrowserInformationControl fInfoControl; public BackAction(BrowserInformationControl infoControl) { fInfoControl= infoControl; setText("Back"); ISharedImages images= getWorkbench().getSharedImages(); setImageDescriptor(images.getImageDescriptor(IMG_TOOL_BACK)); setDisabledImageDescriptor(images.getImageDescriptor(IMG_TOOL_BACK_DISABLED)); update(); } @Override public void run() { BrowserInput previous= (BrowserInput) fInfoControl.getInput().getPrevious(); if (previous != null) { fInfoControl.setInput(previous); } } public void update() { BrowserInput current= fInfoControl.getInput(); if (current != null && current.getPrevious() != null) { BrowserInput previous= current.getPrevious(); setToolTipText("Back to " + previous.getInputName()); setEnabled(true); } else { setToolTipText("Back"); setEnabled(false); } } } /** * Action to go forward to the next input in the hover control. */ static final class ForwardAction extends Action { private final BrowserInformationControl fInfoControl; public ForwardAction(BrowserInformationControl infoControl) { fInfoControl= infoControl; setText("Forward"); ISharedImages images= getWorkbench().getSharedImages(); setImageDescriptor(images.getImageDescriptor(IMG_TOOL_FORWARD)); setDisabledImageDescriptor(images.getImageDescriptor(IMG_TOOL_FORWARD_DISABLED)); update(); } @Override public void run() { BrowserInput next= (BrowserInput) fInfoControl.getInput().getNext(); if (next != null) { fInfoControl.setInput(next); } } public void update() { BrowserInput current= fInfoControl.getInput(); if (current != null && current.getNext() != null) { setToolTipText("Forward to " + current.getNext().getInputName()); setEnabled(true); } else { setToolTipText("Forward"); setEnabled(false); } } } /** * Action that shows the current hover contents in the Javadoc view. */ /*private static final class ShowInDocViewAction extends Action { private final BrowserInformationControl fInfoControl; public ShowInJavadocViewAction(BrowserInformationControl infoControl) { fInfoControl= infoControl; setText("Show in Ceylondoc View"); setImageDescriptor(JavaPluginImages.DESC_OBJS_JAVADOCTAG); //TODO: better image } @Override public void run() { DocBrowserInformationControlInput infoInput= (DocBrowserInformationControlInput) fInfoControl.getInput(); //TODO: check cast fInfoControl.notifyDelayedInputChange(null); fInfoControl.dispose(); //FIXME: should have protocol to hide, rather than dispose try { JavadocView view= (JavadocView) JavaPlugin.getActivePage().showView(JavaUI.ID_JAVADOC_VIEW); view.setInput(infoInput); } catch (PartInitException e) { JavaPlugin.log(e); } } }*/ /** * Action that opens the current hover input element. */ final class OpenDeclarationAction extends Action { private final BrowserInformationControl fInfoControl; public OpenDeclarationAction(BrowserInformationControl infoControl) { fInfoControl = infoControl; setText("Open Declaration"); setLocalImageDescriptors(this, "goto_input.gif"); } @Override public void run() { close(fInfoControl); //FIXME: should have protocol to hide, rather than dispose CeylonBrowserInput input = (CeylonBrowserInput) fInfoControl.getInput(); gotoDeclaration(editor, getLinkedModel(editor, input.getAddress())); } } static void gotoDeclaration(CeylonEditor editor, Referenceable model) { CeylonParseController cpc = editor.getParseController(); Node refNode = Nodes.getReferencedNode(model, cpc); if (refNode!=null) { gotoNode(refNode, cpc.getProject(), cpc.getTypeChecker()); } else if (model instanceof Declaration) { gotoJavaNode((Declaration) model, cpc); } } private static void close(BrowserInformationControl control) { control.notifyDelayedInputChange(null); control.dispose(); } /** * The hover control creator. */ private IInformationControlCreator fHoverControlCreator; /** * The presentation control creator. */ private IInformationControlCreator fPresenterControlCreator; private IInformationControlCreator getInformationPresenterControlCreator() { if (fPresenterControlCreator == null) fPresenterControlCreator= new PresenterControlCreator(this); return fPresenterControlCreator; } @Override public IInformationControlCreator getHoverControlCreator() { return getHoverControlCreator("F2 for focus"); } public IInformationControlCreator getHoverControlCreator( String statusLineMessage) { if (fHoverControlCreator == null) { fHoverControlCreator= new HoverControlCreator(this, getInformationPresenterControlCreator(), statusLineMessage); } return fHoverControlCreator; } void addLinkListener(final BrowserInformationControl control) { control.addLocationListener(new CeylonLocationListener(control)); } public static Referenceable getLinkedModel(CeylonEditor editor, String location) { TypeChecker tc = editor.getParseController().getTypeChecker(); String[] bits = location.split(":"); JDTModelLoader modelLoader = getModelLoader(tc); String moduleName = bits[1]; Module module = modelLoader.getLoadedModule(moduleName); if (module==null || bits.length==2) { return module; } Referenceable target = module.getPackage(bits[2]); for (int i=3; i<bits.length; i++) { Scope scope; if (target instanceof Scope) { scope = (Scope) target; } else if (target instanceof TypedDeclaration) { scope = ((TypedDeclaration) target).getType().getDeclaration(); } else { return null; } target = scope.getDirectMember(bits[i], null, false); //TODO: nasty workaround for bug in model loader // where unshared parameters are not getting // persisted as members. Delete: if (target==null && (scope instanceof Functional)) { for (ParameterList pl: ((Functional)scope).getParameterLists()) { for (Parameter p: pl.getParameters()) { if (p!=null && p.getName().equals(bits[i])) { target = p.getModel(); } } } } } return target; } public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { CeylonBrowserInput info = (CeylonBrowserInput) getHoverInfo2(textViewer, hoverRegion); return info!=null ? info.getHtml() : null; } @Override public CeylonBrowserInput getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) { return internalGetHoverInfo(editor, hoverRegion); } static CeylonBrowserInput internalGetHoverInfo(final CeylonEditor editor, IRegion hoverRegion) { if (editor==null || editor.getSelectionProvider()==null) return null; CeylonParseController parseController = editor.getParseController(); if (parseController==null) return null; Tree.CompilationUnit rn = parseController.getRootNode(); if (rn!=null) { int hoffset = hoverRegion.getOffset(); ITextSelection selection = EditorUtil.getSelectionFromThread(editor); if (selection!=null && selection.getOffset()<=hoffset && selection.getOffset()+selection.getLength()>=hoffset) { Node node = Nodes.findNode(rn, selection.getOffset(), selection.getOffset()+selection.getLength()-1); if (node instanceof Tree.Expression) { node = ((Tree.Expression) node).getTerm(); } if (node instanceof Tree.Term) { return getTermTypeHoverInfo(node, selection.getText(), editor.getCeylonSourceViewer().getDocument(), editor.getParseController().getProject()); } } Node node = Nodes.findNode(rn, hoffset); if (node instanceof Tree.ImportPath) { Referenceable r = ((Tree.ImportPath) node).getModel(); if (r!=null) { return getHoverInfo(r, null, editor, node); } } else if (node instanceof Tree.LocalModifier) { return getInferredTypeHoverInfo(node, editor.getParseController().getProject()); } else if (node instanceof Tree.Literal) { return getTermTypeHoverInfo(node, null, editor.getCeylonSourceViewer().getDocument(), editor.getParseController().getProject()); } else { return getHoverInfo(Nodes.getReferencedDeclaration(node), null, editor, node); } } return null; } private static CeylonBrowserInput getInferredTypeHoverInfo(Node node, IProject project) { ProducedType t = ((Tree.LocalModifier) node).getTypeModel(); if (t==null) return null; StringBuilder buffer = new StringBuilder(); HTMLPrinter.insertPageProlog(buffer, 0, HTML.getStyleSheet()); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("types.gif").toExternalForm(), 16, 16, "<b><tt>" + HTML.highlightLine(t.getProducedTypeName()) + "</tt></b>", 20, 4); buffer.append("<hr/>"); if (!t.containsUnknowns()) { buffer.append("One quick assist available:<br/>"); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("correction_change.gif").toExternalForm(), 16, 16, "<a href=\"stp:" + node.getStartIndex() + "\">Specify explicit type</a>", 20, 4); } //buffer.append(getDocumentationFor(editor.getParseController(), t.getDeclaration())); HTMLPrinter.addPageEpilog(buffer); return new CeylonBrowserInput(null, null, buffer.toString()); } private static CeylonBrowserInput getTermTypeHoverInfo(Node node, String selectedText, IDocument doc, IProject project) { ProducedType t = ((Tree.Term) node).getTypeModel(); if (t==null) return null; // String expr = ""; // try { // expr = doc.get(node.getStartIndex(), node.getStopIndex()-node.getStartIndex()+1); // catch (BadLocationException e) { // e.printStackTrace(); StringBuilder buffer = new StringBuilder(); HTMLPrinter.insertPageProlog(buffer, 0, HTML.getStyleSheet()); String desc = node instanceof Tree.Literal ? "literal" : "expression"; HTML.addImageAndLabel(buffer, null, HTML.fileUrl("types.gif").toExternalForm(), 16, 16, "<b><tt>" + HTML.highlightLine(t.getProducedTypeName()) + "</tt> "+desc+"</b>", 20, 4); if (node instanceof Tree.StringLiteral) { buffer.append( "<hr/>") .append("<code style='color:") .append(toHex(getCurrentThemeColor(STRINGS))) .append("'><pre>") .append('\"') .append(convertToHTMLContent(node.getText())) .append('\"') .append("</pre></code>"); // If a single char selection, then append info on that character too if (selectedText != null && codePointCount(selectedText, 0, selectedText.length()) == 1) { appendCharacterHoverInfo(buffer, selectedText); } } else if (node instanceof Tree.CharLiteral) { String character = node.getText(); if (character.length()>2) { appendCharacterHoverInfo(buffer, character.substring(1, character.length()-1)); } } else if (node instanceof Tree.NaturalLiteral) { buffer.append( "<hr/>") .append("<code style='color:") .append(toHex(getCurrentThemeColor(NUMBERS))) .append("'>"); String text = node.getText().replace("_", ""); switch (text.charAt(0)) { case ' buffer.append(parseInt(text.substring(1),16)); break; case '$': buffer.append(parseInt(text.substring(1),2)); break; default: buffer.append(parseInt(text)); } buffer.append("</code>"); } else if (node instanceof Tree.FloatLiteral) { buffer.append( "<hr/>") .append("<code style='color:") .append(toHex(getCurrentThemeColor(NUMBERS))) .append("'>") .append(parseFloat(node.getText().replace("_", ""))) .append("</code>"); } if (selectedText!=null) { buffer.append("<hr/>").append("Two quick assists available:<br/>"); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("change.png").toExternalForm(), 16, 16, "<a href=\"exv:\">Extract value</a>", 20, 4); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("change.png").toExternalForm(), 16, 16, "<a href=\"exf:\">Extract function</a>", 20, 4); buffer.append("<br/>"); } HTMLPrinter.addPageEpilog(buffer); return new CeylonBrowserInput(null, null, buffer.toString()); } private static void appendCharacterHoverInfo(StringBuilder buffer, String character) { buffer.append( "<hr/>") .append("<code style='color:") .append(toHex(getCurrentThemeColor(CHARS))) .append("'>") .append('\'') .append(convertToHTMLContent(character)) .append('\'') .append("</code>"); int codepoint = Character.codePointAt(character, 0); String name = Character.getName(codepoint); buffer.append("<hr/>Unicode Name: <code>").append(name).append("</code>"); String hex = Integer.toHexString(codepoint).toUpperCase(); while (hex.length() < 4) { hex = "0" + hex; } buffer.append("<br/>Codepoint: <code>").append("U+").append(hex).append("</code>"); buffer.append("<br/>General Category: <code>").append(getCodepointGeneralCategoryName(codepoint)).append("</code>"); Character.UnicodeScript script = Character.UnicodeScript.of(codepoint); buffer.append("<br/>Script: <code>").append(script.name()).append("</code>"); Character.UnicodeBlock block = Character.UnicodeBlock.of(codepoint); buffer.append("<br/>Block: <code>").append(block).append("</code><br/>"); } private static String getCodepointGeneralCategoryName(int codepoint) { String gc; switch (Character.getType(codepoint)) { case Character.COMBINING_SPACING_MARK: gc = "Mark, combining spacing"; break; case Character.CONNECTOR_PUNCTUATION: gc = "Punctuation, connector"; break; case Character.CONTROL: gc = "Other, control"; break; case Character.CURRENCY_SYMBOL: gc = "Symbol, currency"; break; case Character.DASH_PUNCTUATION: gc = "Punctuation, dash"; break; case Character.DECIMAL_DIGIT_NUMBER: gc = "Number, decimal digit"; break; case Character.ENCLOSING_MARK: gc = "Mark, enclosing"; break; case Character.END_PUNCTUATION: gc = "Punctuation, close"; break; case Character.FINAL_QUOTE_PUNCTUATION: gc = "Punctuation, final quote"; break; case Character.FORMAT: gc = "Other, format"; break; case Character.INITIAL_QUOTE_PUNCTUATION: gc = "Punctuation, initial quote"; break; case Character.LETTER_NUMBER: gc = "Number, letter"; break; case Character.LINE_SEPARATOR: gc = "Separator, line"; break; case Character.LOWERCASE_LETTER: gc = "Letter, lowercase"; break; case Character.MATH_SYMBOL: gc = "Symbol, math"; break; case Character.MODIFIER_LETTER: gc = "Letter, modifier"; break; case Character.MODIFIER_SYMBOL: gc = "Symbol, modifier"; break; case Character.NON_SPACING_MARK: gc = "Mark, nonspacing"; break; case Character.OTHER_LETTER: gc = "Letter, other"; break; case Character.OTHER_NUMBER: gc = "Number, other"; break; case Character.OTHER_PUNCTUATION: gc = "Punctuation, other"; break; case Character.OTHER_SYMBOL: gc = "Symbol, other"; break; case Character.PARAGRAPH_SEPARATOR: gc = "Separator, paragraph"; break; case Character.PRIVATE_USE: gc = "Other, private use"; break; case Character.SPACE_SEPARATOR: gc = "Separator, space"; break; case Character.START_PUNCTUATION: gc = "Punctuation, open"; break; case Character.SURROGATE: gc = "Other, surrogate"; break; case Character.TITLECASE_LETTER: gc = "Letter, titlecase"; break; case Character.UNASSIGNED: gc = "Other, unassigned"; break; case Character.UPPERCASE_LETTER: gc = "Letter, uppercase"; break; default: gc = "&lt;Unknown&gt;"; } return gc; } private static String getIcon(Object obj) { if (obj instanceof Module) { return "jar_l_obj.gif"; } else if (obj instanceof Package) { return "package_obj.gif"; } else if (obj instanceof Declaration) { Declaration dec = (Declaration) obj; if (dec instanceof Class) { return dec.isShared() ? "class_obj.gif" : "innerclass_private_obj.gif"; } else if (dec instanceof Interface) { return dec.isShared() ? "int_obj.gif" : "innerinterface_private_obj.gif"; } else if (dec instanceof TypeAlias|| dec instanceof NothingType) { return "types.gif"; } else if (dec.isParameter()) { if (dec instanceof Method) { return "methpro_obj.gif"; } else { return "field_protected_obj.gif"; } } else if (dec instanceof Method) { return dec.isShared() ? "public_co.gif" : "private_co.gif"; } else if (dec instanceof MethodOrValue) { return dec.isShared() ? "field_public_obj.gif" : "field_private_obj.gif"; } else if (dec instanceof TypeParameter) { return "typevariable_obj.gif"; } } return null; } /** * Computes the hover info. * @param previousInput the previous input, or <code>null</code> * @param node * @param elements the resolved elements * @param editorInputElement the editor input, or <code>null</code> * * @return the HTML hover info for the given element(s) or <code>null</code> * if no information is available * @since 3.4 */ static CeylonBrowserInput getHoverInfo(Referenceable model, BrowserInput previousInput, CeylonEditor editor, Node node) { if (model instanceof Declaration) { Declaration dec = (Declaration) model; return new CeylonBrowserInput(previousInput, dec, getDocumentationFor(editor.getParseController(), dec, node)); } else if (model instanceof Package) { Package dec = (Package) model; return new CeylonBrowserInput(previousInput, dec, getDocumentationFor(editor.getParseController(), dec)); } else if (model instanceof Module) { Module dec = (Module) model; return new CeylonBrowserInput(previousInput, dec, getDocumentationFor(editor.getParseController(), dec)); } else { return null; } } private static void appendJavadoc(IJavaElement elem, StringBuilder sb) { if (elem instanceof IMember) { try { //TODO: Javadoc @ icon? IMember mem = (IMember) elem; String jd = JavadocContentAccess2.getHTMLContent(mem, true); if (jd!=null) { sb.append("<br/>").append(jd); String base = getBaseURL(mem, mem.isBinary()); int endHeadIdx= sb.indexOf("</head>"); sb.insert(endHeadIdx, "\n<base href='" + base + "'>\n"); } } catch (JavaModelException e) { e.printStackTrace(); } } } private static String getBaseURL(IJavaElement element, boolean isBinary) throws JavaModelException { if (isBinary) { // Source attachment usually does not include Javadoc resources // => Always use the Javadoc location as base: URL baseURL= JavaUI.getJavadocLocation(element, false); if (baseURL != null) { if (baseURL.getProtocol().equals("jar")) { // It's a JarURLConnection, which is not known to the browser widget. // Let's start the help web server: URL baseURL2= PlatformUI.getWorkbench().getHelpSystem().resolve(baseURL.toExternalForm(), true); if (baseURL2 != null) { // can be null if org.eclipse.help.ui is not available baseURL= baseURL2; } } return baseURL.toExternalForm(); } } else { IResource resource= element.getResource(); if (resource != null) { IPath location= resource.getLocation(); if (location != null) return location.toFile().toURI().toString(); } } return null; } public static String getDocumentationFor(CeylonParseController cpc, Package pack) { StringBuilder buffer= new StringBuilder(); addMainPackageDescription(pack, buffer); Module mod = addPackageModuleInfo(pack, buffer); addPackageDocumentation(cpc, pack, buffer); addAdditionalPackageInfo(buffer, mod); addPackageMembers(buffer, pack); insertPageProlog(buffer, 0, HTML.getStyleSheet()); addPageEpilog(buffer); return buffer.toString(); } private static void addPackageMembers(StringBuilder buffer, Package pack) { boolean first = true; for (Declaration dec: pack.getMembers()) { if (dec instanceof Class && ((Class)dec).isOverloaded()) { continue; } if (dec.isShared() && !dec.isAnonymous()) { if (first) { buffer.append("<hr/>Contains:&nbsp;&nbsp;"); first = false; } else { buffer.append(", "); } /*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(), 16, 16, "<tt><a " + link(dec) + ">" + dec.getName() + "</a></tt>", 20, 2);*/ buffer.append("<tt><a ") .append(HTML.link(dec)) .append(">") .append(dec.getName()) .append("</a></tt>"); } } if (!first) { buffer.append(".<br/>"); } } private static void addAdditionalPackageInfo(StringBuilder buffer, Module mod) { if (mod.isJava()) { buffer.append("<p>This package is implemented in Java.</p>"); } if (JDKUtils.isJDKModule(mod.getNameAsString())) { buffer.append("<p>This package forms part of the Java SDK.</p>"); } } private static void addMainPackageDescription(Package pack, StringBuilder buffer) { HTML.addImageAndLabel(buffer, pack, HTML.fileUrl(getIcon(pack)).toExternalForm(), 16, 16, "<tt style='font-size:102%'>" + HTML.highlightLine(description(pack)) + "</tt>", 20, 4); buffer.append("<hr/>"); } private static Module addPackageModuleInfo(Package pack, StringBuilder buffer) { Module mod = pack.getModule(); HTML.addImageAndLabel(buffer, mod, HTML.fileUrl(getIcon(mod)).toExternalForm(), 16, 16, "in module&nbsp;&nbsp;<tt><a " + HTML.link(mod) + ">" + getLabel(mod) +"</a></tt>", 20, 2); return mod; } private static void addPackageDocumentation(CeylonParseController cpc, Package pack, StringBuilder buffer) { String packageFileName = pack.getNameAsString().replace('.', '/') + "/package.ceylon"; PhasedUnit pu = cpc.getTypeChecker() .getPhasedUnitFromRelativePath(packageFileName); if (pu!=null) { List<Tree.PackageDescriptor> packageDescriptors = pu.getCompilationUnit().getPackageDescriptors(); if (!packageDescriptors.isEmpty()) { Tree.PackageDescriptor refnode = packageDescriptors.get(0); if (refnode!=null) { appendDocAnnotationContent(refnode.getAnnotationList(), buffer, pack); appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, pack); appendSeeAnnotationContent(refnode.getAnnotationList(), buffer); } } } } private static String description(Package pack) { return "package " + getLabel(pack); } public static String getDocumentationFor(ModuleDetails mod, String version) { return getDocumentationForModule(mod.getName(), version, mod.getDoc()); } public static String getDocumentationForModule(String name, String version, String doc) { StringBuilder buffer= new StringBuilder(); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("jar_l_obj.gif").toExternalForm(), 16, 16, "<b><tt>" + HTML.highlightLine(description(name, version)) + "</tt></b>", 20, 4); buffer.append("<hr/>"); if (doc!=null) { buffer.append(markdown(doc, null, null)); } insertPageProlog(buffer, 0, HTML.getStyleSheet()); addPageEpilog(buffer); return buffer.toString(); } private static String description(String name, String version) { return "module " + name + " \"" + version + "\""; } private static String getDocumentationFor(CeylonParseController cpc, Module mod) { StringBuilder buffer = new StringBuilder(); addMainModuleDescription(mod, buffer); addAdditionalModuleInfo(buffer, mod); addModuleDocumentation(cpc, mod, buffer); addModuleMembers(buffer, mod); insertPageProlog(buffer, 0, HTML.getStyleSheet()); addPageEpilog(buffer); return buffer.toString(); } private static void addAdditionalModuleInfo(StringBuilder buffer, Module mod) { if (mod.isJava()) { buffer.append("<p>This module is implemented in Java.</p>"); } if (mod.isDefault()) { buffer.append("<p>The default module for packages which do not belong to explicit module.</p>"); } if (JDKUtils.isJDKModule(mod.getNameAsString())) { buffer.append("<p>This module forms part of the Java SDK.</p>"); } } private static void addMainModuleDescription(Module mod, StringBuilder buffer) { HTML.addImageAndLabel(buffer, mod, HTML.fileUrl(getIcon(mod)).toExternalForm(), 16, 16, "<tt style='font-size:102%'>" + HTML.highlightLine(description(mod)) + "</tt>", 20, 4); buffer.append("<hr/>"); } private static void addModuleDocumentation(CeylonParseController cpc, Module mod, StringBuilder buffer) { Unit unit = mod.getUnit(); PhasedUnit pu = null; if (unit instanceof CeylonUnit) { pu = ((CeylonUnit)unit).getPhasedUnit(); } if (pu!=null) { List<Tree.ModuleDescriptor> moduleDescriptors = pu.getCompilationUnit().getModuleDescriptors(); if (!moduleDescriptors.isEmpty()) { Tree.ModuleDescriptor refnode = moduleDescriptors.get(0); if (refnode!=null) { Scope linkScope = mod.getPackage(mod.getNameAsString()); appendDocAnnotationContent(refnode.getAnnotationList(), buffer, linkScope); appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, linkScope); appendSeeAnnotationContent(refnode.getAnnotationList(), buffer); } } } } private static void addModuleMembers(StringBuilder buffer, Module mod) { boolean first = true; for (Package pack: mod.getPackages()) { if (pack.isShared()) { if (first) { buffer.append("<hr/>Contains:&nbsp;&nbsp;"); first = false; } else { buffer.append(", "); } /*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(), 16, 16, "<tt><a " + link(dec) + ">" + dec.getName() + "</a></tt>", 20, 2);*/ buffer.append("<tt><a ") .append(HTML.link(pack)) .append(">") .append(pack.getNameAsString()) .append("</a></tt>"); } } if (!first) { buffer.append(".<br/>"); } } private static String description(Module mod) { return "module " + getLabel(mod) + " \"" + mod.getVersion() + "\""; } public static String getDocumentationFor(CeylonParseController cpc, Declaration dec) { return getDocumentationFor(cpc, dec, null); } private static String getDocumentationFor(CeylonParseController cpc, Declaration dec, Node node) { if (dec==null) return null; StringBuilder buffer = new StringBuilder(); insertPageProlog(buffer, 0, HTML.getStyleSheet()); addMainDescription(buffer, dec, node, cpc); addContainerInfo(dec, node, buffer); boolean hasDoc = addDoc(cpc, dec, node, buffer); boolean obj = addInheritanceInfo(dec, buffer); addRefinementInfo(cpc, dec, node, buffer, hasDoc); addReturnType(dec, buffer, node, obj); addParameters(cpc, dec, node, buffer); addClassMembersInfo(dec, buffer); if (dec instanceof NothingType) { addNothingTypeInfo(buffer); } else { appendExtraActions(dec, buffer); } addPageEpilog(buffer); return buffer.toString(); } private static void addMainDescription(StringBuilder buffer, Declaration dec, Node node, CeylonParseController cpc) { HTML.addImageAndLabel(buffer, dec, HTML.fileUrl(getIcon(dec)).toExternalForm(), 16, 16, "<tt style='font-size:102%'>" + (dec.isDeprecated() ? "<s>":"") + HTML.highlightLine(description(dec, node, cpc)) + (dec.isDeprecated() ? "</s>":"") + "</tt>", 20, 4); buffer.append("<hr/>"); } private static void addClassMembersInfo(Declaration dec, StringBuilder buffer) { if (dec instanceof ClassOrInterface) { if (!dec.getMembers().isEmpty()) { boolean first = true; for (Declaration mem: dec.getMembers()) { if (mem instanceof Method && ((Method)mem).isOverloaded()) { continue; } if (mem.isShared() && !dec.isAnonymous()) { if (first) { buffer.append("<hr/>Members:&nbsp;&nbsp;"); first = false; } else { buffer.append(", "); } /*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(), 16, 16, "<tt><a " + link(dec) + ">" + dec.getName() + "</a></tt>", 20, 2);*/ buffer.append("<tt><a ") .append(HTML.link(mem)) .append(">") .append(mem.getName()) .append("</a></tt>"); } } if (!first) { buffer.append(".<br/>"); //extraBreak = true; } } } } private static void addNothingTypeInfo(StringBuilder buffer) { buffer.append("Special bottom type defined by the language. " + "<code>Nothing</code> is assignable to all types, but has no value. " + "A function or value of type <code>Nothing</code> either throws " + "an exception, or never returns."); } private static boolean addInheritanceInfo(Declaration dec, StringBuilder buffer) { //boolean extraBreak = false; boolean obj=false; if (dec instanceof TypedDeclaration) { TypeDeclaration td = ((TypedDeclaration) dec).getTypeDeclaration(); if (td!=null && td.isAnonymous()) { obj=true; documentInheritance(td, buffer); } } else if (dec instanceof TypeDeclaration) { documentInheritance((TypeDeclaration) dec, buffer); } return obj; } private static void addRefinementInfo(CeylonParseController cpc, Declaration dec, Node node, StringBuilder buffer, boolean hasDoc) { Declaration rd = dec.getRefinedDeclaration(); if (dec!=rd) { buffer.append("<p>"); TypeDeclaration superclass = (TypeDeclaration) rd.getContainer(); ClassOrInterface outer = (ClassOrInterface) dec.getContainer(); ProducedType sup = getQualifyingType(node, outer).getSupertype(superclass); String qualifyingType = sup.getProducedTypeName(); HTML.addImageAndLabel(buffer, rd, HTML.fileUrl(rd.isFormal() ? "implm_co.gif" : "over_co.gif").toExternalForm(), 16, 16, "refines&nbsp;&nbsp;<tt><a " + HTML.link(rd) + ">" + rd.getName() +"</a></tt>&nbsp;&nbsp;declared by&nbsp;&nbsp;<tt>" + convertToHTMLContent(qualifyingType) + "</tt>", 20, 2); buffer.append("</p>"); if (!hasDoc) { Tree.Declaration refnode2 = (Tree.Declaration) Nodes.getReferencedNode(rd, cpc); if (refnode2!=null) { appendDocAnnotationContent(refnode2.getAnnotationList(), buffer, resolveScope(rd)); } } } } private static void addParameters(CeylonParseController cpc, Declaration dec, Node node, StringBuilder buffer) { if (dec instanceof Functional) { ProducedReference ptr = getProducedReference(dec, node); for (ParameterList pl: ((Functional) dec).getParameterLists()) { if (!pl.getParameters().isEmpty()) { buffer.append("<p>"); for (Parameter p: pl.getParameters()) { StringBuilder params = new StringBuilder(); appendParametersDescription(p.getModel(), params, cpc); String def = getDefaultValueDescription(p, cpc); StringBuilder doc = new StringBuilder(); Tree.Declaration refNode = (Tree.Declaration) Nodes.getReferencedNode(p.getModel(), cpc); if (refNode!=null) { appendDocAnnotationContent(refNode.getAnnotationList(), doc, resolveScope(dec)); } ProducedType type = ptr.getTypedParameter(p).getFullType(); if (type==null) type = new UnknownType(dec.getUnit()).getType(); HTML.addImageAndLabel(buffer, p.getModel(), HTML.fileUrl("methpro_obj.gif").toExternalForm(), 16, 16, "accepts&nbsp;&nbsp;<tt><a " + HTML.link(type.getDeclaration()) + ">" + convertToHTMLContent(type.getProducedTypeName()) + "</a>&nbsp;<a " + HTML.link(p.getModel()) + ">"+ p.getName() + convertToHTMLContent(params.toString()) + "</a>" + convertToHTMLContent(def) + "</tt>" + doc, 20, 2); } buffer.append("</p>"); } } } } private static void addReturnType(Declaration dec, StringBuilder buffer, Node node, boolean obj) { if (dec instanceof TypedDeclaration && !obj) { ProducedType ret = getProducedReference(dec, node).getType(); if (ret!=null) { buffer.append("<p>"); List<ProducedType> list; if (ret.getDeclaration() instanceof UnionType) { list = ret.getDeclaration().getCaseTypes(); } else { list = Arrays.asList(ret); } StringBuilder buf = new StringBuilder("returns&nbsp;&nbsp;<tt>"); for (ProducedType pt: list) { if (pt.getDeclaration() instanceof ClassOrInterface || pt.getDeclaration() instanceof TypeParameter) { buf.append("<a " + HTML.link(pt.getDeclaration()) + ">" + convertToHTMLContent(pt.getProducedTypeName()) +"</a>"); } else { buf.append(convertToHTMLContent(pt.getProducedTypeName())); } buf.append("|"); } buf.setLength(buf.length()-1); buf.append("</tt>"); HTML.addImageAndLabel(buffer, ret.getDeclaration(), HTML.fileUrl("stepreturn_co.gif").toExternalForm(), 16, 16, buf.toString(), 20, 2); buffer.append("</p>"); } } } private static ProducedReference getProducedReference(Declaration dec, Node node) { if (node instanceof Tree.MemberOrTypeExpression) { return ((Tree.MemberOrTypeExpression) node).getTarget(); } ClassOrInterface outer = dec.isClassOrInterfaceMember() ? (ClassOrInterface) dec.getContainer() : null; return dec.getProducedReference(getQualifyingType(node, outer), Collections.<ProducedType>emptyList()); } private static boolean addDoc(CeylonParseController cpc, Declaration dec, Node node, StringBuilder buffer) { boolean hasDoc = false; Node rn = Nodes.getReferencedNode(dec, cpc); if (rn instanceof Tree.Declaration) { Tree.Declaration refnode = (Tree.Declaration) rn; appendDeprecatedAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec)); int len = buffer.length(); appendDocAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec)); hasDoc = buffer.length()!=len; appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec)); appendSeeAnnotationContent(refnode.getAnnotationList(), buffer); } appendJavadoc(dec, cpc.getProject(), buffer, node); return hasDoc; } private static void addContainerInfo(Declaration dec, Node node, StringBuilder buffer) { Package pack = dec.getUnit().getPackage(); if (dec.isParameter()) { Declaration pd = ((MethodOrValue) dec).getInitializerParameter() .getDeclaration(); HTML.addImageAndLabel(buffer, pd, HTML.fileUrl(getIcon(pd)).toExternalForm(), 16, 16, "parameter of&nbsp;&nbsp;<tt><a " + HTML.link(pd) + ">" + pd.getName() +"</a></tt>", 20, 2); } else if (dec instanceof TypeParameter) { Declaration pd = ((TypeParameter) dec).getDeclaration(); HTML.addImageAndLabel(buffer, pd, HTML.fileUrl(getIcon(pd)).toExternalForm(), 16, 16, "type parameter of&nbsp;&nbsp;<tt><a " + HTML.link(pd) + ">" + pd.getName() +"</a></tt>", 20, 2); } else { if (dec.isClassOrInterfaceMember()) { ClassOrInterface outer = (ClassOrInterface) dec.getContainer(); ProducedType qt = getQualifyingType(node, outer); if (qt!=null) { String qualifyingType = qt.getProducedTypeName(); HTML.addImageAndLabel(buffer, outer, HTML.fileUrl(getIcon(outer)).toExternalForm(), 16, 16, "member of&nbsp;&nbsp;<tt><a " + HTML.link(outer) + ">" + convertToHTMLContent(qualifyingType) + "</a></tt>", 20, 2); } } if ((dec.isShared() || dec.isToplevel()) && !(dec instanceof NothingType)) { String label; if (pack.getNameAsString().isEmpty()) { label = "in default package"; } else { label = "in package&nbsp;&nbsp;<tt><a " + HTML.link(pack) + ">" + getPackageLabel(dec) +"</a></tt>"; } HTML.addImageAndLabel(buffer, pack, HTML.fileUrl(getIcon(pack)).toExternalForm(), 16, 16, label, 20, 2); Module mod = pack.getModule(); HTML.addImageAndLabel(buffer, mod, HTML.fileUrl(getIcon(mod)).toExternalForm(), 16, 16, "in module&nbsp;&nbsp;<tt><a " + HTML.link(mod) + ">" + getModuleLabel(dec) +"</a></tt>", 20, 2); } } } private static ProducedType getQualifyingType(Node node, ClassOrInterface outer) { if (outer == null) { return null; } if (node instanceof Tree.MemberOrTypeExpression) { ProducedReference pr = ((Tree.MemberOrTypeExpression) node).getTarget(); if (pr!=null) { return pr.getQualifyingType(); } } return outer.getType(); } private static void appendExtraActions(Declaration dec, StringBuilder buffer) { buffer.append("<hr/>"); String unitName = null; if (dec.getUnit() instanceof CeylonUnit) { // Manage the case of CeylonBinaryUnit : getFileName() would return the class file name. // but getCeylonFileName() will return the ceylon source file name if any. unitName = ((CeylonUnit)dec.getUnit()).getCeylonFileName(); } if (unitName == null) { unitName = dec.getUnit().getFilename(); } HTML.addImageAndLabel(buffer, null, HTML.fileUrl("unit.gif").toExternalForm(), 16, 16, "<a href='dec:" + HTML.declink(dec) + "'>declared</a> in unit&nbsp;&nbsp;<tt>"+ unitName + "</tt>", 20, 2); buffer.append("<hr/>"); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("search_ref_obj.png").toExternalForm(), 16, 16, "<a href='ref:" + HTML.declink(dec) + "'>find references</a> to&nbsp;&nbsp;<tt>" + dec.getName() + "</tt>", 20, 2); if (dec instanceof ClassOrInterface) { HTML.addImageAndLabel(buffer, null, HTML.fileUrl("search_decl_obj.png").toExternalForm(), 16, 16, "<a href='sub:" + HTML.declink(dec) + "'>find subtypes</a> of&nbsp;&nbsp;<tt>" + dec.getName() + "</tt>", 20, 2); } if (dec instanceof Value) { HTML.addImageAndLabel(buffer, null, HTML.fileUrl("search_ref_obj.png").toExternalForm(), 16, 16, "<a href='ass:" + HTML.declink(dec) + "'>find assignments</a> to&nbsp;&nbsp;<tt>" + dec.getName() + "</tt>", 20, 2); } if (dec.isFormal()||dec.isDefault()) { HTML.addImageAndLabel(buffer, null, HTML.fileUrl("search_decl_obj.png").toExternalForm(), 16, 16, "<a href='act:" + HTML.declink(dec) + "'>find refinements</a> of&nbsp;&nbsp;<tt>" + dec.getName() + "</tt>", 20, 2); } } private static void documentInheritance(TypeDeclaration dec, StringBuilder buffer) { if (dec instanceof Class) { ProducedType sup = ((Class) dec).getExtendedType(); if (sup!=null) { buffer.append("<p>"); HTML.addImageAndLabel(buffer, sup.getDeclaration(), HTML.fileUrl("super_co.gif").toExternalForm(), 16, 16, "extends <tt><a " + HTML.link(sup.getDeclaration()) + ">" + convertToHTMLContent(sup.getProducedTypeName()) +"</a></tt>", 20, 2); buffer.append("</p>"); //extraBreak = true; } } // if (dec instanceof TypeDeclaration) { List<ProducedType> sts = ((TypeDeclaration) dec).getSatisfiedTypes(); if (!sts.isEmpty()) { buffer.append("<p>"); for (ProducedType td: sts) { HTML.addImageAndLabel(buffer, td.getDeclaration(), HTML.fileUrl("super_co.gif").toExternalForm(), 16, 16, "satisfies <tt><a " + HTML.link(td.getDeclaration()) + ">" + convertToHTMLContent(td.getProducedTypeName()) +"</a></tt>", 20, 2); //extraBreak = true; } buffer.append("</p>"); } List<ProducedType> cts = ((TypeDeclaration) dec).getCaseTypes(); if (cts!=null) { buffer.append("<p>"); for (ProducedType td: cts) { HTML.addImageAndLabel(buffer, td.getDeclaration(), HTML.fileUrl("sub_co.gif").toExternalForm(), 16, 16, (td.getDeclaration().isSelfType() ? "has self type" : "has case") + " <tt><a " + HTML.link(td.getDeclaration()) + ">" + convertToHTMLContent(td.getProducedTypeName()) +"</a></tt>", 20, 2); //extraBreak = true; } buffer.append("</p>"); } } private static String description(Declaration dec, Node node, CeylonParseController cpc) { ProducedReference pr = getProducedReference(dec, node); String result = node==null ? getDescriptionFor(dec, pr, dec.getUnit()) : getDescriptionFor(dec, pr, node.getUnit()); if (dec instanceof TypeDeclaration) { TypeDeclaration td = (TypeDeclaration) dec; if (td.isAlias() && td.getExtendedType()!=null) { result += " => "; result += td.getExtendedType().getProducedTypeName(); } } else if (dec instanceof Value) { if (!((Value) dec).isVariable()) { result += getInitalValueDescription(dec, cpc); } } /*else if (dec instanceof ValueParameter) { Tree.Declaration refnode = (Tree.Declaration) getReferencedNode(dec, cpc); if (refnode instanceof Tree.ValueParameterDeclaration) { Tree.DefaultArgument da = ((Tree.ValueParameterDeclaration) refnode).getDefaultArgument(); if (da!=null) { Tree.Expression e = da.getSpecifierExpression().getExpression(); if (e!=null) { Tree.Term term = e.getTerm(); if (term instanceof Tree.Literal) { result += " = "; result += term.getText(); } else { result += " ="; } } } } }*/ return result; } private static void appendJavadoc(Declaration model, IProject project, StringBuilder buffer, Node node) { IJavaProject jp = JavaCore.create(project); if (jp!=null) { try { appendJavadoc(getJavaElement(model, jp, node), buffer); } catch (JavaModelException jme) { jme.printStackTrace(); } } } private static void appendDocAnnotationContent(Tree.AnnotationList annotationList, StringBuilder documentation, Scope linkScope) { if (annotationList!=null) { AnonymousAnnotation aa = annotationList.getAnonymousAnnotation(); if (aa!=null) { documentation.append(markdown(aa.getStringLiteral().getText(), linkScope, annotationList.getUnit())); } for (Tree.Annotation annotation : annotationList.getAnnotations()) { Tree.Primary annotPrim = annotation.getPrimary(); if (annotPrim instanceof Tree.BaseMemberExpression) { String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText(); if ("doc".equals(name)) { Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList(); if (argList!=null) { List<Tree.PositionalArgument> args = argList.getPositionalArguments(); if (!args.isEmpty()) { Tree.PositionalArgument a = args.get(0); if (a instanceof Tree.ListedArgument) { String text = ((Tree.ListedArgument) a).getExpression() .getTerm().getText(); if (text!=null) { documentation.append(markdown(text, linkScope, annotationList.getUnit())); } } } } } } } } } private static void appendDeprecatedAnnotationContent(Tree.AnnotationList annotationList, StringBuilder documentation, Scope linkScope) { if (annotationList!=null) { for (Tree.Annotation annotation : annotationList.getAnnotations()) { Tree.Primary annotPrim = annotation.getPrimary(); if (annotPrim instanceof Tree.BaseMemberExpression) { String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText(); if ("deprecated".equals(name)) { Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList(); if (argList!=null) { List<Tree.PositionalArgument> args = argList.getPositionalArguments(); if (!args.isEmpty()) { Tree.PositionalArgument a = args.get(0); if (a instanceof Tree.ListedArgument) { String text = ((Tree.ListedArgument) a).getExpression() .getTerm().getText(); if (text!=null) { documentation.append(markdown("_(This is a deprecated program element.)_\n\n" + text, linkScope, annotationList.getUnit())); } } } } } } } } } private static void appendSeeAnnotationContent(Tree.AnnotationList annotationList, StringBuilder documentation) { if (annotationList!=null) { for (Tree.Annotation annotation : annotationList.getAnnotations()) { Tree.Primary annotPrim = annotation.getPrimary(); if (annotPrim instanceof Tree.BaseMemberExpression) { String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText(); if ("see".equals(name)) { Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList(); if (argList!=null) { List<Tree.PositionalArgument> args = argList.getPositionalArguments(); for (Tree.PositionalArgument arg: args) { if (arg instanceof Tree.ListedArgument) { Tree.Term term = ((Tree.ListedArgument) arg).getExpression().getTerm(); if (term instanceof Tree.MetaLiteral) { Declaration dec = ((Tree.MetaLiteral) term).getDeclaration(); if (dec!=null) { String dn = dec.getName(); if (dec.isClassOrInterfaceMember()) { dn = ((ClassOrInterface) dec.getContainer()).getName() + "." + dn; } HTML.addImageAndLabel(documentation, dec, HTML.fileUrl("link_obj.gif"/*getIcon(dec)*/).toExternalForm(), 16, 16, "see <tt><a "+HTML.link(dec)+">"+dn+"</a></tt>", 20, 2); } } } } } } } } } } private static void appendThrowAnnotationContent(Tree.AnnotationList annotationList, StringBuilder documentation, Scope linkScope) { if (annotationList!=null) { for (Tree.Annotation annotation : annotationList.getAnnotations()) { Tree.Primary annotPrim = annotation.getPrimary(); if (annotPrim instanceof Tree.BaseMemberExpression) { String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText(); if ("throws".equals(name)) { Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList(); if (argList!=null) { List<Tree.PositionalArgument> args = argList.getPositionalArguments(); if (args.isEmpty()) continue; Tree.PositionalArgument typeArg = args.get(0); Tree.PositionalArgument textArg = args.size()>1 ? args.get(1) : null; if (typeArg instanceof Tree.ListedArgument && (textArg==null || textArg instanceof Tree.ListedArgument)) { Tree.Term typeArgTerm = ((Tree.ListedArgument) typeArg).getExpression().getTerm(); Tree.Term textArgTerm = textArg==null ? null : ((Tree.ListedArgument) textArg).getExpression().getTerm(); String text = textArgTerm instanceof Tree.StringLiteral ? textArgTerm.getText() : ""; if (typeArgTerm instanceof Tree.MetaLiteral) { Declaration dec = ((Tree.MetaLiteral) typeArgTerm).getDeclaration(); if (dec!=null) { String dn = dec.getName(); if (typeArgTerm instanceof Tree.QualifiedMemberOrTypeExpression) { Tree.Primary p = ((Tree.QualifiedMemberOrTypeExpression) typeArgTerm).getPrimary(); if (p instanceof Tree.MemberOrTypeExpression) { dn = ((Tree.MemberOrTypeExpression) p).getDeclaration().getName() + "." + dn; } } HTML.addImageAndLabel(documentation, dec, HTML.fileUrl("ihigh_obj.gif"/*getIcon(dec)*/).toExternalForm(), 16, 16, "throws <tt><a "+HTML.link(dec)+">"+dn+"</a></tt>" + markdown(text, linkScope, annotationList.getUnit()), 20, 2); } } } } } } } } } private static String markdown(String text, final Scope linkScope, final Unit unit) { if( text == null || text.length() == 0 ) { return text; } // String unquotedText = text.substring(1, text.length()-1); Builder builder = Configuration.builder().forceExtentedProfile(); builder.setCodeBlockEmitter(new CeylonBlockEmitter()); if (linkScope!=null) { builder.setSpecialLinkEmitter(new SpanEmitter() { @Override public void emitSpan(StringBuilder out, String content) { String linkName; String linkTarget; int indexOf = content.indexOf("|"); if( indexOf == -1 ) { linkName = content; linkTarget = content; } else { linkName = content.substring(0, indexOf); linkTarget = content.substring(indexOf+1, content.length()); } String href = resolveLink(linkTarget, linkScope, unit); if (href != null) { out.append("<a ").append(href).append(">"); } out.append("<code>"); int sep = linkName.indexOf("::"); out.append(sep<0?linkName:linkName.substring(sep+2)); out.append("</code>"); if (href != null) { out.append("</a>"); } } }); } return Processor.process(text, builder.build()); } private static String resolveLink(String linkTarget, Scope linkScope, Unit unit) { String declName; Scope scope = null; int pkgSeparatorIndex = linkTarget.indexOf("::"); if( pkgSeparatorIndex == -1 ) { declName = linkTarget; scope = linkScope; } else { String pkgName = linkTarget.substring(0, pkgSeparatorIndex); declName = linkTarget.substring(pkgSeparatorIndex+2, linkTarget.length()); Module module = resolveModule(linkScope); if( module != null ) { scope = module.getPackage(pkgName); } } if (scope==null || declName == null || "".equals(declName)) { return null; // no point in continuing. Required for non-token auto-complete. } String[] declNames = declName.split("\\."); Declaration decl = scope.getMemberOrParameter(unit, declNames[0], null, false); for (int i=1; i<declNames.length; i++) { if (decl instanceof Scope) { scope = (Scope) decl; decl = scope.getMember(declNames[i], null, false); } else { decl = null; break; } } if (decl != null) { String href = HTML.link(decl); return href; } else { return null; } } private static Scope resolveScope(Declaration decl) { if (decl == null) { return null; } else if (decl instanceof Scope) { return (Scope) decl; } else { return decl.getContainer(); } } private static Module resolveModule(Scope scope) { if (scope == null) { return null; } else if (scope instanceof Package) { return ((Package) scope).getModule(); } else { return resolveModule(scope.getContainer()); } } public static final class CeylonBlockEmitter implements BlockEmitter { @Override public void emitBlock(StringBuilder out, List<String> lines, String meta) { if (!lines.isEmpty()) { out.append("<pre>"); /*if (meta == null || meta.length() == 0) { out.append("<pre>"); } else { out.append("<pre class=\"brush: ").append(meta).append("\">"); }*/ StringBuilder code = new StringBuilder(); for (String s: lines) { code.append(s).append('\n'); } String highlighted; if (meta == null || meta.length() == 0 || "ceylon".equals(meta)) { highlighted = HTML.highlightLine(code.toString()); } else { highlighted = code.toString(); } out.append(highlighted); out.append("</pre>\n"); } } } /** * Creates the "enriched" control. */ private final class PresenterControlCreator extends AbstractReusableInformationControlCreator { private final DocumentationHover docHover; PresenterControlCreator(DocumentationHover docHover) { this.docHover = docHover; } @Override public IInformationControl doCreateInformationControl(Shell parent) { if (isAvailable(parent)) { ToolBarManager tbm = new ToolBarManager(SWT.FLAT); BrowserInformationControl control = new BrowserInformationControl(parent, APPEARANCE_JAVADOC_FONT, tbm); final BackAction backAction = new BackAction(control); backAction.setEnabled(false); tbm.add(backAction); final ForwardAction forwardAction = new ForwardAction(control); tbm.add(forwardAction); forwardAction.setEnabled(false); //final ShowInJavadocViewAction showInJavadocViewAction= new ShowInJavadocViewAction(iControl); //tbm.add(showInJavadocViewAction); final OpenDeclarationAction openDeclarationAction = new OpenDeclarationAction(control); tbm.add(openDeclarationAction); // final SimpleSelectionProvider selectionProvider = new SimpleSelectionProvider(); //TODO: an action to open the generated ceylondoc // from the doc archive, in a browser window /*if (fSite != null) { OpenAttachedJavadocAction openAttachedJavadocAction= new OpenAttachedJavadocAction(fSite); openAttachedJavadocAction.setSpecialSelectionProvider(selectionProvider); openAttachedJavadocAction.setImageDescriptor(DESC_ELCL_OPEN_BROWSER); openAttachedJavadocAction.setDisabledImageDescriptor(DESC_DLCL_OPEN_BROWSER); selectionProvider.addSelectionChangedListener(openAttachedJavadocAction); selectionProvider.setSelection(new StructuredSelection()); tbm.add(openAttachedJavadocAction); }*/ IInputChangedListener inputChangeListener = new IInputChangedListener() { public void inputChanged(Object newInput) { backAction.update(); forwardAction.update(); // if (newInput == null) { // selectionProvider.setSelection(new StructuredSelection()); // else boolean isDeclaration = false; if (newInput instanceof CeylonBrowserInput) { // Object inputElement = ((CeylonBrowserInput) newInput).getInputElement(); // selectionProvider.setSelection(new StructuredSelection(inputElement)); //showInJavadocViewAction.setEnabled(isJavaElementInput); isDeclaration = ((CeylonBrowserInput) newInput).getAddress()!=null; } openDeclarationAction.setEnabled(isDeclaration); } }; control.addInputChangeListener(inputChangeListener); tbm.update(true); docHover.addLinkListener(control); return control; } else { return new DefaultInformationControl(parent, true); } } } private final class HoverControlCreator extends AbstractReusableInformationControlCreator { private final DocumentationHover docHover; private String statusLineMessage; private final IInformationControlCreator enrichedControlCreator; HoverControlCreator(DocumentationHover docHover, IInformationControlCreator enrichedControlCreator, String statusLineMessage) { this.docHover = docHover; this.enrichedControlCreator = enrichedControlCreator; this.statusLineMessage = statusLineMessage; } @Override public IInformationControl doCreateInformationControl(Shell parent) { if (enrichedControlCreator!=null && isAvailable(parent)) { BrowserInformationControl control = new BrowserInformationControl(parent, APPEARANCE_JAVADOC_FONT, statusLineMessage) { @Override public IInformationControlCreator getInformationPresenterControlCreator() { return enrichedControlCreator; } }; if (docHover!=null) { docHover.addLinkListener(control); } return control; } else { return new DefaultInformationControl(parent, statusLineMessage); } } } }
package org.jkiss.dbeaver.ui.dialogs.connection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.struct.DBSObjectFilter; import org.jkiss.dbeaver.model.struct.rdb.DBSCatalog; import org.jkiss.dbeaver.model.struct.rdb.DBSSchema; import org.jkiss.dbeaver.model.struct.rdb.DBSTable; import org.jkiss.dbeaver.registry.DataSourceDescriptor; import org.jkiss.dbeaver.ui.IHelpContextIds; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.controls.CImageCombo; import org.jkiss.dbeaver.ui.dialogs.ActiveWizardPage; import org.jkiss.dbeaver.ui.preferences.PrefPageConnectionTypes; import org.jkiss.utils.CommonUtils; import java.util.ArrayList; import java.util.StringTokenizer; /** * General connection page (common for all connection types) */ class ConnectionPageGeneral extends ActiveWizardPage<ConnectionWizard> { static final Log log = LogFactory.getLog(ConnectionPageGeneral.class); private ConnectionWizard wizard; private DataSourceDescriptor dataSourceDescriptor; private Text connectionNameText; private CImageCombo connectionTypeCombo; private Button savePasswordCheck; private Button autocommit; private Combo isolationLevel; private Combo defaultSchema; private Button showSystemObjects; private Button readOnlyConnection; private Button eventsButton; private Font boldFont; private boolean connectionNameChanged = false; private java.util.List<FilterInfo> filters = new ArrayList<FilterInfo>(); private Group filtersGroup; private boolean activated = false; private java.util.List<DBPTransactionIsolation> supportedLevels = new ArrayList<DBPTransactionIsolation>(); private static class FilterInfo { final Class<?> type; final String title; Link link; DBSObjectFilter filter; private FilterInfo(Class<?> type, String title) { this.type = type; this.title = title; } } ConnectionPageGeneral(ConnectionWizard wizard) { super("newConnectionFinal"); //$NON-NLS-1$ this.wizard = wizard; setTitle(wizard.isNew() ? CoreMessages.dialog_connection_wizard_final_header : "General"); setDescription(CoreMessages.dialog_connection_wizard_final_description); filters.add(new FilterInfo(DBSCatalog.class, CoreMessages.dialog_connection_wizard_final_filter_catalogs)); filters.add(new FilterInfo(DBSSchema.class, CoreMessages.dialog_connection_wizard_final_filter_schemas_users)); filters.add(new FilterInfo(DBSTable.class, CoreMessages.dialog_connection_wizard_final_filter_tables)); } ConnectionPageGeneral(ConnectionWizard wizard, DataSourceDescriptor dataSourceDescriptor) { this(wizard); this.dataSourceDescriptor = dataSourceDescriptor; for (FilterInfo filterInfo : filters) { filterInfo.filter = dataSourceDescriptor.getObjectFilter(filterInfo.type, null, false); } } @Override public void dispose() { UIUtils.dispose(boldFont); super.dispose(); } @Override public void activatePage() { if (connectionNameText != null) { ConnectionPageSettings settings = wizard.getPageSettings(); if (settings != null && connectionNameText != null && (CommonUtils.isEmpty(connectionNameText.getText()) || !connectionNameChanged)) { DBPConnectionInfo connectionInfo = settings.getActiveDataSource().getConnectionInfo(); String newName = dataSourceDescriptor == null ? "" : dataSourceDescriptor.getName(); //$NON-NLS-1$ if (CommonUtils.isEmpty(newName)) { newName = connectionInfo.getDatabaseName(); if (CommonUtils.isEmpty(newName)) { newName = connectionInfo.getHostName(); } if (CommonUtils.isEmpty(newName)) { newName = connectionInfo.getUrl(); } if (CommonUtils.isEmpty(newName)) { newName = CoreMessages.dialog_connection_wizard_final_default_new_connection_name; } StringTokenizer st = new StringTokenizer(newName, "/\\:,?=%$#@!^&*()"); //$NON-NLS-1$ while (st.hasMoreTokens()) { newName = st.nextToken(); } if (!CommonUtils.isEmpty(settings.getDriver().getCategory())) { newName = settings.getDriver().getCategory() + " - " + newName; //$NON-NLS-1$ } else { newName = settings.getDriver().getName() + " - " + newName; //$NON-NLS-1$ } newName = CommonUtils.truncateString(newName, 50); } connectionNameText.setText(newName); connectionNameChanged = false; } } if (dataSourceDescriptor != null) { if (!activated) { // Get settings from data source descriptor connectionTypeCombo.select(dataSourceDescriptor.getConnectionInfo().getConnectionType()); savePasswordCheck.setSelection(dataSourceDescriptor.isSavePassword()); autocommit.setSelection(dataSourceDescriptor.isDefaultAutoCommit()); showSystemObjects.setSelection(dataSourceDescriptor.isShowSystemObjects()); readOnlyConnection.setSelection(dataSourceDescriptor.isConnectionReadOnly()); isolationLevel.add(""); if (dataSourceDescriptor.isConnected()) { isolationLevel.setEnabled(!autocommit.getSelection()); supportedLevels.clear(); DBPTransactionIsolation defaultLevel = dataSourceDescriptor.getDefaultTransactionsIsolation(); for (DBPTransactionIsolation level : CommonUtils.safeCollection(dataSourceDescriptor.getDataSource().getInfo().getSupportedTransactionsIsolation())) { if (!level.isEnabled()) continue; isolationLevel.add(level.getTitle()); supportedLevels.add(level); if (level.equals(defaultLevel)) { isolationLevel.select(isolationLevel.getItemCount() - 1); } } } else { isolationLevel.setEnabled(false); } defaultSchema.setText(CommonUtils.notEmpty(dataSourceDescriptor.getDefaultActiveObject())); activated = true; } } else { if (eventsButton != null) { eventsButton.setFont(getFont()); DataSourceDescriptor dataSource = getWizard().getPageSettings().getActiveDataSource(); for (DBPConnectionEventType eventType : dataSource.getConnectionInfo().getDeclaredEvents()) { if (dataSource.getConnectionInfo().getEvent(eventType).isEnabled()) { eventsButton.setFont(boldFont); break; } } } // Default settings savePasswordCheck.setSelection(true); connectionTypeCombo.select(0); autocommit.setSelection(((DBPConnectionType)connectionTypeCombo.getData(0)).isAutocommit()); showSystemObjects.setSelection(true); readOnlyConnection.setSelection(false); isolationLevel.setEnabled(false); defaultSchema.setText(""); } if (savePasswordCheck != null) { //savePasswordCheck.setEnabled(); } long features = 0; try { features = wizard.getPageSettings().getDriver().getDataSourceProvider().getFeatures(); } catch (DBException e) { log.error("Can't obtain data source provider instance", e); //$NON-NLS-1$ } for (FilterInfo filterInfo : filters) { if (DBSCatalog.class.isAssignableFrom(filterInfo.type)) { enableFilter(filterInfo, (features & DBPDataSourceProvider.FEATURE_CATALOGS) != 0); } else if (DBSSchema.class.isAssignableFrom(filterInfo.type)) { enableFilter(filterInfo, (features & DBPDataSourceProvider.FEATURE_SCHEMAS) != 0); } else { enableFilter(filterInfo, true); } } filtersGroup.layout(); } private void enableFilter(FilterInfo filterInfo, boolean enable) { filterInfo.link.setEnabled(enable); if (enable) { filterInfo.link.setText("<a>" + filterInfo.title + "</a>"); filterInfo.link.setToolTipText(NLS.bind(CoreMessages.dialog_connection_wizard_final_filter_link_tooltip, filterInfo.title)); if (filterInfo.filter != null && !filterInfo.filter.isEmpty()) { filterInfo.link.setFont(boldFont); } else { filterInfo.link.setFont(getFont()); } } else { filterInfo.link.setText(NLS.bind(CoreMessages.dialog_connection_wizard_final_filter_link_not_supported_text, filterInfo.title)); filterInfo.link.setToolTipText(NLS.bind(CoreMessages.dialog_connection_wizard_final_filter_link_not_supported_tooltip, filterInfo.title, wizard.getPageSettings().getDriver().getName())); } } @Override public void deactivatePage() { } @Override public void createControl(Composite parent) { boldFont = UIUtils.makeBoldFont(parent.getFont()); Composite group = new Composite(parent, SWT.NONE); GridLayout gl = new GridLayout(2, false); group.setLayout(gl); String connectionName = dataSourceDescriptor == null ? "" : dataSourceDescriptor.getName(); //$NON-NLS-1$ connectionNameText = UIUtils.createLabelText(group, CoreMessages.dialog_connection_wizard_final_label_connection_name, CommonUtils.toString(connectionName)); connectionNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { connectionNameChanged = true; ConnectionPageGeneral.this.getContainer().updateButtons(); } }); { UIUtils.createControlLabel(group, "Connection type"); Composite ctGroup = UIUtils.createPlaceholder(group, 2, 5); connectionTypeCombo = new CImageCombo(ctGroup, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY); loadConnectionTypes(); connectionTypeCombo.select(0); connectionTypeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DBPConnectionType type = (DBPConnectionType)connectionTypeCombo.getItem(connectionTypeCombo.getSelectionIndex()).getData(); autocommit.setSelection(type.isAutocommit()); } }); Button pickerButton = new Button(ctGroup, SWT.PUSH); pickerButton.setText("Edit"); pickerButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DataSourceDescriptor dataSource = wizard.getPageSettings().getActiveDataSource(); UIUtils.showPreferencesFor( getControl().getShell(), dataSource.getConnectionInfo().getConnectionType(), PrefPageConnectionTypes.PAGE_ID); loadConnectionTypes(); DBPConnectionType connectionType = dataSource.getConnectionInfo().getConnectionType(); connectionTypeCombo.select(connectionType); autocommit.setSelection(connectionType.isAutocommit()); } }); /* UIUtils.createControlLabel(colorGroup, "Custom color"); new CImageCombo(colorGroup, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY); Button pickerButton = new Button(colorGroup, SWT.PUSH); pickerButton.setText("..."); */ } { Composite optionsGroup = new Composite(group, SWT.NONE); gl = new GridLayout(2, true); gl.verticalSpacing = 0; gl.horizontalSpacing = 5; gl.marginHeight = 0; gl.marginWidth = 0; optionsGroup.setLayout(gl); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; optionsGroup.setLayoutData(gd); Composite leftSide = UIUtils.createPlaceholder(optionsGroup, 1, 5); leftSide.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING)); Composite rightSide = UIUtils.createPlaceholder(optionsGroup, 1, 5); rightSide.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING)); { Group securityGroup = UIUtils.createControlGroup(leftSide, CoreMessages.dialog_connection_wizard_final_group_security, 1, GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING, 0); savePasswordCheck = UIUtils.createCheckbox(securityGroup, CoreMessages.dialog_connection_wizard_final_checkbox_save_password_locally, dataSourceDescriptor == null || dataSourceDescriptor.isSavePassword()); savePasswordCheck.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); } { Group txnGroup = UIUtils.createControlGroup(rightSide, "Connection", 2, GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING, 0); autocommit = UIUtils.createCheckbox( txnGroup, CoreMessages.dialog_connection_wizard_final_checkbox_auto_commit, dataSourceDescriptor != null && dataSourceDescriptor.isDefaultAutoCommit()); gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalSpan = 2; autocommit.setLayoutData(gd); autocommit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (dataSourceDescriptor != null && dataSourceDescriptor.isConnected()) { isolationLevel.setEnabled(!autocommit.getSelection()); } } }); isolationLevel = UIUtils.createLabelCombo(txnGroup, "Isolation level", SWT.DROP_DOWN | SWT.READ_ONLY); isolationLevel.setToolTipText( "Default transaction isolation level."); defaultSchema = UIUtils.createLabelCombo(txnGroup, "Default schema/catalog", SWT.DROP_DOWN); defaultSchema.setToolTipText( "Name of schema or catalog which will be set as default."); } { Group miscGroup = UIUtils.createControlGroup( leftSide, CoreMessages.dialog_connection_wizard_final_group_misc, 1, GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL, 0); showSystemObjects = UIUtils.createCheckbox( miscGroup, CoreMessages.dialog_connection_wizard_final_checkbox_show_system_objects, dataSourceDescriptor == null || dataSourceDescriptor.isShowSystemObjects()); showSystemObjects.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); readOnlyConnection = UIUtils.createCheckbox( miscGroup, CoreMessages.dialog_connection_wizard_final_checkbox_connection_readonly, dataSourceDescriptor != null && dataSourceDescriptor.isConnectionReadOnly()); gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); //gd.horizontalSpan = 2; readOnlyConnection.setLayoutData(gd); } { // Filters filtersGroup = UIUtils.createControlGroup( rightSide, CoreMessages.dialog_connection_wizard_final_group_filters, 1, GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL, 0); for (int i = 0; i < filters.size(); i++) { final FilterInfo filterInfo = filters.get(i); filterInfo.link = new Link(filtersGroup,SWT.NONE); filterInfo.link.setText("<a>" + filterInfo.title + "</a>"); filterInfo.link.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { //DBSObjectFilter filter = EditObjectFilterDialog dialog = new EditObjectFilterDialog( getShell(), filterInfo.title, filterInfo.filter != null ? filterInfo.filter : new DBSObjectFilter(), true); if (dialog.open() == IDialogConstants.OK_ID) { filterInfo.filter = dialog.getFilter(); if (filterInfo.filter != null && !filterInfo.filter.isEmpty()) { filterInfo.link.setFont(boldFont); } else { filterInfo.link.setFont(getFont()); } } } }); } } } { //Composite buttonsGroup = UIUtils.createPlaceholder(group, 3); Composite buttonsGroup = new Composite(group, SWT.NONE); gl = new GridLayout(1, false); gl.verticalSpacing = 0; gl.horizontalSpacing = 10; gl.marginHeight = 0; gl.marginWidth = 0; buttonsGroup.setLayout(gl); //buttonsGroup.setLayout(new GridLayout(2, true)); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; buttonsGroup.setLayoutData(gd); if (getWizard().isNew()) { eventsButton = new Button(buttonsGroup, SWT.PUSH); eventsButton.setText("Shell Commands"); eventsButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); eventsButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { configureEvents(); } }); } } setControl(group); UIUtils.setHelp(group, IHelpContextIds.CTX_CON_WIZARD_FINAL); } private void loadConnectionTypes() { connectionTypeCombo.removeAll(); for (DBPConnectionType ct : DBeaverCore.getInstance().getDataSourceProviderRegistry().getConnectionTypes()) { connectionTypeCombo.add(null, ct.getName(), ct.getColor(), ct); } } @Override public boolean isPageComplete() { return connectionNameText != null && !CommonUtils.isEmpty(connectionNameText.getText()); } void saveSettings(DataSourceDescriptor dataSource) { if (dataSourceDescriptor != null && !activated) { // No changes anyway return; } dataSource.setName(connectionNameText.getText()); dataSource.setSavePassword(savePasswordCheck.getSelection()); dataSource.setDefaultAutoCommit(autocommit.getSelection(), true); if (dataSource.isConnected()) { int levelIndex = isolationLevel.getSelectionIndex(); if (levelIndex <= 0) { dataSource.setDefaultTransactionsIsolation(null); } else { dataSource.setDefaultTransactionsIsolation(supportedLevels.get(levelIndex - 1)); } } dataSource.setDefaultActiveObject(defaultSchema.getText()); dataSource.setShowSystemObjects(showSystemObjects.getSelection()); dataSource.setConnectionReadOnly(readOnlyConnection.getSelection()); if (!dataSource.isSavePassword()) { dataSource.resetPassword(); } if (connectionTypeCombo.getSelectionIndex() >= 0) { dataSource.getConnectionInfo().setConnectionType( (DBPConnectionType) connectionTypeCombo.getData(connectionTypeCombo.getSelectionIndex())); } for (FilterInfo filterInfo : filters) { if (filterInfo.filter != null) { dataSource.setObjectFilter(filterInfo.type, null, filterInfo.filter); } } } private void configureEvents() { DataSourceDescriptor dataSource = getWizard().getPageSettings().getActiveDataSource(); EditShellCommandsDialog dialog = new EditShellCommandsDialog( getShell(), dataSource); if (dialog.open() == IDialogConstants.OK_ID) { eventsButton.setFont(getFont()); for (DBPConnectionEventType eventType : dataSource.getConnectionInfo().getDeclaredEvents()) { if (dataSource.getConnectionInfo().getEvent(eventType).isEnabled()) { eventsButton.setFont(boldFont); break; } } } } }
package org.jkiss.dbeaver.ui.editors.sql.indent; import org.eclipse.jface.text.*; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.model.DBPKeywordType; import org.jkiss.dbeaver.model.DBPPreferenceStore; import org.jkiss.dbeaver.model.sql.SQLSyntaxManager; import org.jkiss.dbeaver.ui.editors.sql.SQLPreferenceConstants; import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLPartitionScanner; import org.jkiss.dbeaver.utils.GeneralUtils; import java.util.HashMap; import java.util.Map; public class SQLAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy { private static final Log log = Log.getLog(SQLAutoIndentStrategy.class); private static final int MINIMUM_SOUCE_CODE_LENGTH = 10; private String partitioning; private SQLSyntaxManager syntaxManager; private Map<Integer, String> autoCompletionMap = new HashMap<>(); private String[] delimiters; /** * Creates a new SQL auto indent strategy for the given document partitioning. */ public SQLAutoIndentStrategy(String partitioning, SQLSyntaxManager syntaxManager) { this.partitioning = partitioning; this.syntaxManager = syntaxManager; } @Override public void customizeDocumentCommand(IDocument document, DocumentCommand command) { // Do not check for doit because it is disabled in LinkedModeUI (e.g. when braket triggers position group) // if (!command.doit) { // return; if (command.offset < 0) { return; } if (command.text != null && command.text.length() > MINIMUM_SOUCE_CODE_LENGTH) { if (syntaxManager.getPreferenceStore().getBoolean(SQLPreferenceConstants.SQL_FORMAT_EXTRACT_FROM_SOURCE)) { transformSourceCode(document, command); } } else if (command.length == 0 && command.text != null) { final boolean lineDelimiter = isLineDelimiter(document, command.text); try { boolean isPrevLetter = command.offset > 0 && Character.isJavaIdentifierPart(document.getChar(command.offset - 1)); if (command.offset > 1 && isPrevLetter && (lineDelimiter || (command.text.length() == 1 && !Character.isJavaIdentifierPart(command.text.charAt(0)))) && syntaxManager.getPreferenceStore().getBoolean(SQLPreferenceConstants.SQL_FORMAT_KEYWORD_CASE_AUTO)) { updateKeywordCase(document, command); } } catch (BadLocationException e) { log.debug(e); } if (lineDelimiter) { smartIndentAfterNewLine(document, command); } } } private boolean transformSourceCode(IDocument document, DocumentCommand command) { String sourceCode = command.text; int quoteStart = -1, quoteEnd = -1; for (int i = 0; i < sourceCode.length(); i++) { final char ch = sourceCode.charAt(i); if (ch == '"') { quoteStart = i; break; } else if (Character.isUnicodeIdentifierPart(ch)) { // Letter before quote return false; } } for (int i = sourceCode.length() - 1; i >= 0; i final char ch = sourceCode.charAt(i); if (ch == '"') { quoteEnd = i; break; } else if (Character.isUnicodeIdentifierPart(ch)) { // Letter before quote return false; } } if (quoteStart == -1 || quoteEnd == -1) { return false; } // Let's check that source code has some whitespaces boolean hasWhitespaces = false; for (int i = quoteStart + 1; i < quoteEnd; i++) { if (Character.isWhitespace(sourceCode.charAt(i))) { hasWhitespaces = true; break; } } if (!hasWhitespaces) { return false; } StringBuilder result = new StringBuilder(sourceCode.length()); char prevChar = (char)-1; boolean inString = true; for (int i = quoteStart + 1; i < quoteEnd; i++) { final char ch = sourceCode.charAt(i); if (prevChar == '\\' && inString) { switch (ch) { case 'n': result.append("\n"); break; case 'r': result.append("\r"); break; case 't': result.append("\t"); break; default: result.append(ch); break; } } else { switch (ch) { case '"': inString = !inString; break; case '\\': break; default: if (inString) { result.append(ch); } else if (ch == '\n' && result.length() > 0) { // Append linefeed even if it is outside of quotes // (but only if string in quotes doesn't end with linefeed - we don't need doubles) boolean endsWithLF = false; for (int k = result.length(); k > 0; k final char lch = result.charAt(k - 1); if (!Character.isWhitespace(lch)) { break; } if (lch == '\n' || lch == '\r') { endsWithLF = true; break; } } if (!endsWithLF) { result.append(ch); } } } } prevChar = ch; } try { document.replace(command.offset, command.length, command.text); document.replace(command.offset, command.text.length(), result.toString()); } catch (Exception e) { log.warn(e); } command.caretOffset = command.offset + result.length(); command.text = null; command.length = 0; command.doit = false; return true; } private boolean updateKeywordCase(final IDocument document, DocumentCommand command) throws BadLocationException { // Whitespace - check for keyword final int startPos, endPos; int pos = command.offset - 1; while (pos >= 0 && Character.isWhitespace(document.getChar(pos))) { pos } endPos = pos + 1; while (pos >= 0 && Character.isJavaIdentifierPart(document.getChar(pos))) { pos } startPos = pos + 1; final String keyword = document.get(startPos, endPos - startPos); if (syntaxManager.getDialect().getKeywordType(keyword) == DBPKeywordType.KEYWORD) { final String fixedKeyword = syntaxManager.getKeywordCase().transform(keyword); if (!fixedKeyword.equals(keyword)) { command.addCommand(startPos, endPos - startPos, fixedKeyword, null); command.doit = false; return true; } } return false; } private void smartIndentAfterNewLine(IDocument document, DocumentCommand command) { clearCachedValues(); int docLength = document.getLength(); if (docLength == 0) { return; } SQLHeuristicScanner scanner = new SQLHeuristicScanner(document, syntaxManager); SQLIndenter indenter = new SQLIndenter(document, scanner); //get previous token int previousToken = scanner.previousToken(command.offset - 1, SQLHeuristicScanner.UNBOUND); StringBuilder indent; StringBuilder beginIndentaion = new StringBuilder(); if (isSupportedAutoCompletionToken(previousToken)) { indent = indenter.computeIndentation(command.offset); beginIndentaion.append(indenter.getReferenceIndentation(command.offset)); } else { indent = indenter.getReferenceIndentation(command.offset); } if (indent == null) { indent = new StringBuilder(); //$NON-NLS-1$ } try { int p = (command.offset == docLength ? command.offset - 1 : command.offset); int line = document.getLineOfOffset(p); StringBuilder buf = new StringBuilder(command.text + indent); IRegion reg = document.getLineInformation(line); int lineEnd = reg.getOffset() + reg.getLength(); int contentStart = findEndOfWhiteSpace(document, command.offset, lineEnd); command.length = Math.max(contentStart - command.offset, 0); int start = reg.getOffset(); ITypedRegion region = TextUtilities.getPartition(document, partitioning, start, true); if (SQLPartitionScanner.CONTENT_TYPE_SQL_MULTILINE_COMMENT.equals(region.getType())) { start = document.getLineInformationOfOffset(region.getOffset()).getOffset(); } command.caretOffset = command.offset + buf.length(); command.shiftsCaret = false; if (isSupportedAutoCompletionToken(previousToken) && !isClosed(document, command.offset, previousToken) && getTokenCount(start, command.offset, scanner, previousToken) > 0) { buf.append(getLineDelimiter(document)); buf.append(beginIndentaion); buf.append(getAutoCompletionTrail(previousToken)); } command.text = buf.toString(); } catch (BadLocationException e) { log.error(e); } } private static String getLineDelimiter(IDocument document) { try { if (document.getNumberOfLines() > 1) { return document.getLineDelimiter(0); } } catch (BadLocationException e) { log.error(e); } return GeneralUtils.getDefaultLineSeparator(); } private boolean isLineDelimiter(IDocument document, String text) { if (delimiters == null) { delimiters = document.getLegalLineDelimiters(); } return delimiters != null && TextUtilities.equals(delimiters, text) > -1; } private void clearCachedValues() { autoCompletionMap.clear(); DBPPreferenceStore preferenceStore = DBeaverCore.getGlobalPreferenceStore(); boolean closeBeginEnd = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_BEGIN_END); if (closeBeginEnd) { autoCompletionMap.put(SQLIndentSymbols.Tokenbegin, SQLIndentSymbols.beginTrail); autoCompletionMap.put(SQLIndentSymbols.TokenBEGIN, SQLIndentSymbols.BEGINTrail); } } private boolean isSupportedAutoCompletionToken(int token) { return autoCompletionMap.containsKey(token); } private String getAutoCompletionTrail(int token) { return autoCompletionMap.get(token); } /** * To count token numbers from start offset to end offset. */ private int getTokenCount(int startOffset, int endOffset, SQLHeuristicScanner scanner, int token) { int tokenCount = 0; while (startOffset < endOffset) { int nextToken = scanner.nextToken(startOffset, endOffset); int position = scanner.getPosition(); if (nextToken != SQLIndentSymbols.TokenEOF && scanner.isSameToken(nextToken, token)) { tokenCount++; } startOffset = position; } return tokenCount; } private boolean isClosed(IDocument document, int offset, int token) { //currently only BEGIN/END is supported. Later more typing aids will be added here. if (token == SQLIndentSymbols.TokenBEGIN || token == SQLIndentSymbols.Tokenbegin) { return getBlockBalance(document, offset) <= 0; } return false; } /** * Returns the block balance, i.e. zero if the blocks are balanced at <code>offset</code>, a negative number if * there are more closing than opening peers, and a positive number if there are more opening than closing peers. */ private int getBlockBalance(IDocument document, int offset) { if (offset < 1) { return -1; } if (offset >= document.getLength()) { return 1; } int begin = offset; int end = offset; SQLHeuristicScanner scanner = new SQLHeuristicScanner(document, syntaxManager); while (true) { begin = scanner.findOpeningPeer(begin, SQLIndentSymbols.TokenBEGIN, SQLIndentSymbols.TokenEND); end = scanner.findClosingPeer(end, SQLIndentSymbols.TokenBEGIN, SQLIndentSymbols.TokenEND); if (begin == -1 && end == -1) { return 0; } if (begin == -1) { return -1; } if (end == -1) { return 1; } } } }
package org.python.pydev.debug.newconsole; import java.io.IOException; import java.net.Socket; import java.net.SocketTimeoutException; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.model.IProcess; import org.eclipse.ui.console.IConsoleFactory; import org.python.pydev.core.IInterpreterInfo; import org.python.pydev.core.IPythonNature; import org.python.pydev.core.log.Log; import org.python.pydev.debug.core.PydevDebugPlugin; import org.python.pydev.debug.model.PyDebugTargetConsole; import org.python.pydev.debug.model.PyStackFrame; import org.python.pydev.debug.model.remote.ListenConnector; import org.python.pydev.debug.model.remote.RemoteDebuggerConsole; import org.python.pydev.debug.newconsole.env.JythonEclipseProcess; import org.python.pydev.debug.newconsole.env.PydevIProcessFactory; import org.python.pydev.debug.newconsole.env.PydevIProcessFactory.PydevConsoleLaunchInfo; import org.python.pydev.debug.newconsole.env.UserCanceledException; import org.python.pydev.debug.newconsole.prefs.InteractiveConsolePrefs; import org.python.pydev.editor.preferences.PydevEditorPrefs; import org.python.pydev.plugin.preferences.PydevPrefs; import org.python.pydev.shared_interactive_console.InteractiveConsolePlugin; import org.python.pydev.shared_interactive_console.console.ui.ScriptConsoleManager; /** * Could ask to configure the interpreter in the preferences * * PreferencesUtil.createPreferenceDialogOn(null, preferencePageId, null, null) * * This is the class responsible for creating the console (and setting up the communication * between the console server and the client). * * @author Fabio */ public class PydevConsoleFactory implements IConsoleFactory { /** * @see IConsoleFactory#openConsole() */ public void openConsole() { createConsole(null); } /** * Create a new PyDev console */ public void createConsole(String additionalInitialComands) { try { PydevConsoleInterpreter interpreter = createDefaultPydevInterpreter(); if (interpreter == null) { return; } if (interpreter.getFrame() == null) { createConsole(interpreter, additionalInitialComands); } else { createDebugConsole(interpreter.getFrame(), additionalInitialComands); } } catch (Exception e) { Log.log(e); } } public void createConsole(final PydevConsoleInterpreter interpreter, final String additionalInitialComands) { Job job = new Job("Create Interactive Console") { @Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask("Create Interactive Console", 3); try { sayHello(interpreter, new SubProgressMonitor(monitor, 1)); connectDebugger(interpreter, additionalInitialComands, new SubProgressMonitor(monitor, 2)); return Status.OK_STATUS; } catch (Exception e) { try { interpreter.close(); } catch (Exception e_inner) { // ignore, but log nested exception Log.log(e_inner); } if (e instanceof UserCanceledException) { return Status.CANCEL_STATUS; } else { Log.log(e); return PydevDebugPlugin.makeStatus(IStatus.ERROR, "Error initializing console.", e); } } finally { monitor.done(); } } }; job.setUser(true); job.schedule(); } private void sayHello(PydevConsoleInterpreter interpreter, IProgressMonitor monitor) throws UserCanceledException, CoreException { monitor.beginTask("Connect To PyDev Console Process", 1); try { PydevConsoleCommunication consoleCommunication = (PydevConsoleCommunication) interpreter .getConsoleCommunication(); try { consoleCommunication.hello(new SubProgressMonitor(monitor, 1)); } catch (UserCanceledException uce) { throw uce; } catch (Exception ex) { final String message; if (ex instanceof SocketTimeoutException) { message = "Timed out after " + InteractiveConsolePrefs.getMaximumAttempts() + " attempts to connect to the console."; } else { message = "Unexpected error connecting to console."; } throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, message, ex)); } } finally { monitor.done(); } } private void connectDebugger(final PydevConsoleInterpreter interpreter, final String additionalInitialComands, IProgressMonitor monitor) throws IOException, CoreException, DebugException, UserCanceledException { monitor.beginTask("Connect Debugger", 10); try { if (interpreter.getFrame() == null) { monitor.worked(1); PydevConsole console = new PydevConsole(interpreter, additionalInitialComands); monitor.worked(1); createDebugTarget(interpreter, console, new SubProgressMonitor(monitor, 8)); ScriptConsoleManager manager = ScriptConsoleManager.getInstance(); manager.add(console, true); } } finally { monitor.done(); } } private void createDebugTarget(PydevConsoleInterpreter interpreter, PydevConsole console, IProgressMonitor monitor) throws IOException, CoreException, DebugException, UserCanceledException { monitor.beginTask("Connect Debug Target", 2); try { // Jython within Eclipse does not yet support these new features Process process = interpreter.getProcess(); if (InteractiveConsolePrefs.getConsoleConnectVariableView() && !(process instanceof JythonEclipseProcess)) { PydevConsoleCommunication consoleCommunication = (PydevConsoleCommunication) interpreter .getConsoleCommunication(); int acceptTimeout = PydevPrefs.getPreferences().getInt(PydevEditorPrefs.CONNECT_TIMEOUT); PyDebugTargetConsole pyDebugTargetConsole = null; IProcess eclipseProcess = interpreter.getLaunch().getProcesses()[0]; RemoteDebuggerConsole debugger = new RemoteDebuggerConsole(); ListenConnector connector = new ListenConnector(acceptTimeout); debugger.startConnect(connector); pyDebugTargetConsole = new PyDebugTargetConsole(consoleCommunication, interpreter.getLaunch(), eclipseProcess, debugger); Socket socket = null; try { consoleCommunication.connectToDebugger(connector.getLocalPort()); socket = debugger.waitForConnect(monitor, process, eclipseProcess); if (socket == null) { throw new UserCanceledException("Cancelled"); } } catch (Exception ex) { try { if (ex instanceof UserCanceledException) { //Only close the console communication if the user actually cancelled (otherwise the user will expect it to still be working). consoleCommunication.close(); debugger.dispose(); //Can't terminate the process either! } else { //But we still want to dispose of the connector. debugger.disposeConnector(); } } catch (Exception e) { // Don't hide important information from user Log.log(e); } if (ex instanceof UserCanceledException) { UserCanceledException userCancelled = (UserCanceledException) ex; throw userCancelled; } String message = "Unexpected error setting up the debugger"; if (ex instanceof SocketTimeoutException) { message = "Timed out after " + Float.toString(acceptTimeout / 1000) + " seconds while waiting for python script to connect."; } throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, message, ex)); } pyDebugTargetConsole.startTransmission(socket); // this starts reading/writing from sockets pyDebugTargetConsole.initialize(); consoleCommunication.setDebugTarget(pyDebugTargetConsole); interpreter.getLaunch().addDebugTarget(pyDebugTargetConsole); ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); launchManager.addLaunch(interpreter.getLaunch()); pyDebugTargetConsole.setConsole(console); console.setProcess(pyDebugTargetConsole.getProcess()); pyDebugTargetConsole.finishedInit = true; } } finally { monitor.done(); } } /** * Create a new Debug Console * * @param interpreter * @param additionalInitialComands */ public void createDebugConsole(PyStackFrame frame, String additionalInitialComands) throws Exception { PydevConsoleLaunchInfo launchAndProcess = new PydevConsoleLaunchInfo(null, null, 0, null, frame); PydevConsoleInterpreter interpreter = createPydevDebugInterpreter(launchAndProcess); ScriptConsoleManager manager = ScriptConsoleManager.getInstance(); PydevDebugConsole console = new PydevDebugConsole(interpreter, additionalInitialComands); manager.add(console, true); } /** * @return A PydevConsoleInterpreter with its communication configured. * * @throws CoreException * @throws IOException * @throws UserCanceledException */ public static PydevConsoleInterpreter createDefaultPydevInterpreter() throws Exception, UserCanceledException { // import sys; sys.ps1=''; sys.ps2='' // import sys;print >> sys.stderr, ' '.join([sys.executable, sys.platform, sys.version]) // print >> sys.stderr, 'PYTHONPATH:' // for p in sys.path: // print >> sys.stderr, p // print >> sys.stderr, 'Ok, all set up... Enjoy' PydevIProcessFactory iprocessFactory = new PydevIProcessFactory(); PydevConsoleLaunchInfo launchAndProcess = iprocessFactory.createInteractiveLaunch(); if (launchAndProcess == null) { return null; } if (launchAndProcess.interpreter != null) { return createPydevInterpreter(launchAndProcess, iprocessFactory.getNaturesUsed()); } else { return createPydevDebugInterpreter(launchAndProcess); } } // Use IProcessFactory to get the required tuple public static PydevConsoleInterpreter createPydevInterpreter(PydevConsoleLaunchInfo info, List<IPythonNature> natures) throws Exception { final ILaunch launch = info.launch; Process process = info.process; Integer clientPort = info.clientPort; IInterpreterInfo interpreterInfo = info.interpreter; if (launch == null) { return null; } PydevConsoleInterpreter consoleInterpreter = new PydevConsoleInterpreter(); int port = Integer.parseInt(launch.getAttribute(PydevIProcessFactory.INTERACTIVE_LAUNCH_PORT)); consoleInterpreter.setConsoleCommunication(new PydevConsoleCommunication(port, process, clientPort)); consoleInterpreter.setNaturesUsed(natures); consoleInterpreter.setInterpreterInfo(interpreterInfo); consoleInterpreter.setLaunch(launch); consoleInterpreter.setProcess(process); InteractiveConsolePlugin.getDefault().addConsoleLaunch(launch); consoleInterpreter.addCloseOperation(new Runnable() { public void run() { InteractiveConsolePlugin.getDefault().removeConsoleLaunch(launch); } }); return consoleInterpreter; } /** * Initialize Console Interpreter and Console Communication for the Debug Console */ public static PydevConsoleInterpreter createPydevDebugInterpreter(PydevConsoleLaunchInfo info) throws Exception { PyStackFrame frame = info.frame; PydevConsoleInterpreter consoleInterpreter = new PydevConsoleInterpreter(); consoleInterpreter.setFrame(frame); // pydev console uses running debugger as a backend consoleInterpreter.setConsoleCommunication(new PydevDebugConsoleCommunication()); return consoleInterpreter; } }
package com.ctrip.xpipe.redis.integratedtest.simple; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.List; import java.util.concurrent.TimeUnit; import com.ctrip.xpipe.concurrent.AbstractExceptionLogTask; import com.ctrip.xpipe.redis.core.entity.RedisMeta; import com.ctrip.xpipe.redis.integratedtest.AbstractIntegratedTest; import org.junit.Test; import redis.clients.jedis.Jedis; /** * @author wenchao.meng * * Jan 20, 2017 */ public class RedisTest extends AbstractIntegratedTest{ @Test public void test() throws IOException{ Socket s = new Socket(); s.connect(new InetSocketAddress("localhost", 6379)); for(String command : createCommands()){ s.getOutputStream().write(command.getBytes()); } s.close(); } @Test public void testIncr() throws IOException { Jedis jedis = createJedis("localhost", 6379); scheduled.scheduleAtFixedRate(new AbstractExceptionLogTask() { @Override protected void doRun() throws Exception { jedis.incr("incr"); } }, 0, 100, TimeUnit.MILLISECONDS); waitForAnyKeyToExit(); } private String[] createCommands() { int valueLen = 20; String setcommand = "set b "; setcommand += randomString(valueLen - setcommand.length()); return new String[] { "*3\r\n" + "$3\r\nset\r\n" + "$1\r\na\r\n" + "$" + valueLen + "\r\n" , setcommand + "\r\n1\r\n" }; } @Override protected List<RedisMeta> getRedisSlaves() { return null; } }
package com.vip.saturn.job.console.controller.gui; import com.vip.saturn.job.console.controller.AbstractController; import com.vip.saturn.job.console.domain.RequestResult; import com.vip.saturn.job.console.exception.SaturnJobConsoleException; import com.vip.saturn.job.console.service.JobService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; /** * Job page controller. * * @author hebelala */ @Controller @RequestMapping("/console/job_overview/{namespace:.+}/") public class JobOverviewController extends AbstractController { @Resource private JobService jobService; @RequestMapping(value = "/jobs", method = RequestMethod.GET) public ResponseEntity<RequestResult> list(final HttpServletRequest request, @PathVariable("namespace") String namespace) throws SaturnJobConsoleException { checkMissingParameter("namespace", namespace); return new ResponseEntity<>(new RequestResult(true, jobService.jobs(namespace)), HttpStatus.OK); } @RequestMapping(value = "/groups", method = RequestMethod.GET) public ResponseEntity<RequestResult> groups(final HttpServletRequest request, @PathVariable("namespace") String namespace) throws SaturnJobConsoleException { checkMissingParameter("namespace", namespace); return new ResponseEntity<>(new RequestResult(true, jobService.groups(namespace)), HttpStatus.OK); } }
package org.sagebionetworks.table.worker; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.sagebionetworks.AsynchronousJobWorkerHelper; import org.sagebionetworks.repo.manager.EntityManager; import org.sagebionetworks.repo.manager.table.ColumnModelManager; import org.sagebionetworks.repo.manager.table.metadata.DefaultColumnModelMapper; import org.sagebionetworks.repo.model.EntityRef; import org.sagebionetworks.repo.model.FileEntity; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.UserInfo; import org.sagebionetworks.repo.model.annotation.v2.Annotations; import org.sagebionetworks.repo.model.annotation.v2.AnnotationsV2TestUtils; import org.sagebionetworks.repo.model.annotation.v2.AnnotationsValueType; import org.sagebionetworks.repo.model.dbo.dao.table.TableRowTruthDAO; import org.sagebionetworks.repo.model.dbo.file.FileHandleDao; import org.sagebionetworks.repo.model.file.S3FileHandle; import org.sagebionetworks.repo.model.helper.DaoObjectHelper; import org.sagebionetworks.repo.model.jdo.KeyFactory; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.ColumnType; import org.sagebionetworks.repo.model.table.Dataset; import org.sagebionetworks.repo.model.table.DatasetCollection; import org.sagebionetworks.repo.model.table.ObjectField; import org.sagebionetworks.repo.model.table.QueryResultBundle; import org.sagebionetworks.repo.model.table.ReplicationType; import org.sagebionetworks.repo.model.table.Row; import org.sagebionetworks.repo.model.table.SnapshotRequest; import org.sagebionetworks.repo.model.table.TableUpdateTransactionRequest; import org.sagebionetworks.repo.model.table.TableUpdateTransactionResponse; import org.sagebionetworks.repo.model.table.ViewObjectType; import org.sagebionetworks.worker.TestHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "classpath:test-context.xml" }) public class DatasetCollectionIntegrationTest { private static final int MAX_WAIT = 1 * 60 * 1000; @Autowired private AsynchronousJobWorkerHelper asyncHelper; @Autowired private TestHelper testHelper; @Autowired private TableRowTruthDAO tableRowTruthDao; @Autowired private DaoObjectHelper<S3FileHandle> fileHandleDaoHelper; @Autowired private EntityManager entityManager; @Autowired private ColumnModelManager columnModelManager; @Autowired private DefaultColumnModelMapper defaultColumnMapper; @Autowired private FileHandleDao fileHandleDao; private UserInfo userInfo; private Project project; private ColumnModel stringColumn; private ColumnModel descriptionColumn; @BeforeEach public void before() throws Exception { tableRowTruthDao.truncateAllRowData(); fileHandleDao.truncateTable(); testHelper.before(); userInfo = testHelper.createUser(); project = testHelper.createProject(userInfo); stringColumn = new ColumnModel(); stringColumn.setName("string_column"); stringColumn.setColumnType(ColumnType.STRING); stringColumn.setMaximumSize(50L); stringColumn = columnModelManager.createColumnModel(userInfo, stringColumn); descriptionColumn = defaultColumnMapper.getColumnModels(ViewObjectType.DATASET_COLLECTION, ObjectField.description).get(0); } @AfterEach public void after() { tableRowTruthDao.truncateAllRowData(); testHelper.cleanup(); fileHandleDao.truncateTable(); } @Test public void testCreateAndQueryDatasetCollection() throws Exception { Dataset datasetOne = createDatasetAndSnapshot(); Dataset datasetTwo = createDatasetAndSnapshot(); Long snapshotVersion = 1L; DatasetCollection collection = asyncHelper.createDatasetCollection(userInfo, new DatasetCollection() .setParentId(project.getId()) .setName("Dataset Collection") .setColumnIds(Arrays.asList(stringColumn.getId(), descriptionColumn.getId())) .setItems(List.of( new EntityRef().setEntityId(datasetOne.getId()).setVersionNumber(snapshotVersion), new EntityRef().setEntityId(datasetTwo.getId()).setVersionNumber(snapshotVersion) ))); List<Row> expectedRows = Arrays.asList( new Row().setRowId(KeyFactory.stringToKey(datasetOne.getId())).setVersionNumber(snapshotVersion).setEtag(datasetOne.getEtag()).setValues(Arrays.asList(datasetOne.getId(), datasetOne.getDescription())), new Row().setRowId(KeyFactory.stringToKey(datasetTwo.getId())).setVersionNumber(snapshotVersion).setEtag(datasetTwo.getEtag()).setValues(Arrays.asList(datasetTwo.getId(), datasetTwo.getDescription())) ); // call under test asyncHelper.assertQueryResult(userInfo, "SELECT * FROM " + collection.getId() + " ORDER BY ROW_VERSION ASC", (QueryResultBundle result) -> { assertEquals(expectedRows, result.getQueryResult().getQueryResults().getRows()); }, MAX_WAIT); } private Dataset createDatasetAndSnapshot() throws Exception { FileEntity fileOne = createFileEntityAndWaitForReplication(); FileEntity fileTwo = createFileEntityAndWaitForReplication(); Dataset dataset = asyncHelper.createDataset(userInfo, new Dataset() .setParentId(project.getId()) .setName(UUID.randomUUID().toString()) .setDescription(UUID.randomUUID().toString()) .setColumnIds(Arrays.asList(stringColumn.getId())) .setItems(List.of( new EntityRef().setEntityId(fileOne.getId()).setVersionNumber(fileOne.getVersionNumber()), new EntityRef().setEntityId(fileTwo.getId()).setVersionNumber(fileTwo.getVersionNumber()) )) ); Annotations annotations = new Annotations() .setId(dataset.getId()) .setEtag(dataset.getEtag()); AnnotationsV2TestUtils.putAnnotations(annotations, stringColumn.getName(), dataset.getId(), AnnotationsValueType.STRING); entityManager.updateAnnotations(userInfo, dataset.getId(), annotations); asyncHelper.assertQueryResult(userInfo, "SELECT * FROM " + dataset.getId(), (QueryResultBundle result) -> { assertEquals(dataset.getItems().size(), result.getQueryResult().getQueryResults().getRows().size()); }, MAX_WAIT); SnapshotRequest snapshotOptions = new SnapshotRequest(); snapshotOptions.setSnapshotComment("Dataset snapshot"); // Add all of the parts TableUpdateTransactionRequest transactionRequest = new TableUpdateTransactionRequest(); transactionRequest.setEntityId(dataset.getId()); transactionRequest.setCreateSnapshot(true); transactionRequest.setSnapshotOptions(snapshotOptions); asyncHelper.assertJobResponse(userInfo, transactionRequest, (TableUpdateTransactionResponse response) -> { assertEquals(1L, response.getSnapshotVersionNumber()); }, MAX_WAIT).getResponse().getSnapshotVersionNumber(); return entityManager.getEntity(userInfo, dataset.getId(), Dataset.class); } private FileEntity createFileEntityAndWaitForReplication() throws Exception { String fileEntityId = entityManager.createEntity(userInfo, new FileEntity() .setName(UUID.randomUUID().toString()) .setParentId(project.getId()) .setDataFileHandleId(fileHandleDaoHelper.create((f) -> { f.setCreatedBy(userInfo.getId().toString()); f.setFileName(UUID.randomUUID().toString()); f.setContentSize(128_000L); }).getId()), null); FileEntity fileEntity = entityManager.getEntity(userInfo, fileEntityId, FileEntity.class); asyncHelper.waitForObjectReplication(ReplicationType.ENTITY, KeyFactory.stringToKey(fileEntity.getId()), fileEntity.getEtag(), MAX_WAIT); return fileEntity; } }
package gov.nih.nci.caarray.services; import gov.nih.nci.caarray.util.EntityPruner; import gov.nih.nci.caarray.util.HibernateUtil; import java.util.Collection; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; /** * Ensures that retrieved entitites are ready for transport, including correct * 'cutting' of object graphs. * * @see EntityPruner#makeChildrenLeaves(Object) */ public class EntityConfiguringInterceptor { /** * Ensures that any object returned and its direct associated entities are loaded. * * @param invContext the method context * @return the method result * @throws Exception if invoking the method throws an exception. */ @AroundInvoke @SuppressWarnings("PMD.SignatureDeclareThrowsException") // method invocation wrapper requires throws Exception public Object prepareReturnValue(InvocationContext invContext) throws Exception { // make the call to the underlying method. This method (prepareReturnValue) wraps the intended method. Object returnValue = invContext.proceed(); // flush any changes made (ie, DataSet population) to this point. We're going to modify // hibernate objects in ways we /don't/ want flushed in prepareEntity // FIXME: we cannot flush any changes here, because the SecurityPolicyPostLoadEventListener makes // changes to objects (like Project) that hibernate sees as modifications. The anonymous user // Commenting this call out for now, because the only time we'd need to flush changes is for // parse-on-demand, which we don't currently do. // HibernateUtil.getCurrentSession().flush(); if (returnValue instanceof Collection) { prepareEntities((Collection<?>) returnValue); } else { prepareEntity(returnValue); } // keep hibernate from performing write behind of all the cutting we just did HibernateUtil.getCurrentSession().clear(); return returnValue; } private void prepareEntities(Collection<?> collection) { EntityPruner pruner = new EntityPruner(); // A note on this loop: We refresh each element first because the session is cleared // each iteration, which would potentially mean that the entities un-initialized // collection properties would be unavailable. // We call clear because the hibernate session could be potentially HUGE after getting // certain collections on objects (like ArrayDesignDetails.designElements, probes, etc.) // Together, these calls keep the hibernate session small, and ensure that we won't get // LazyInitializationExceptions for (Object entity : collection) { HibernateUtil.getCurrentSession().refresh(entity); prepareEntity(entity, pruner); HibernateUtil.getCurrentSession().clear(); } } private void prepareEntity(Object entity) { prepareEntity(entity, new EntityPruner()); } private void prepareEntity(Object entity, EntityPruner pruner) { pruner.makeChildrenLeaves(entity); } }
package com.alecstrong.sqlite.android; import com.google.common.collect.Lists; import com.google.common.io.Files; import com.google.common.io.Resources; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import static com.google.common.truth.Truth.assertThat; import static java.nio.charset.StandardCharsets.UTF_8; public class SqliteAndroidPluginTest { @Rule public TemporaryFixture fixture = new TemporaryFixture(false); private final GradleRunner gradleRunner = GradleRunner.create(); private List<File> pluginClasspath; @Before public void setup() throws IOException { URL pluginClasspathResource = getClass().getClassLoader().getResource("plugin-classpath.txt"); if (pluginClasspathResource == null) { throw new IllegalStateException( "Did not find plugin classpath resource, run `testClasses` build task."); } pluginClasspath = Lists.transform(Resources.readLines(pluginClasspathResource, UTF_8), File::new); File studioProperties = new File(System.getProperty("user.dir") + "/..", "local.properties"); if (!studioProperties.exists()) { throw new IllegalStateException("Need a local.properties file with sdk.dir to run tests, " + "open this project in Android Studio to have a local.properties automatically generated"); } File localProperties = new File(fixture.getRoot(), "local.properties"); Files.copy(studioProperties, localProperties); } @FixtureName("works-fine") @Test public void worksFine() { BuildResult result = gradleRunner.withProjectDir(fixture.getRoot()) .withArguments("assembleDebug", "--stacktrace") .withPluginClasspath(pluginClasspath) .build(); assertThat(result.getStandardOutput()).contains("BUILD SUCCESSFUL"); } @FixtureName("works-fine-as-library") @Test public void worksFineAsLibrary() { BuildResult result = gradleRunner.withProjectDir(fixture.getRoot()) .withArguments("compileDebugJavaWithJavac", "--stacktrace") .withPluginClasspath(pluginClasspath) .build(); assertThat(result.getStandardOutput()).contains("BUILD SUCCESSFUL"); } @FixtureName("unknown-class-type") @Test public void unknownClassType() { BuildResult result = prepareTask().buildAndFail(); assertThat(result.getStandardError()).contains( "Table.sq line 9:2 - Couldnt make a guess for type of colum a_class\n" + " 07\t\tCREATE TABLE test (\n" + " 08\t\t id INT PRIMARY KEY NOT NULL,\n" + " 09\t\t a_class CLASS('')\n" + " \t\t ^^^^^^^^^^^^^^^^^\n" + " 10\t\t)"); } @FixtureName("missing-package-statement") @Test public void missingPackageStatement() { BuildResult result = prepareTask().buildAndFail(); assertThat(result.getStandardError()).contains( "Table.sq line 1:0 - mismatched input 'CREATE' expecting {<EOF>, K_PACKAGE, UNEXPECTED_CHAR}"); } @FixtureName("syntax-error") @Test public void syntaxError() { BuildResult result = prepareTask().buildAndFail(); assertThat(result.getStandardError()).contains( "Table.sq line 5:4 - mismatched input 'FRM' expecting {';', ',', K_EXCEPT, K_FROM, K_GROUP, K_INTERSECT, K_LIMIT, K_ORDER, K_UNION, K_WHERE}"); } @FixtureName("unknown-type") @Test public void unknownType() { BuildResult result = prepareTask().buildAndFail(); assertThat(result.getStandardError()).contains( "Table.sq line 5:15 - no viable alternative at input 'LIST'"); } private GradleRunner prepareTask() { return gradleRunner.withProjectDir(fixture.getRoot()) .withArguments("generateSqliteInterface", "--stacktrace") .withPluginClasspath(pluginClasspath); } }
package at.ac.tuwien.kr.alpha.grounder.transformation.aggregates; import at.ac.tuwien.kr.alpha.common.ComparisonOperator; import at.ac.tuwien.kr.alpha.common.atoms.AggregateAtom; import at.ac.tuwien.kr.alpha.common.atoms.AggregateLiteral; import at.ac.tuwien.kr.alpha.common.atoms.Literal; import at.ac.tuwien.kr.alpha.common.rule.BasicRule; import org.apache.commons.lang3.tuple.ImmutablePair; import java.util.ArrayList; import java.util.Collections; import java.util.List; public final class AggregateLiteralSplitting { private AggregateLiteralSplitting() { throw new UnsupportedOperationException("Utility class - cannot instantiate!"); } public static List<BasicRule> split(BasicRule sourceRule) { // Check if body contains aggregates that need to be split. for (Literal lit : sourceRule.getBody()) { if (lit instanceof AggregateLiteral && shouldRewrite((AggregateLiteral) lit)) { return splitAggregatesInRule(sourceRule); } } // No aggregate in the body that needs splitting, return original rule. return Collections.singletonList(sourceRule); } private static List<BasicRule> splitAggregatesInRule(BasicRule sourceRule) { // Rule contains some aggregates that need splitting. // Aggregates may require splitting in two literals, or in two rules. List<Literal> commonBodyLiterals = new ArrayList<>(); List<Literal> twoLiteralsSplitAggregates = new ArrayList<>(); List<ImmutablePair<Literal, Literal>> twoRulesSplitAggregates = new ArrayList<>(); // First, sort literals of the rule and also compute splitting. for (Literal literal : sourceRule.getBody()) { if (literal instanceof AggregateLiteral && shouldRewrite((AggregateLiteral) literal)) { AggregateLiteral aggLit = (AggregateLiteral) literal; ImmutablePair<AggregateAtom, AggregateAtom> splitAggregate = splitCombinedAggregateAtom(aggLit.getAtom()); if (literal.isNegated()) { // Negated aggregate require splitting in two rules. twoRulesSplitAggregates.add(new ImmutablePair<>( splitAggregate.left.toLiteral(false), splitAggregate.right.toLiteral(false))); } else { // Positive aggregate requires two literals in the body. twoLiteralsSplitAggregates.add(splitAggregate.left.toLiteral(true)); twoLiteralsSplitAggregates.add(splitAggregate.right.toLiteral(true)); } } else { // Literal is no aggregate that needs splitting. commonBodyLiterals.add(literal); } } // Second, compute rule bodies of splitting result. List<Literal> commonBody = new ArrayList<>(commonBodyLiterals); commonBody.addAll(twoLiteralsSplitAggregates); List<List<Literal>> rewrittenBodies = new ArrayList<>(); rewrittenBodies.add(commonBody); // Initialize list of rules with the common body. // For n twoRulesSplitAggregates we need 2^n rules, so // for each of the n pairs in twoRulesSplitAggregates we duplicate the list of rewritten bodies. for (ImmutablePair<Literal, Literal> ruleSplitAggregate : twoRulesSplitAggregates) { int numBodiesBeforeDuplication = rewrittenBodies.size(); for (int i = 0; i < numBodiesBeforeDuplication; i++) { List<Literal> originalBody = rewrittenBodies.get(i); List<Literal> duplicatedBody = new ArrayList<>(originalBody); // Extend bodies of original and duplicate with splitting results. originalBody.add(ruleSplitAggregate.left); duplicatedBody.add(ruleSplitAggregate.right); rewrittenBodies.add(duplicatedBody); } } // Third, turn computed bodies into rules again. List<BasicRule> rewrittenRules = new ArrayList<>(); for (List<Literal> rewrittenBody : rewrittenBodies) { rewrittenRules.add(new BasicRule(sourceRule.getHead(), rewrittenBody)); } return rewrittenRules; } private static boolean shouldRewrite(AggregateLiteral lit) { return lit.getAtom().getLowerBoundTerm() != null && lit.getAtom().getUpperBoundTerm() != null; } private static ImmutablePair<AggregateAtom, AggregateAtom> splitCombinedAggregateAtom(AggregateAtom atom) { AggregateAtom leftHandAtom = new AggregateAtom(atom.getLowerBoundOperator(), atom.getLowerBoundTerm(), atom.getAggregatefunction(), atom.getAggregateElements()); AggregateAtom rightHandAtom = new AggregateAtom(switchOperands(atom.getUpperBoundOperator()), atom.getUpperBoundTerm(), atom.getAggregatefunction(), atom.getAggregateElements()); return new ImmutablePair<>(leftHandAtom, rightHandAtom); } private static ComparisonOperator switchOperands(ComparisonOperator op) { switch (op) { case EQ: return op; case NE: return op; case LT: return ComparisonOperator.GT; case LE: return ComparisonOperator.GE; case GT: return ComparisonOperator.LT; case GE: return ComparisonOperator.LE; default: throw new IllegalArgumentException("Unsupported ComparisonOperator " + op + "!"); } } }
package com.sri.ai.praise.core.representation.interfacebased.factor.core.table; import static com.sri.ai.util.Util.arrayListFilledWith; import static com.sri.ai.util.Util.in; import static com.sri.ai.util.Util.mapIntoArrayList; import static com.sri.ai.util.Util.mapFromListOfKeysAndListOfValues; import static com.sri.ai.util.Util.setDifference; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import com.sri.ai.praise.core.representation.interfacebased.factor.api.Factor; import com.sri.ai.praise.core.representation.interfacebased.factor.api.Variable; import com.sri.ai.praise.core.representation.interfacebased.factor.core.ConstantFactor; import com.sri.ai.util.DefaultExplanationTree; import com.sri.ai.util.ExplanationTree; import com.sri.ai.util.base.NullaryFunction; import com.sri.ai.util.collect.CartesianProductIterator; import com.sri.ai.util.math.MixedRadixNumber; /** * Data type representing a graph factor. * * @author gabriel * @author bobak * */ public class TableFactor implements Factor { // DATA MEMBERS //////////////////////////////////////////////////////////////////////////////////// private String name; private final ArrayList<TableVariable> variableList; private final LinkedHashSet<TableVariable> variableSet; private ArrayList<Double> parameters; private final MixedRadixNumber parameterIndexRadix; private ExplanationTree explanation = DefaultExplanationTree.PLACEHOLDER; // use currently not supported /* NOTE: Understanding the Parameter Order * * ex: consider a factor with three binary variables v1, v2, and v3 in that same order * * parameters will be arranged based on the following variable assignment order: * * [ (v1=0,v2=0,v3=0), (v1=0,v2=0,v3=1), (v1=0,v2=1,v3=0), (v1=0,v2=1,v3=1), * (v1=1,v2=0,v3=0), (v1=1,v2=0,v3=1), (v1=1,v2=1,v3=0), (v1=1,v2=1,v3=1) ] * * Note that the order would change if the order the variables are stored as is changed. * * parameterIndexRadix is responsible for mapping the variable assignments to the correct parameter index. */ // CONSTRUCTORS ///////////////////////////////////////////////////////////////////////////////////// public TableFactor(String factorName, Collection<? extends TableVariable> variables, ArrayList<Double> parameters) { this.name = factorName; if(variables instanceof LinkedHashSet<?>) { this.variableSet = (LinkedHashSet<TableVariable>) variables; } else { this.variableSet = new LinkedHashSet<TableVariable>(variables); } if(variables instanceof ArrayList<?>) { this.variableList = (ArrayList<TableVariable>) variables; } else { this.variableList = new ArrayList<TableVariable>(variables); } this.parameters = parameters; this.parameterIndexRadix = createMixedRadixNumberForIndexingFactorParameters(); } public TableFactor(Collection<? extends TableVariable> variables, ArrayList<Double> parameters) { this("phi",variables,parameters); } public TableFactor(Collection<? extends TableVariable> variables, Double defaultValue) { this(variables, arrayListFilledWith(defaultValue, numEntries(variables))); } public TableFactor(Collection<? extends TableVariable> variables) { this(variables, -1.); } // PUBLIC METHODS /////////////////////////////////////////////////////////////////////////////////// // STATIC METHODS /////////////////////////////////////////////////////////////////////////////////// /** * Calculates the number of parameters are needed for a factor with scope based on the passed variables * * @param variableList * @return number of parameters a factor of given scope needs */ public static int numEntries(Collection<? extends TableVariable> variableList) { int result = 1; for(TableVariable v : variableList) { result *= v.getCardinality(); } return result; } //TODO: finish description /** * * * @param listOfVariables * @return */ public static Iterator<ArrayList<Integer>> getCartesianProduct(Collection<TableVariable> listOfVariables) { ArrayList<ArrayList<Integer>> listOfValuesForTheVariables = mapIntoArrayList(listOfVariables, v -> makeArrayWithValuesFromZeroToCardinalityMinusOne(v.getCardinality())); ArrayList<NullaryFunction<Iterator<Integer>>> iteratorForListOfVariableValues = mapIntoArrayList(listOfValuesForTheVariables, element -> () -> element.iterator()); Iterator<ArrayList<Integer>> cartesianProduct = new CartesianProductIterator<Integer>(iteratorForListOfVariableValues); return cartesianProduct; } //TODO: I suggest refactoring copyToSubTableFactor() to getSubFactor() or sliceFactorAt() across project /** * Slices the factor along variable values provided, returning the sub-factor produced by the slicing * * @param factor (factor to slice on) * @param variablesPredetermined (variables to slice on) * @param valuesPredetermined (values of the above-mentioned variables to slice by) * @return sub-factor produced from slicing the passed variables at their given values */ public static TableFactor copyToSubTableFactor(TableFactor factor, List<TableVariable> variablesPredetermined, List<Integer> valuesPredetermined) { Map<TableVariable, Integer> mapOfvaluesPredetermined = mapFromListOfKeysAndListOfValues(variablesPredetermined, valuesPredetermined); TableFactor result = copyToSubTableFactorWithoutRecreatingANewMap(factor, mapOfvaluesPredetermined); return result; } public static TableFactor copyToSubTableFactor(TableFactor factor, Map<TableVariable, Integer> mapOfvaluesPredetermined) { Map<TableVariable, Integer> map2= new LinkedHashMap<>(mapOfvaluesPredetermined); TableFactor result = copyToSubTableFactorWithoutRecreatingANewMap(factor, map2); return result; } // METHODS BASED ON IMPLEMENTING FACTOR ///////////////////////////////////////////////////////////// @Override public boolean contains(Variable variable) { boolean res = variableSet.contains(variable); return res; } @Override public ArrayList<TableVariable> getVariables() { return variableList; } //TODO: Check correctness of isIdentity() function @Override public boolean isIdentity() { if(parameters.size() == 0 || parameters.get(0) == 0) { return false; } double valueAtZero = parameters.get(0); for(Double v : parameters) { if (v != valueAtZero) { return false; } } return true; } /** * Normalizes factor so that the overall sum of all parameters together = 1.0 * * @return reference to normalized self */ @Override public TableFactor normalize() { Double normalizationConstant = sumOfParameters(); if(normalizationConstant != 0.0 && normalizationConstant != 1.0) { this.normalizeBy(normalizationConstant); } return this ; } /** * Returns parameter corresponding to given variable-assignments * * @param variablesAndTheirValues (variables and their value assignments) * @return parameter corresponding the given variable assignments */ @Override public Double getEntryFor(Map<? extends Variable, ? extends Object> variablesAndTheirValues) { int[] variableValues = variableValuesInFactorVariableOrder(variablesAndTheirValues); Double result = getEntryFor(variableValues); return result; } public <T extends Variable, U extends Object> Double getEntryFor(List<T> variableList, List<U> variableValues) { Map<T, U> variablesAndTheirValues = mapFromListOfKeysAndListOfValues(variableList, variableValues); return getEntryFor(variablesAndTheirValues); } public Double getEntryFor(List<? extends Object> variableValuesInTheRightOrder) { int parameterIndex = getParameterIndex(variableValuesInTheRightOrder); return parameters.get(parameterIndex); } /** * Sums out given variables from factor. * * @param variablesToSumOut (variables to sum out) * @return new factor with given variables summed out */ @Override public Factor sumOut(List<? extends Variable> variablesToSumOutList) { //TODO: Error check for if variablesToSumOut is of type List<? extends TableVarable> //TODO: Error check for if a variable listed to SumOut exists in the factor LinkedHashSet<TableVariable> variablesToSumOut = new LinkedHashSet<>((List<TableVariable>) variablesToSumOutList); LinkedHashSet<TableVariable> variablesNotToSumOut = new LinkedHashSet<>(); variablesNotToSumOut = (LinkedHashSet<TableVariable>) setDifference(this.variableSet, variablesToSumOut, variablesNotToSumOut); Factor result; // if every variable is summed out, return the sum of all the parameters in a constant factor if(variablesNotToSumOut.isEmpty()) { result = new ConstantFactor(sumOfParameters()); } else { result = sumOutEverythingExcept(variablesNotToSumOut); } return result; } /** * Multiplies current TableFactor to another passed in TableFactor * * @param another (the other TableFactor to be multiplied to) * @return a Factor reference to the TableFactor product of the multiplication */ @Override public Factor multiply(Factor another) { Factor result; if(another instanceof ConstantFactor) { result = another.multiply(this); } else if(another.getClass() != this.getClass()) { throw new Error("Trying to multiply different types of factors: this is a " + this.getClass() + "and another is a " + another.getClass()); } else { result = multiply((TableFactor)another); } return result; } @Override public Factor add(Factor another) { Factor result; if(another instanceof ConstantFactor) { result = another.add(this); } else if(another.getClass() != this.getClass()) { throw new Error("Trying to multiply different types of factors: this is a " + this.getClass() + "and another is a " + another.getClass()); } else { result = add((TableFactor) another); } return result; } @Override public boolean isZero() { return false; } @Override public Factor invert() { TableFactor result; ArrayList<Double> newEntries = new ArrayList<>(getEntries().size()); for (Double entry : getEntries()) { if(Math.abs(entry) < 0.00000001) { throw new Error("Can't invert : 0 value in the table factor."); } newEntries.add(1/entry); } result = new TableFactor(getVariables(), newEntries); return result; } @Override public Factor max(Collection<? extends Variable> variablesToMaximize) { // TODO Auto-generated method stub return null; } @Override public ExplanationTree getExplanation() { return explanation; } @Override public void setExplanation(ExplanationTree explanation) { this.explanation = explanation; } @Override public Factor argmax(Collection<? extends Variable> variablesToMaximize) { // TODO Auto-generated method stub return null; } @Override public Factor min(Collection<? extends Variable> variablesToMinimize) { // TODO Auto-generated method stub return null; } @Override public Factor argmin(Collection<? extends Variable> variablesToMinimize) { // TODO Auto-generated method stub return null; } // TABLEFACTOR-SPECIFIC METHODS ///////////////////////////////////////////////////////////////////// @Override public String toString() { String factorAsString = name + variableSet.toString() + ": " + parameters.toString(); return factorAsString; } public void reinitializeEntries(Double defaultValue) { this.parameters = arrayListFilledWith(defaultValue, parameters.size()); } public TableFactor normalizedCopy() { Double normalizationConstant = sumOfParameters(); TableFactor normalizedTableFactor = this; if(normalizationConstant != 0.0 && normalizationConstant != 1.0) { ArrayList<Double> newParameters = new ArrayList<>(parameters.size()); for (Double unnormalizedParameter : parameters) { newParameters.add(unnormalizedParameter/normalizationConstant); } normalizedTableFactor = new TableFactor(variableSet, newParameters); } return normalizedTableFactor; } public TableFactor multiply(TableFactor another) { TableFactor result = initializeNewFactorUnioningVariables(another); result = operateOnUnionedParameters(another, result, (a,b) -> a * b); return result; } public TableFactor add(TableFactor another) { TableFactor result = initializeNewFactorUnioningVariables(another); result = operateOnUnionedParameters(another, result, (a,b) -> a + b); return result; } public void setEntryFor(Map<? extends Variable, ? extends Object> variablesAndTheirValues, Double newParameterValue) { int parameterIndex = getParameterIndex(variablesAndTheirValues); parameters.set(parameterIndex, newParameterValue); } public <T extends Variable, U extends Object> void setEntryFor(List<T> variableList, List<U> variableValues, Double newParameterValue) { Map<T, U> variablesAndTheirValues = mapFromListOfKeysAndListOfValues(variableList, variableValues); int parameterIndex = getParameterIndex(variablesAndTheirValues); parameters.set(parameterIndex, newParameterValue); } public void setEntryFor(List<? extends Integer> variableValuesInTheRightOrder, Double newParameterValue) { int parameterIndex = getParameterIndex(variableValuesInTheRightOrder); parameters.set(parameterIndex, newParameterValue); } public void setName(String newName) { this.name = newName; } public ArrayList<Double> getEntries() { return this.parameters; } // PRIVATE METHODS ////////////////////////////////////////////////////////////////////////////////// // HELPER METHODS /////////////////////////////////////////////////////////////////////////////////// private MixedRadixNumber createMixedRadixNumberForIndexingFactorParameters() { ArrayList<Integer> listOfVariableCardinalities = mapIntoArrayList(variableList, v->v.getCardinality()); return new MixedRadixNumber(BigInteger.ZERO, listOfVariableCardinalities); } private Double sumOfParameters() { Double sumOfParameters = 0.; for(Double p : this.parameters) { sumOfParameters = sumOfParameters + p; } return sumOfParameters; } private void normalizeBy(Double normalizationConstant) { int numParameters = parameters.size(); for(int i = 0; i < numParameters; ++i) { parameters.set(i, parameters.get(i)/normalizationConstant); } } private TableFactor sumOutEverythingExcept(LinkedHashSet<TableVariable> variablesNotToSumOut) { TableFactor result = new TableFactor(variablesNotToSumOut, 0.0); Iterator<ArrayList<Integer>> cartesianProduct = getCartesianProduct(this.variableList); LinkedHashMap<Variable, Integer> variableValueMap = new LinkedHashMap<>(); for(ArrayList<Integer> values: in(cartesianProduct)) { variableValueMap = addtoVariableValueMap(variableValueMap, values); Double currentValue = result.getEntryFor(variableValueMap); Double addedValue = this.getEntryFor(variableValueMap); result.setEntryFor(variableValueMap, currentValue + addedValue); } return result; } private TableFactor initializeNewFactorUnioningVariables(TableFactor another) { LinkedHashSet<TableVariable> newListOfVariables = new LinkedHashSet<>(this.variableSet); newListOfVariables.addAll(another.variableSet); Integer numberOfParametersForNewListOfVariables = numEntries(newListOfVariables); ArrayList<Double> newParameters = arrayListFilledWith(-1.0,numberOfParametersForNewListOfVariables); TableFactor newFactor = new TableFactor(newListOfVariables, newParameters); return newFactor; } private LinkedHashMap<Variable,Integer> addtoVariableValueMap(LinkedHashMap<Variable,Integer> variableValueMap, ArrayList<Integer> values) { int numVars = variableList.size(); for(int i = 0; i < numVars; ++i) { variableValueMap.put(variableList.get(i), values.get(i)); } return variableValueMap; } /** * Returns the indices in this.parameters holding the parameter corresponding to the input variables assignments * <p> * First, the input Map<Variable,VariableAssignment> is converted into an int[] such that each element's index * corresponds to the variables in VariableList and the element values corresponding to the variable assignments. * This array is then passed to another overload of this function to obtain the return value. * * @param variableValueMap (a map from a variable to its assigned value) * @return index position in this.parameters of the parameter corresponding to the variable assignments provided */ private int getParameterIndex(Map<? extends Variable, ? extends Object> variableValueMap) { int[] varValues = variableValuesInFactorVariableOrder(variableValueMap); int parameterIndex = getParameterIndex(varValues); return parameterIndex; } /** * Returns the stored parameter corresponding to the input variable assignments * * @param varValues (array with indices corresponding to variables, and entries * corresponding to the variable assignments) * @return parameter corresponding to the input variable assignments */ private Double getEntryFor(int[] varValues) { int parameterIndex = getParameterIndex(varValues); return parameters.get(parameterIndex); } private int[] variableValuesInFactorVariableOrder(Map<? extends Variable, ? extends Object> mapFromVariableToVariableValue) { //TODO: error checking //TODO: there is no mechanism for handling partial variable assignments int numVariables = variableList.size(); int[] indexOfVariablesValues = new int[numVariables]; for(int i = 0; i < numVariables; ++i) { TableVariable v = variableList.get(i); indexOfVariablesValues[i] = (Integer) mapFromVariableToVariableValue.get(v); } return indexOfVariablesValues; } /** * Returns the index in this.parameters holding the parameter corresponding to the variable assignments input * * @param variableValuesInTheRightOrder (List with element positions corresponding to variables, and entries * corresponding to the variable assignments) * @return index position in this.parameters of the parameter corresponding to the variable assignments provided */ private int getParameterIndex(List<? extends Object> variableValuesInTheRightOrder) { int[] variableValuesArray = new int[variableValuesInTheRightOrder.size()]; int i = 0; for(Object variableValue : variableValuesInTheRightOrder) { //TODO: CURRENTLY NOT SUPPORTING VARIABLE VALUES THAT DO NOT RANGE FROM 0 - variableCardinality... ONCE // THIS IS SUPPORTED, NEED TO ADJUST THIS SECTION OF CODE variableValuesArray[i] = (Integer) variableValue; i++; } int parameterIndex = getParameterIndex(variableValuesArray); return parameterIndex; } /** * Returns the index in this.entries holding the parameter corresponding to the variable assignments input * * @param variableValues (array with indices corresponding to variables, and entries * corresponding to the variable assignments) * @return index position in this.entries of the parameter corresponding to the variable assignments provided */ private int getParameterIndex(int[] variableValues) { int parameterIndex = this.parameterIndexRadix.getValueFor(variableValues).intValue(); return parameterIndex; } private static ArrayList<Integer> makeArrayWithValuesFromZeroToCardinalityMinusOne(int cardinality) { ArrayList<Integer> result = new ArrayList<>(cardinality); for (int i = 0; i < cardinality; i++) { result.add(i); } return result; } private static TableFactor copyToSubTableFactorWithoutRecreatingANewMap(TableFactor factor, Map<TableVariable, Integer> mapOfvaluesPredetermined) { ArrayList<TableVariable> newVariables = new ArrayList<>(factor.getVariables()); newVariables.removeAll(mapOfvaluesPredetermined.keySet()); if(newVariables.size() == 0) { return null; } Iterator<ArrayList<Integer>> cartesianProduct = getCartesianProduct(newVariables); TableFactor result = new TableFactor(newVariables); for(ArrayList<Integer> instantiations: in(cartesianProduct)) { for (int i = 0; i < newVariables.size(); i++) { mapOfvaluesPredetermined.put(newVariables.get(i), instantiations.get(i)); } Double newEntryValue = factor.getEntryFor(mapOfvaluesPredetermined); result.setEntryFor(mapOfvaluesPredetermined, newEntryValue); } return result; } private TableFactor operateOnUnionedParameters(TableFactor another, TableFactor result, BiFunction<Double, Double, Double> operator) { Iterator<ArrayList<Integer>> cartesianProduct = getCartesianProduct(result.variableSet); LinkedHashMap<Variable, Integer> variableValueMap = new LinkedHashMap<>(); for(ArrayList<Integer> values: in(cartesianProduct)) { variableValueMap = result.addtoVariableValueMap(variableValueMap, values); Double product = operator.apply(this.getEntryFor(variableValueMap), another.getEntryFor(variableValueMap)); result.setEntryFor(variableValueMap, product); } return result; } }
package hudson.plugins.scm_sync_configuration.strategies.impl; import hudson.model.Hudson; import hudson.plugins.scm_sync_configuration.strategies.AbstractScmSyncStrategy; import hudson.plugins.scm_sync_configuration.strategies.model.ClassOnlyConfigurationEntityMatcher; import hudson.plugins.scm_sync_configuration.strategies.model.ConfigurationEntityMatcher; import hudson.plugins.scm_sync_configuration.strategies.model.PageMatcher; import java.io.File; import java.util.ArrayList; import java.util.List; public class JenkinsConfigScmSyncStrategy extends AbstractScmSyncStrategy { private static final List<PageMatcher> PAGE_MATCHERS = new ArrayList<PageMatcher>(){ { // Global configuration page add(new PageMatcher("^configure$", "config")); // View configuration pages add(new PageMatcher("^(.+/)?view/[^/]+/configure$", "viewConfig")); add(new PageMatcher("^newView$", "createView")); } }; private static final ConfigurationEntityMatcher CONFIG_ENTITY_MATCHER = new ClassOnlyConfigurationEntityMatcher(Hudson.class); public JenkinsConfigScmSyncStrategy(){ super(CONFIG_ENTITY_MATCHER, PAGE_MATCHERS); } public List<File> createInitializationSynchronizedFileset() { return new ArrayList<File>(){{ add(new File(Hudson.getInstance().getRootDir().getAbsolutePath()+File.separator+"config.xml")); }}; } }
package net.sf.mzmine.modules.peaklistmethods.identification.sirius; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import javax.annotation.Nonnull; import net.sf.mzmine.datamodel.MZmineProject; import net.sf.mzmine.datamodel.MassList; import net.sf.mzmine.datamodel.PeakList; import net.sf.mzmine.datamodel.PeakListRow; import net.sf.mzmine.datamodel.RawDataFile; import net.sf.mzmine.datamodel.Scan; import net.sf.mzmine.main.MZmineCore; import net.sf.mzmine.modules.MZmineModuleCategory; import net.sf.mzmine.modules.MZmineProcessingModule; import net.sf.mzmine.parameters.ParameterSet; import net.sf.mzmine.parameters.parametertypes.MassListComponent; import net.sf.mzmine.parameters.parametertypes.MassListParameter; import net.sf.mzmine.taskcontrol.Task; import net.sf.mzmine.util.ExitCode; public class SiriusProcessingModule implements MZmineProcessingModule { private static final String MODULE_NAME = "SIRIUS structure prediction"; private static final String MODULE_DESCRIPTION = "Sirius identification method."; @Override public @Nonnull String getName() { return MODULE_NAME; } @Override public @Nonnull String getDescription() { return MODULE_DESCRIPTION; } @Override @Nonnull public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters, @Nonnull Collection<Task> tasks) { final PeakList[] peakLists = parameters.getParameter(PeakListIdentificationParameters.peakLists) .getValue().getMatchingPeakLists(); for (final PeakList peakList : peakLists) { Task newTask = new PeakListIdentificationTask(parameters, peakList); tasks.add(newTask); } return ExitCode.OK; } /** * Show dialog for identifying a single peak-list row. * * @param row the peak list row. */ public static void showSingleRowIdentificationDialog(final PeakListRow row) { final ParameterSet parameters = new SingleRowIdentificationParameters(); // Set m/z. parameters.getParameter(SingleRowIdentificationParameters.ION_MASS) .setValue(row.getAverageMZ()); if (parameters.showSetupDialog(MZmineCore.getDesktop().getMainWindow(), true) == ExitCode.OK) { String massListName = parameters.getParameter(SingleRowIdentificationParameters.MASS_LIST).getValue(); List<String> massLists = MassListComponent.getMassListNames(); int fingerCandidates, siriusCandidates, timer; timer = parameters.getParameter(SingleRowIdentificationParameters.SIRIUS_TIMEOUT).getValue(); siriusCandidates = parameters.getParameter(SingleRowIdentificationParameters.SIRIUS_CANDIDATES).getValue(); fingerCandidates = parameters.getParameter(SingleRowIdentificationParameters.FINGERID_CANDIDATES).getValue(); if (timer <= 0 || siriusCandidates <= 0 || fingerCandidates <= 0) { MZmineCore.getDesktop().displayErrorMessage(MZmineCore.getDesktop().getMainWindow(), "Sirius parameters can't be negative"); } else if (!massLists.contains(massListName)) { MZmineCore.getDesktop().displayErrorMessage(MZmineCore.getDesktop().getMainWindow(), "Mass List parameter", String.format("Mass List parameter is set wrong [%s]", massListName)); } else { // Run task. MZmineCore.getTaskController() .addTask(new SingleRowIdentificationTask(parameters.cloneParameterSet(), row)); } } } @Override public @Nonnull MZmineModuleCategory getModuleCategory() { return MZmineModuleCategory.IDENTIFICATION; } @Override public @Nonnull Class<? extends ParameterSet> getParameterSetClass() { return PeakListIdentificationParameters.class; } }
package edu.northwestern.bioinformatics.studycalendar.restlets; import static edu.northwestern.bioinformatics.studycalendar.domain.Fixtures.createBasicTemplate; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.xml.writers.StudySnapshotXmlSerializer; import edu.nwu.bioinformatics.commons.DateUtils; import static org.easymock.EasyMock.*; import org.restlet.data.Status; import java.util.Calendar; import java.util.Date; /** * @author John Dzak * @author Rhett Sutphin */ public class AmendedTemplateResourceTest extends AuthorizedResourceTestCase<AmendedTemplateResource> { private Study study, amendedStudy; private AmendedTemplateHelper helper; private StudySnapshotXmlSerializer studySnapshotXmlSerializer; @Override protected void setUp() throws Exception { super.setUp(); helper = registerMockFor(AmendedTemplateHelper.class); helper.setRequest(request); expectLastCall().atLeastOnce(); studySnapshotXmlSerializer = registerMockFor(StudySnapshotXmlSerializer.class); study = createBasicTemplate(); amendedStudy = study.transientClone(); } @Override protected AmendedTemplateResource createResource() { AmendedTemplateResource resource = new AmendedTemplateResource(); resource.setXmlSerializer(studySnapshotXmlSerializer); resource.setAmendedTemplateHelper(helper); return resource; } public void testGetWhenHelperIsSuccessful() throws Exception { expect(helper.getAmendedTemplate()).andReturn(amendedStudy); expectObjectXmlized(); doGet(); assertResponseStatus(Status.SUCCESS_OK); } public void testSuccessfulResponseIncludesLastModified() throws Exception { Date expectedLastMod = DateUtils.createDate(2007, Calendar.APRIL, 6); amendedStudy.getAmendment().setUpdatedDate(expectedLastMod); assertEquals("Sanity check failed", expectedLastMod, amendedStudy.getLastModifiedDate()); expect(helper.getAmendedTemplate()).andReturn(amendedStudy); expectObjectXmlized(); doGet(); assertEquals(expectedLastMod, response.getEntity().getModificationDate()); } public void testGetWhenHelperFails() throws Exception { expect(helper.getAmendedTemplate()).andThrow(new AmendedTemplateHelper.NotFound("It's not there. I checked twice.")); doGet(); assertResponseStatus(Status.CLIENT_ERROR_NOT_FOUND); assertEntityTextContains("404"); assertEntityTextContains("It's not there. I checked twice."); } ////// EXPECTATIONS protected void expectObjectXmlized() { expect(studySnapshotXmlSerializer.createDocumentString(amendedStudy)).andReturn(MOCK_XML); } }
package org.jbehave.scenario.parser; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.equalTo; import static org.jbehave.Ensure.ensureThat; import java.util.List; import org.jbehave.scenario.PropertyBasedConfiguration; import org.jbehave.scenario.definition.ScenarioDefinition; import org.jbehave.scenario.definition.StoryDefinition; import org.junit.Ignore; import org.junit.Test; public class PatternScenarioParserBehaviour { private static final String NL = System.getProperty("line.separator"); @Test public void shouldExtractGivensWhensAndThensFromSimpleScenarios() { ScenarioParser parser = new PatternScenarioParser(new PropertyBasedConfiguration()); StoryDefinition story = parser.defineStoryFrom( "Given a scenario" + NL + "When I parse it" + NL + "Then I should get steps"); List<String> steps = story.getScenarios().get(0).getSteps(); ensureThat(steps.get(0), equalTo("Given a scenario")); ensureThat(steps.get(1), equalTo("When I parse it")); ensureThat(steps.get(2), equalTo("Then I should get steps")); } @Test public void shouldExtractGivensWhensAndThensFromSimpleScenariosContainingKeywordsAsPartOfTheContent() { ScenarioParser parser = new PatternScenarioParser(new PropertyBasedConfiguration()); StoryDefinition story = parser.defineStoryFrom( "Given a scenario Givenly" + NL + "When I parse it to Whenever" + NL + "And I parse it to Anderson" + NL + "Then I should get steps Thenact"); List<String> steps = story.getScenarios().get(0).getSteps(); ensureThat(steps.get(0), equalTo("Given a scenario Givenly")); ensureThat(steps.get(1), equalTo("When I parse it to Whenever")); ensureThat(steps.get(2), equalTo("And I parse it to Anderson")); ensureThat(steps.get(3), equalTo("Then I should get steps Thenact")); } @Test public void shouldExtractGivensWhensAndThensFromMultilineScenarios() { ScenarioParser parser = new PatternScenarioParser(new PropertyBasedConfiguration()); StoryDefinition story = parser.defineStoryFrom( "Given a scenario" + NL + "with this line" + NL + "When I parse it" + NL + "with another line" + NL + NL + "Then I should get steps" + NL + "without worrying about lines" + NL + "or extra white space between or after steps" + NL + NL); List<String> steps = story.getScenarios().get(0).getSteps(); ensureThat(steps.get(0), equalTo("Given a scenario" + NL + "with this line" )); ensureThat(steps.get(1), equalTo("When I parse it" + NL + "with another line")); ensureThat(steps.get(2), equalTo("Then I should get steps" + NL + "without worrying about lines" + NL + "or extra white space between or after steps")); } @Test public void canParseMultipleScenariosFromOneStory() { String wholeStory = "Scenario: the first scenario " + NL + NL + "Given my scenario" + NL + NL + "Scenario: the second scenario" + NL + NL + "Given my second scenario"; PatternScenarioParser parser = new PatternScenarioParser(new PropertyBasedConfiguration()); StoryDefinition story = parser.defineStoryFrom(wholeStory); ensureThat(story.getScenarios().get(0).getTitle(), equalTo("the first scenario")); ensureThat(story.getScenarios().get(0).getSteps(), equalTo(asList("Given my scenario"))); ensureThat(story.getScenarios().get(1).getTitle(), equalTo("the second scenario")); ensureThat(story.getScenarios().get(1).getSteps(), equalTo(asList("Given my second scenario"))); } @Test public void canParseFullStory() { String wholeStory = "Story: I can output narratives" + NL + NL + "As a developer" + NL + "I want to see the narrative for my story when a scenario in that story breaks" + NL + "So that I can see what we're not delivering" + NL + NL + "Scenario: A pending scenario" + NL + NL + "Given a step that's pending" + NL + "When I run the scenario" + NL + "Then I should see this in the output" + NL + "Scenario: A passing scenario" + NL + "Given I'm not reporting passing scenarios" + NL + "When I run the scenario" + NL + "Then this should not be in the output" + NL + "Scenario: A failing scenario" + NL + "Given a step that fails" + NL + "When I run the scenario" + NL + "Then I should see this in the output" + NL + "And I should see this in the output" + NL; StoryDefinition story = new PatternScenarioParser(new PropertyBasedConfiguration()).defineStoryFrom(wholeStory); ensureThat(story.getBlurb().asString(), equalTo("Story: I can output narratives" + NL + NL + "As a developer" + NL + "I want to see the narrative for my story when a scenario in that story breaks" + NL + "So that I can see what we're not delivering")); ensureThat(story.getScenarios().get(0).getTitle(), equalTo("A pending scenario")); ensureThat(story.getScenarios().get(0).getSteps(), equalTo(asList( "Given a step that's pending", "When I run the scenario", "Then I should see this in the output" ))); ensureThat(story.getScenarios().get(1).getTitle(), equalTo("A passing scenario")); ensureThat(story.getScenarios().get(1).getSteps(), equalTo(asList( "Given I'm not reporting passing scenarios", "When I run the scenario", "Then this should not be in the output" ))); ensureThat(story.getScenarios().get(2).getTitle(), equalTo("A failing scenario")); ensureThat(story.getScenarios().get(2).getSteps(), equalTo(asList( "Given a step that fails", "When I run the scenario", "Then I should see this in the output", "And I should see this in the output" ))); } @Test public void canParseLongStoryWithKeywordSplitScenarios() { ScenarioParser parser = new PatternScenarioParser(new PropertyBasedConfiguration()); ensureLongStoryCanBeParsed(parser); } @Test @Ignore("on Windows, it should fail due to regex stack overflow") public void canParseLongStoryWithPatternSplitScenarios() { ScenarioParser parser = new PatternScenarioParser(new PropertyBasedConfiguration()){ @Override protected List<String> splitScenarios(String allScenariosInFile) { return super.splitScenariosWithPattern(allScenariosInFile); } }; ensureLongStoryCanBeParsed(parser); } private void ensureLongStoryCanBeParsed(ScenarioParser parser) { String aGivenWhenThen = "Given a step" + NL + "When I run it" + NL + "Then I should seen an output" + NL; StringBuffer aScenario = new StringBuffer(); aScenario.append("Scenario: A long scenario").append(NL); int numberOfGivenWhenThensPerScenario = 50; for (int i = 0; i < numberOfGivenWhenThensPerScenario; i++) { aScenario.append(aGivenWhenThen); } int numberOfScenarios = 100; StringBuffer wholeStory = new StringBuffer(); wholeStory.append("Story: A very long story").append(NL); for (int i = 0; i < numberOfScenarios; i++) { wholeStory.append(aScenario).append(NL); } StoryDefinition story = parser.defineStoryFrom(wholeStory.toString()); ensureThat(story.getScenarios().size(), equalTo(numberOfScenarios)); for ( ScenarioDefinition scenario : story.getScenarios() ){ ensureThat(scenario.getSteps().size(), equalTo(numberOfGivenWhenThensPerScenario*3)); } } }
package com.hp.oo.execution.services; import com.hp.oo.engine.queue.entities.ExecStatus; import com.hp.oo.engine.queue.entities.ExecutionMessage; import com.hp.oo.engine.queue.services.QueueDispatcherService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.Date; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; public class InBuffer implements ApplicationListener, Runnable, WorkerRecoveryListener { private final long MEMORY_THRESHOLD = 50000000; // 50 Mega byte private final Logger logger = Logger.getLogger(this.getClass()); @Autowired private QueueDispatcherService queueDispatcher; @Resource private String workerUuid; @Autowired @Qualifier("inBufferCapacity") private Integer capacity; @Autowired(required = false) @Qualifier("coolDownPollingMillis") private Integer coolDownPollingMillis = 300; private Thread fillMsgsThread = new Thread(this); private boolean inShutdown; private boolean endOfInit = false; @Autowired private WorkerManager workerManager; @Autowired private SimpleExecutionRunnableFactory simpleExecutionRunnableFactory; @Autowired private OutboundBuffer outBuffer; @Autowired private WorkerRecoveryManagerImpl recoveryManager; private AtomicBoolean recoveryFlag = new AtomicBoolean(false); private Date currentCreateDate = new Date(0); @PostConstruct private void init(){ capacity = Integer.getInteger("worker.inbuffer.capacity",capacity); coolDownPollingMillis = Integer.getInteger("worker.inbuffer.coolDownPollingMillis",capacity); logger.info("InBuffer capacity is set to :" + capacity + ", coolDownPollingMillis is set to :"+ coolDownPollingMillis); } private void fillBufferPeriodically() { long pollCounter = 0; while (!inShutdown) { pollCounter = pollCounter+ 1; // we reset the currentCreateDate every 100 queries , for the theoretical problem of records // with wrong order of create_time in the queue table. if ((pollCounter % 100) == 0) { currentCreateDate = new Date(0); } try { boolean workerUp = workerManager.isUp(); if(!workerUp) { Thread.sleep(3000); //sleep if worker is not fully started yet } else { //double check if we still need to fill the buffer - we are running multi threaded int bufferSize = workerManager.getInBufferSize(); if (logger.isDebugEnabled()) logger.debug("InBuffer size: " + bufferSize); if (!recoveryManager.isInRecovery() && bufferSize < (capacity * 0.2) && checkFreeMemorySpace(MEMORY_THRESHOLD)) { int messagesToGet = capacity - workerManager.getInBufferSize(); if (logger.isDebugEnabled()) logger.debug("Polling messages from queue (max " + messagesToGet + ")"); List<ExecutionMessage> newMessages = queueDispatcher.poll(workerUuid, messagesToGet, currentCreateDate); if (logger.isDebugEnabled()) logger.debug("Received " + newMessages.size() + " messages from queue"); if (!newMessages.isEmpty()) { // update currentCreateDate; currentCreateDate = new Date(newMessages.get(newMessages.size()-1).getCreateDate().getTime() - 100); //we must acknowledge the messages that we took from the queue ackMessages(newMessages); for(ExecutionMessage msg :newMessages){ addExecutionMessage(msg); } Thread.sleep(coolDownPollingMillis/8); //if there are no messages - sleep a while } else { Thread.sleep(coolDownPollingMillis); //if there are no messages - sleep a while } } else { if (recoveryManager.isInRecovery() && logger.isDebugEnabled()) logger.debug("in buffer waits for recovery ..."); Thread.sleep(coolDownPollingMillis); //if the buffer is not empty enough yet - sleep a while } } } catch (Exception ex) { logger.error("Failed to load new ExecutionMessages to the buffer!", ex); try {Thread.sleep(1000);} catch (InterruptedException e) {/*ignore*/} } } } private void ackMessages(List<ExecutionMessage> newMessages) { ExecutionMessage cloned; for (ExecutionMessage message : newMessages) { // create a unique id for this lane in this specific worker to be used in out buffer optimization message.setWorkerKey(message.getMsgId() + " : " + message.getExecStateId()); cloned = (ExecutionMessage) message.clone(); cloned.setStatus(ExecStatus.IN_PROGRESS); cloned.incMsgSeqId(); message.incMsgSeqId(); // increment the original message seq too in order to preserve the order of all messages of entire step cloned.setPayload(null); //payload is not needed in ack - make it null in order to minimize the data that is being sent outBuffer.put(cloned); } } public void addExecutionMessage(ExecutionMessage msg) { SimpleExecutionRunnable simpleExecutionRunnable = simpleExecutionRunnableFactory.getObject(); simpleExecutionRunnable.setExecutionMessage(msg); simpleExecutionRunnable.setRecoveryFlag(recoveryFlag); workerManager.addExecution(msg.getMsgId(), simpleExecutionRunnable); } @Override public void onApplicationEvent(ApplicationEvent applicationEvent) { if (applicationEvent instanceof ContextRefreshedEvent && ! endOfInit) { endOfInit = true; inShutdown = false; fillMsgsThread.setName("WorkerFillBufferThread"); fillMsgsThread.start(); } else if (applicationEvent instanceof ContextClosedEvent) { inShutdown = true; } } @Override public void run() { fillBufferPeriodically(); } @Override public void doRecovery() { if (logger.isDebugEnabled()) logger.debug("Begin in buffer recovery"); recoveryFlag.set(true); recoveryFlag = new AtomicBoolean(false); if (logger.isDebugEnabled()) logger.debug("In buffer recovery is done"); } public boolean checkFreeMemorySpace(long threshold){ double allocatedMemory = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); double presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory; boolean result = presumableFreeMemory > threshold; if (! result) { logger.warn("InBuffer would not poll messages, because there is not enough free memory."); } return result; } }
package com.xeiam.xchange.bittrex.v1.dto.marketdata; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; public class BittrexTickersResponse { private final boolean success; private final String message; private final ArrayList<BittrexTicker> tickers; public BittrexTickersResponse(@JsonProperty("success") boolean success, @JsonProperty("message") String message, @JsonProperty("result") ArrayList<BittrexTicker> result) { super(); this.success = success; this.message = message; this.tickers = result; } public boolean isSuccess() { return success; } public String getMessage() { return message; } public ArrayList<BittrexTicker> getTickers() { return tickers; } @Override public String toString() { return "BittrexTickersResponse [success=" + success + ", message=" + message + ", tickers=" + tickers + "]"; } }
package org.jnosql.artemis.key.spi; import org.jnosql.artemis.ConfigurationUnit; import org.jnosql.artemis.Repository; import org.jnosql.artemis.key.KeyRepositorySupplier; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.InjectionPoint; import java.lang.annotation.Annotation; import java.lang.reflect.Member; import java.lang.reflect.ParameterizedType; import java.util.Set; @ApplicationScoped class KeyValueRepositoryConfigurationFactory { @ConfigurationUnit @Produces public <R extends Repository<?,?>> KeyRepositorySupplier<R> get(InjectionPoint injectionPoint) { Member member = injectionPoint.getMember(); Bean<?> bean = injectionPoint.getBean(); Set<Annotation> qualifiers = injectionPoint.getQualifiers(); ParameterizedType type= (ParameterizedType) injectionPoint.getType(); Class repository = (Class) type.getActualTypeArguments()[0]; return null; } }
package com.hp.octane.plugins.bamboo.octane; import com.atlassian.bamboo.builder.BuildState; import com.atlassian.bamboo.builder.LifeCycleState; import com.atlassian.bamboo.chains.cache.ImmutableChainStage; import com.atlassian.bamboo.commit.CommitContext; import com.atlassian.bamboo.commit.CommitFile; import com.atlassian.bamboo.plan.PlanIdentifier; import com.atlassian.bamboo.plan.cache.ImmutableJob; import com.atlassian.bamboo.plan.cache.ImmutablePlan; import com.atlassian.bamboo.plan.cache.ImmutableTopLevelPlan; import com.atlassian.bamboo.plugins.git.GitRepository; import com.atlassian.bamboo.repository.Repository; import com.atlassian.bamboo.repository.RepositoryDefinition; import com.atlassian.bamboo.repository.svn.SvnRepository; import com.atlassian.bamboo.results.tests.TestResults; import com.atlassian.bamboo.resultsummary.ImmutableResultsSummary; import com.atlassian.bamboo.v2.build.BuildChanges; import com.atlassian.bamboo.v2.build.BuildRepositoryChanges; import com.hp.octane.integrations.dto.DTOFactory; import com.hp.octane.integrations.dto.causes.CIEventCause; import com.hp.octane.integrations.dto.causes.CIEventCauseType; import com.hp.octane.integrations.dto.configuration.CIProxyConfiguration; import com.hp.octane.integrations.dto.events.CIEvent; import com.hp.octane.integrations.dto.events.CIEventType; import com.hp.octane.integrations.dto.general.CIJobsList; import com.hp.octane.integrations.dto.general.CIServerInfo; import com.hp.octane.integrations.dto.general.CIServerTypes; import com.hp.octane.integrations.dto.pipelines.PipelineNode; import com.hp.octane.integrations.dto.pipelines.PipelinePhase; import com.hp.octane.integrations.dto.scm.*; import com.hp.octane.integrations.dto.snapshots.CIBuildResult; import com.hp.octane.integrations.dto.snapshots.CIBuildStatus; import com.hp.octane.integrations.dto.snapshots.SnapshotNode; import com.hp.octane.integrations.dto.snapshots.SnapshotPhase; import com.hp.octane.integrations.dto.tests.BuildContext; import com.hp.octane.integrations.dto.tests.TestRun; import com.hp.octane.integrations.dto.tests.TestRunError; import com.hp.octane.integrations.dto.tests.TestRunResult; import com.hp.octane.plugins.bamboo.api.OctaneConfigurationKeys; import java.util.ArrayList; import java.util.List; public class DefaultOctaneConverter implements DTOConverter { private DTOFactory dtoFactoryInstance; private static DTOConverter converter; private DefaultOctaneConverter() { super(); dtoFactoryInstance = DTOFactory.getInstance(); } public static DTOConverter getInstance() { synchronized (DefaultOctaneConverter.class) { if (converter == null) { converter = new DefaultOctaneConverter(); } } return converter; } public PipelineNode getPipelineNodeFromJob(ImmutableJob job) { return dtoFactoryInstance.newDTO(PipelineNode.class).setJobCiId(getJobCiId(job)).setName(job.getBuildName()); } public String getRootJobCiId(ImmutableTopLevelPlan plan) { return getCiId(plan); } public String getJobCiId(ImmutableJob job) { return getCiId(job); } public PipelinePhase getPipelinePhaseFromStage(ImmutableChainStage stage) { PipelinePhase phase = dtoFactoryInstance.newDTO(PipelinePhase.class).setName(stage.getName()).setBlocking(true); List<PipelineNode> nodes = new ArrayList<PipelineNode>(stage.getJobs().size()); for (ImmutableJob job : stage.getJobs()) { // TODO decide if we want to mirror disabled jobs or not // if (!job.isSuspendedFromBuilding()) { nodes.add(getPipelineNodeFromJob(job)); } phase.setJobs(nodes); return phase; } public CIProxyConfiguration getProxyCconfiguration(String server, int port, String user, String password) { return dtoFactoryInstance.newDTO(CIProxyConfiguration.class).setHost(server).setPort(port).setUsername(user) .setPassword(password); } public PipelineNode getRootPipelineNodeFromTopLevelPlan(ImmutableTopLevelPlan plan) { PipelineNode node = dtoFactoryInstance.newDTO(PipelineNode.class).setJobCiId(getRootJobCiId(plan)) .setName(plan.getName()); List<PipelinePhase> phases = new ArrayList<PipelinePhase>(plan.getAllStages().size()); for (ImmutableChainStage stage : plan.getAllStages()) { phases.add(getPipelinePhaseFromStage(stage)); } node.setPhasesInternal(phases); return node; } public CIServerInfo getServerInfo(String baseUrl, String instanceId) { return dtoFactoryInstance.newDTO(CIServerInfo.class) .setInstanceId(instanceId) .setInstanceIdFrom(System.currentTimeMillis()).setSendingTime(System.currentTimeMillis()) .setType(CIServerTypes.BAMBOO).setUrl(baseUrl); } public SnapshotNode getSnapshot(ImmutableTopLevelPlan plan, ImmutableResultsSummary resultsSummary){ SnapshotNode snapshotNode = getSnapshotNode(plan, resultsSummary, true); List<SnapshotPhase> phases = new ArrayList<SnapshotPhase>(plan.getAllStages().size()); for (ImmutableChainStage stage : plan.getAllStages()) { phases.add(getSnapshotPhaseFromStage(stage)); } snapshotNode.setPhasesInternal(phases); return snapshotNode; } private SnapshotPhase getSnapshotPhaseFromStage(ImmutableChainStage stage) { SnapshotPhase phase = dtoFactoryInstance.newDTO(SnapshotPhase.class); phase.setName(stage.getName()); phase.setBlocking(true); List<SnapshotNode> nodes = new ArrayList<SnapshotNode>(stage.getJobs().size()); for (ImmutableJob job : stage.getJobs()) { // TODO decide if we want to mirror disabled jobs or not nodes.add(getSnapshotNode(job, job.getLatestResultsSummary(), false)); } phase.setBuilds(nodes); return phase; } private SnapshotNode getSnapshotNode(ImmutablePlan plane, ImmutableResultsSummary resultsSummary, boolean isRoot) { SnapshotNode result = dtoFactoryInstance.newDTO(SnapshotNode.class) .setBuildCiId(resultsSummary.getPlanResultKey().getKey()) .setName(isRoot? plane.getBuildName() : plane.getName()) .setJobCiId((getCiId(plane))) .setDuration(resultsSummary.getDuration()) .setNumber(String.valueOf(resultsSummary.getBuildNumber())) .setResult(getJobResult(resultsSummary.getBuildState())) .setStatus(getJobStatus(plane.getLatestResultsSummary().getLifeCycleState())) .setStartTime(resultsSummary.getBuildDate() != null ? resultsSummary.getBuildDate().getTime() : (resultsSummary.getBuildCompletedDate() != null ? resultsSummary.getBuildCompletedDate().getTime() : System.currentTimeMillis())); return result; } private CIBuildStatus getJobStatus(LifeCycleState lifeCycleState){ switch (lifeCycleState) { case FINISHED: return CIBuildStatus.FINISHED; case IN_PROGRESS: return CIBuildStatus.RUNNING; case QUEUED: return CIBuildStatus.QUEUED; default: return CIBuildStatus.UNAVAILABLE; } } private CIBuildResult getJobResult(BuildState buildState){ switch (buildState) { case FAILED: return CIBuildResult.FAILURE; case SUCCESS: return CIBuildResult.SUCCESS; default: return CIBuildResult.UNAVAILABLE; } } public CIJobsList getRootJobsList(List<ImmutableTopLevelPlan> plans) { CIJobsList jobsList = dtoFactoryInstance.newDTO(CIJobsList.class).setJobs(new PipelineNode[0]); List<PipelineNode> nodes = new ArrayList<PipelineNode>(plans.size()); for (ImmutableTopLevelPlan plan : plans) { PipelineNode node = DTOFactory.getInstance().newDTO(PipelineNode.class).setJobCiId(getRootJobCiId(plan)) .setName(plan.getName()); nodes.add(node); } jobsList.setJobs(nodes.toArray(new PipelineNode[nodes.size()])); return jobsList; } public String getCiId(PlanIdentifier identifier) { return identifier.getPlanKey().getKey(); } public TestRun getTestRunFromTestResult(TestResults testResult, TestRunResult result, long startTime) { String className = testResult.getClassName(); String simpleName = testResult.getShortClassName(); String packageName = className.substring(0, className.length() - simpleName.length() - (className.length() > simpleName.length() ? 1 : 0)); TestRun testRun = dtoFactoryInstance.newDTO(TestRun.class).setClassName(simpleName) .setDuration(Math.round(Double.valueOf(testResult.getDuration()))).setPackageName(packageName) .setResult(result).setStarted(startTime).setTestName(testResult.getActualMethodName()); if (result == TestRunResult.FAILED) { TestRunError error = dtoFactoryInstance.newDTO(TestRunError.class) .setErrorMessage(testResult.getSystemOut()); if (!testResult.getErrors().isEmpty()) { error.setStackTrace(testResult.getErrors().get(0).getContent()); } testRun.setError(error); } return testRun; } @Override public CIEvent getEventWithDetails(String project, String buildCiId, String displayName, CIEventType eventType, long startTime, long estimatedDuration, List<CIEventCause> causes, String number, BuildState buildState, Long currnetTime) { CIEvent event = getEventWithDetails( project, buildCiId, displayName, eventType,startTime, estimatedDuration, causes, number, null); event.setDuration(currnetTime -event.getStartTime()); event.setResult(getJobResult(buildState)); return event; } public CIEvent getEventWithDetails(String project, String buildCiId, String displayName, CIEventType eventType, long startTime, long estimatedDuration, List<CIEventCause> causes, String number) { // CIEvent event = dtoFactoryInstance.newDTO(CIEvent.class).setEventType(eventType).setCauses(causes) // .setProject(project).setProjectDisplayName(displayName).setBuildCiId(buildCiId) // .setEstimatedDuration(estimatedDuration).setStartTime(startTime); // if (number != null) { // event.setNumber(number); // return event; return getEventWithDetails( project, buildCiId, displayName, eventType,startTime, estimatedDuration, causes, number, null); } @Override public CIEvent getEventWithDetails(String project, String buildCiId, String displayName, CIEventType eventType, long startTime, long estimatedDuration, List<CIEventCause> causes, String number, SCMData scmData) { CIEvent event = dtoFactoryInstance.newDTO(CIEvent.class).setEventType(eventType). setCauses(causes) .setProject(project) .setProjectDisplayName(displayName) .setBuildCiId(buildCiId) .setEstimatedDuration(estimatedDuration) .setStartTime(startTime); if (number != null) { event.setNumber(number); } if(scmData!=null){ event.setScmData(scmData); } return event; } public CIEventCause getCauseWithDetails(String buildCiId, String project, String user) { CIEventCause cause = DTOFactory.getInstance().newDTO(CIEventCause.class).setBuildCiId(buildCiId) .setCauses(new ArrayList<CIEventCause>()).setProject(project).setType(CIEventCauseType.UPSTREAM) .setUser(user); return cause; } public BuildContext getBuildContext(String instanceId, String jobId, String buildId) { return DTOFactory.getInstance().newDTO(BuildContext.class).setBuildId(buildId).setBuildName(buildId) .setJobId(jobId).setJobName(jobId).setServerId(instanceId); } private List<SCMChange> getChangeList(List<CommitFile> fileList){ List<SCMChange> scmChangesList = new ArrayList<>(); for(CommitFile commitFile: fileList){ SCMChange scmChange = DTOFactory.getInstance().newDTO(SCMChange.class). setFile(commitFile.getName()). setType("edit"); scmChangesList.add(scmChange); } return scmChangesList; } private SCMRepository createRepository(Repository repo){ SCMRepository scmRepository = DTOFactory.getInstance().newDTO(SCMRepository.class); if (repo instanceof SvnRepository) { SvnRepository svn = (SvnRepository) repo; scmRepository.setUrl(svn.getRepositoryUrl()); scmRepository.setType(SCMType.SVN); scmRepository.setBranch(svn.getVcsBranch().getName()); }else if (repo instanceof GitRepository){ GitRepository git = (GitRepository) repo; scmRepository.setUrl(git.getRepositoryUrl()); scmRepository.setType(SCMType.GIT); scmRepository.setBranch(git.getVcsBranch().getName()); }else{ scmRepository.setType(SCMType.UNKNOWN); } return scmRepository; } private SCMCommit getScmCommit(CommitContext commitContext){ SCMCommit scmCommit = DTOFactory.getInstance().newDTO(SCMCommit.class); scmCommit.setRevId(commitContext.getChangeSetId()); scmCommit.setComment(commitContext.getComment()); scmCommit.setUser(commitContext.getAuthorContext().getName()); scmCommit.setUserEmail(commitContext.getAuthorContext().getEmail()); //scmCommit.setParentRevId(); scmCommit.setTime(commitContext.getDate().getTime()); scmCommit.setChanges(getChangeList(commitContext.getFiles())); return scmCommit; } @Override public SCMData getScmData(com.atlassian.bamboo.v2.build.BuildContext buildContext) { SCMData scmData = null; // for(BuildRepositoryChanges buildRepoChanges : buildContext.getBuildChanges().getRepositoryChanges()){ // buildRepoChanges.getRepositoryId(); // break; SCMRepository scmRepository = null; for(RepositoryDefinition repDef : buildContext.getRepositoryDefinitions()){ Repository repo = repDef.getRepository(); scmRepository = createRepository(repo); break; } List<SCMCommit> scmCommitList = new ArrayList<>(); BuildChanges buildChanges = buildContext.getBuildChanges(); for(BuildRepositoryChanges change: buildChanges.getRepositoryChanges()){ for(CommitContext commitContext: change.getChanges()){ scmCommitList.add(getScmCommit(commitContext)); } } if(scmCommitList.size() >0) { scmData = DTOFactory.getInstance().newDTO(SCMData.class); scmData.setCommits(scmCommitList); scmData.setRepository(scmRepository); scmData.setBuiltRevId(buildContext.getBuildResultKey()); } return scmData; } }
package org.openhab.binding.http.internal; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.URIException; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Some common methods to be used in both HTTP-In-Binding and HTTP-Out-Binding * * @author Thomas.Eichstaedt-Engelen * @since 0.6.0 */ public class HttpUtil { private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class); /** {@link Pattern} which matches the credentials out of an URL */ private static final Pattern URL_CREDENTIALS_PATTERN = Pattern.compile("http: /** * Excutes the given <code>url</code> with the given <code>httpMethod</code> * * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param timeout the socket timeout to wait for data * * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, int timeout) { HttpClient client = new HttpClient(); HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); Credentials credentials = extractCredentials(url); if (credentials != null) { client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.debug(e.getLocalizedMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } String responseBody = method.getResponseBodyAsString(); if (!responseBody.isEmpty()) { logger.debug(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: ", he); } catch (IOException e) { logger.error("Fatal transport error: {}", e.toString()); } finally { method.releaseConnection(); } return null; } protected static Credentials extractCredentials(String url) { Matcher matcher = URL_CREDENTIALS_PATTERN.matcher(url); if (matcher.matches()) { matcher.reset(); String username = ""; String password = ""; while (matcher.find()) { username = matcher.group(1); password = matcher.group(2); } Credentials credentials = new UsernamePasswordCredentials(username, password); return credentials; } return null; } public static HttpMethod createHttpMethod(String httpMethodString, String url) { if ("GET".equals(httpMethodString)) { return new GetMethod(url); } else if ("PUT".equals(httpMethodString)) { return new PutMethod(url); } else if ("POST".equals(httpMethodString)) { return new PostMethod(url); } else if ("DELETE".equals(httpMethodString)) { return new DeleteMethod(url); } else { throw new IllegalArgumentException("given httpMethod '" + httpMethodString + "' is unknown"); } } }
package ch.vorburger.hotea.minecraft.api; import org.spongepowered.api.event.GameEvent; import org.spongepowered.api.event.Subscribe; import org.spongepowered.api.event.state.ServerStartingEvent; import org.spongepowered.api.event.state.ServerStoppingEvent; public abstract class AbstractHotPlugin { abstract protected void onLoaded(GameEvent event); abstract protected void onStop(GameEvent event); // Hotea lifecycle @Subscribe public final void onPluginLoaded(PluginLoadedEvent event) { if (event.getPluginContainer().getInstance() == this) onLoaded(event); } @Subscribe public final void onPlugUnloading(PluginUnloadingEvent event) { if (event.getPluginContainer().getInstance() == this) onStop(event); } // Regular Sponge lifecycle @Subscribe public final void onServerStarting(ServerStartingEvent event) { onLoaded(event); } @Subscribe public final void onServerStopping(ServerStoppingEvent event) { onStop(event); } }