List of usage examples for org.apache.commons.lang3 StringUtils abbreviate
public static String abbreviate(final String str, final int maxWidth)
Abbreviates a String using ellipses.
From source file:hoot.services.controllers.osm.ElementResource.java
/** * <NAME>Element Service - Get Full Element By Unique ID </NAME> * <DESCRIPTION>/*from w ww . ja va 2s .c o m*/ * Convenience method which allows for retrieving a way or relation and all of its child * elements (way nodes or relation members) by an OSM unique element ID. The ID of the map owning * the element does not need to be specified in the query string because the information already exists * in the element ID. This method is not part of the OSM API * </DESCRIPTION> * <PARAMETERS> * <elementId> * string; ID for the requested element unique across all maps of the form: * <map id>_<first letter of the element type>_<element id>; valid values for * <first letter of the element type> are: "w" or "r" * </elementId> * </PARAMETERS> * <OUTPUT> * XML representation of the requested element * </OUTPUT> * <EXAMPLE> * <URL>http://localhost:8080/hoot-services/osm/api/0.6/element/1_n_1/full</URL> * <REQUEST_TYPE>GET</REQUEST_TYPE> * <INPUT> * </INPUT> * <OUTPUT> * OSM XML * see https://insightcloud.digitalglobe.com/redmine/projects/hootenany/wiki/User_-_OsmElementService#Get-Full-Element-By-Unique-ID * </OUTPUT> * </EXAMPLE> * * Returns a single element item's XML for a given map with all of its element children * * @param elementId a "hoot" formatted element id of the format: * <map id>_<first letter of the element type>_<element id>; valid element types include: * way or relation * @return element XML document * @throws Exception * @see https://insightcloud.digitalglobe.com/redmine/projects/hootenany/wiki/User_-_OsmElementService#Get-Full-Element-By-Unique-ID */ @GET @Path("/element/{elementId}/full") @Consumes({ MediaType.TEXT_PLAIN }) @Produces({ MediaType.TEXT_XML }) public Response getFullElementByUniqueId(@PathParam("elementId") final String elementId) throws Exception { if (!UNIQUE_ELEMENT_ID_PATTERN.matcher(elementId).matches()) { ResourceErrorHandler.handleError("Invalid element ID: " + elementId, Status.BAD_REQUEST, log); } final String[] elementIdParts = elementId.split("_"); final ElementType elementType = Element.elementTypeFromString(elementIdParts[1]); if (elementType == null) { ResourceErrorHandler.handleError("Invalid element type: " + elementType, Status.BAD_REQUEST, log); } else if (elementType.equals(ElementType.Node)) { ResourceErrorHandler.handleError("Get Full Element Request Invalid for type = Node", Status.BAD_REQUEST, log); } Connection conn = DbUtils.createConnection(); Document elementDoc = null; try { log.debug("Initializing database connection..."); elementDoc = getElementXml(elementIdParts[0], Long.parseLong(elementIdParts[2]), elementType, true, true, conn); } finally { DbUtils.closeConnection(conn); } log.debug("Returning response: " + StringUtils.abbreviate(XmlDocumentBuilder.toString(elementDoc), 100) + " ..."); return Response.ok(new DOMSource(elementDoc), MediaType.APPLICATION_XML) .header("Content-type", MediaType.APPLICATION_XML).build(); }
From source file:com.fizzed.rocker.compiler.JavaGenerator.java
private void createSourceTemplate(TemplateModel model, Writer w) throws GeneratorException, IOException { if (model.getOptions().getPostProcessing() != null) { // allow post-processors to transform the model try {//from www . j a v a 2s.c o m model = postProcess(model); } catch (PostProcessorException ppe) { throw new GeneratorException("Error during post-processing of model.", ppe); } } // Used to register any withstatements we encounter, so we can generate all dynamic consumers at the end. final WithStatementConsumerGenerator withStatementConsumerGenerator = new WithStatementConsumerGenerator(); // simple increment to help create unique var names int varCounter = -1; if (model.getPackageName() != null && !model.getPackageName().equals("")) { w.append("package ").append(model.getPackageName()).append(";").append(CRLF); } // imports regardless of template w.append(CRLF); w.append("import ").append(java.io.IOException.class.getName()).append(";").append(CRLF); w.append("import ").append(com.fizzed.rocker.ForIterator.class.getName()).append(";").append(CRLF); w.append("import ").append(com.fizzed.rocker.RenderingException.class.getName()).append(";").append(CRLF); w.append("import ").append(com.fizzed.rocker.RockerContent.class.getName()).append(";").append(CRLF); w.append("import ").append(com.fizzed.rocker.RockerOutput.class.getName()).append(";").append(CRLF); w.append("import ").append(com.fizzed.rocker.runtime.DefaultRockerTemplate.class.getName()).append(";") .append(CRLF); w.append("import ").append(com.fizzed.rocker.runtime.PlainTextUnloadedClassLoader.class.getName()) .append(";").append(CRLF); // template imports if (model.getImports().size() > 0) { for (JavaImport i : model.getImports()) { w.append("// import ").append(sourceRef(i)).append(CRLF); w.append("import ").append(i.getStatement()).append(";").append(CRLF); } } w.append(CRLF); w.append("/*").append(CRLF); w.append(" * Auto generated code to render template ").append(model.getPackageName().replace('.', '/')) .append("/").append(model.getTemplateName()).append(CRLF); w.append(" * Do not edit this file. Changes will eventually be overwritten by Rocker parser!").append(CRLF); w.append(" */").append(CRLF); int indent = 0; // MODEL CLASS // class definition tab(w, indent).append("public class ").append(model.getName()).append(" extends ") .append(model.getOptions().getExtendsModelClass()).append(" {").append(CRLF); indent++; w.append(CRLF); // static info about this template tab(w, indent).append("static public final ").append(ContentType.class.getCanonicalName()) .append(" CONTENT_TYPE = ").append(ContentType.class.getCanonicalName()).append(".") .append(model.getContentType().toString()).append(";").append(CRLF); tab(w, indent).append("static public final String TEMPLATE_NAME = \"").append(model.getTemplateName()) .append("\";").append(CRLF); tab(w, indent).append("static public final String TEMPLATE_PACKAGE_NAME = \"") .append(model.getPackageName()).append("\";").append(CRLF); tab(w, indent).append("static public final String HEADER_HASH = \"").append(model.createHeaderHash() + "") .append("\";").append(CRLF); // Don't include MODIFIED_AT header when optimized compiler is used since this implicitly disables hot reloading anyhow if (!model.getOptions().getOptimize()) { tab(w, indent).append("static public final long MODIFIED_AT = ").append(model.getModifiedAt() + "") .append("L;").append(CRLF); } tab(w, indent).append("static public final String[] ARGUMENT_NAMES = {"); StringBuilder argNameList = new StringBuilder(); for (Argument arg : model.getArgumentsWithoutRockerBody()) { if (argNameList.length() > 0) { argNameList.append(","); } argNameList.append(" \"").append(arg.getExternalName()).append("\""); } w.append(argNameList).append(" };").append(CRLF); // model arguments as members of model class appendArgumentMembers(model, w, "private", false, indent); // model setters & getters with builder-style pattern // special case for the RockerBody argument which sorta "hides" its getter/setter if (model.getArguments().size() > 0) { for (Argument arg : model.getArguments()) { // setter w.append(CRLF); tab(w, indent).append("public ").append(model.getName()).append(" ").append(arg.getExternalName()) .append("(" + arg.getExternalType()).append(" ").append(arg.getName()).append(") {") .append(CRLF); tab(w, indent + 1).append("this.").append(arg.getName()).append(" = ").append(arg.getName()) .append(";").append(CRLF); tab(w, indent + 1).append("return this;").append(CRLF); tab(w, indent).append("}").append(CRLF); // getter w.append(CRLF); tab(w, indent).append("public ").append(arg.getExternalType()).append(" ") .append(arg.getExternalName()).append("() {").append(CRLF); tab(w, indent + 1).append("return this.").append(arg.getName()).append(";").append(CRLF); tab(w, indent).append("}").append(CRLF); } } w.append(CRLF); // // model "template" static builder // tab(w, indent).append("static public ").append(model.getName()).append(" template("); if (model.getArguments().size() > 0) { int i = 0; // RockerBody is NOT included (it is passed via a closure block in other templates) // so we only care about the other arguments for (Argument arg : model.getArgumentsWithoutRockerBody()) { if (i != 0) { w.append(", "); } w.append(arg.getType()).append(" ").append(arg.getName()); i++; } } w.append(") {").append(CRLF); tab(w, indent + 1).append("return new ").append(model.getName()).append("()"); if (model.getArguments().size() > 0) { int i = 0; for (Argument arg : model.getArgumentsWithoutRockerBody()) { w.append(CRLF); tab(w, indent + 2).append(".").append(arg.getName()).append("(").append(arg.getName()).append(")"); i++; } } w.append(";").append(CRLF); tab(w, indent).append("}").append(CRLF); // // render of model // w.append(CRLF); tab(w, indent).append("@Override").append(CRLF); tab(w, indent).append("protected DefaultRockerTemplate buildTemplate() throws RenderingException {") .append(CRLF); if (model.getOptions().getOptimize()) { // model "template" static builder (not reloading support, fastest performance) tab(w, indent + 1).append("// optimized for performance (via rocker.optimize flag; no auto reloading)") .append(CRLF); tab(w, indent + 1).append("return new Template(this);").append(CRLF); //tab(w, indent+1).append("return template.__render(context);").append(CRLF); } else { tab(w, indent + 1).append( "// optimized for convenience (runtime auto reloading enabled if rocker.reloading=true)") .append(CRLF); // use bootstrap to create underlying template tab(w, indent + 1).append("return ").append(RockerRuntime.class.getCanonicalName()) .append(".getInstance().getBootstrap().template(this.getClass(), this);").append(CRLF); //tab(w, indent+1).append("return template.__render(context);").append(CRLF); } tab(w, indent).append("}").append(CRLF); // // TEMPLATE CLASS // w.append(CRLF); // class definition tab(w, indent).append("static public class Template extends ").append(model.getOptions().getExtendsClass()); w.append(" {").append(CRLF); indent++; // plain text -> map of chunks of text (Java only supports 2-byte length of string constant) LinkedHashMap<String, LinkedHashMap<String, String>> plainTextMap = model .createPlainTextMap(PLAIN_TEXT_CHUNK_LENGTH); if (!plainTextMap.isEmpty()) { w.append(CRLF); for (String plainText : plainTextMap.keySet()) { // include static text as comments in source (limit to 500) tab(w, indent).append("// ") .append(StringUtils.abbreviate(RockerUtil.ESCAPE_JAVA.translate(plainText), 500)) .append(CRLF); for (Map.Entry<String, String> chunk : plainTextMap.get(plainText).entrySet()) { if (this.plainTextStrategy == PlainTextStrategy.STATIC_STRINGS) { tab(w, indent).append("static private final String ").append(chunk.getKey()).append(" = \"") .append(StringEscapeUtils.escapeJava(chunk.getValue())).append("\";").append(CRLF); } else if (this.plainTextStrategy == PlainTextStrategy.STATIC_BYTE_ARRAYS_VIA_UNLOADED_CLASS) { tab(w, indent).append("static private final byte[] ").append(chunk.getKey()).append(";") .append(CRLF); } } } // generate the static initializer if (this.plainTextStrategy == PlainTextStrategy.STATIC_BYTE_ARRAYS_VIA_UNLOADED_CLASS) { w.append(CRLF); tab(w, indent).append("static {").append(CRLF); String loaderClassName = unqualifiedClassName(PlainTextUnloadedClassLoader.class); tab(w, indent + 1).append(loaderClassName).append(" loader = ").append(loaderClassName) .append(".tryLoad(").append(model.getName()).append(".class.getClassLoader(), ") .append(model.getName()).append(".class.getName()").append(" + \"$PlainText\", \"") .append(model.getOptions().getTargetCharset()).append("\");").append(CRLF); for (String plainText : plainTextMap.keySet()) { for (Map.Entry<String, String> chunk : plainTextMap.get(plainText).entrySet()) { if (this.plainTextStrategy == PlainTextStrategy.STATIC_BYTE_ARRAYS_VIA_UNLOADED_CLASS) { tab(w, indent + 1).append(chunk.getKey()).append(" = loader.tryGet(\"") .append(chunk.getKey()).append("\");").append(CRLF); } } } tab(w, indent).append("}").append(CRLF); } } // arguments as members of template class appendArgumentMembers(model, w, "protected", true, indent); w.append(CRLF); // constructor tab(w, indent).append("public Template(").append(model.getName()).append(" model) {").append(CRLF); tab(w, indent + 1).append("super(model);").append(CRLF); tab(w, indent + 1).append("__internal.setCharset(\"").append(model.getOptions().getTargetCharset()) .append("\");").append(CRLF); tab(w, indent + 1).append("__internal.setContentType(CONTENT_TYPE);").append(CRLF); tab(w, indent + 1).append("__internal.setTemplateName(TEMPLATE_NAME);").append(CRLF); tab(w, indent + 1).append("__internal.setTemplatePackageName(TEMPLATE_PACKAGE_NAME);").append(CRLF); // each model argument passed along as well for (Argument arg : model.getArguments()) { tab(w, indent + 1).append("this.").append(arg.getName()).append(" = model.") .append(arg.getExternalName()).append("();").append(CRLF); } tab(w, indent).append("}").append(CRLF); w.append(CRLF); tab(w, indent).append("@Override").append(CRLF); tab(w, indent).append("protected void __doRender() throws IOException, RenderingException {").append(CRLF); // build rendering code int depth = 1; Deque<String> blockEnd = new ArrayDeque<>(); for (TemplateUnit unit : model.getUnits()) { if (unit instanceof Comment) { continue; } // something like // IfBeginBlock // __internal.aboutToExecutePosInSourceTemplate(5, 10); appendCommentAndSourcePositionUpdate(w, depth + indent, unit); if (unit instanceof PlainText) { PlainText plain = (PlainText) unit; LinkedHashMap<String, String> chunks = plainTextMap.get(plain.getText()); for (String chunkName : chunks.keySet()) { tab(w, depth + indent).append("__internal.writeValue(").append(chunkName).append(");") .append(CRLF); } } else if (unit instanceof ValueExpression) { ValueExpression value = (ValueExpression) unit; tab(w, depth + indent).append("__internal.renderValue(").append(value.getExpression()).append(", ") .append("" + value.isNullSafe()).append(");").append(CRLF); } else if (unit instanceof NullTernaryExpression) { NullTernaryExpression nullTernary = (NullTernaryExpression) unit; tab(w, depth + indent).append("{").append(CRLF); tab(w, depth + indent + 1).append("final Object __v = ").append(nullTernary.getLeftExpression()) .append(";").append(CRLF); tab(w, depth + indent + 1).append("if (__v != null) { __internal.renderValue(__v, false); }") .append(CRLF); if (nullTernary.getRightExpression() != null) { tab(w, depth + indent + 1).append("else {__internal.renderValue(") .append(nullTernary.getRightExpression()).append(", true); }").append(CRLF); } tab(w, depth + indent).append("}").append(CRLF); } else if (unit instanceof ValueClosureBegin) { ValueClosureBegin closure = (ValueClosureBegin) unit; tab(w, depth + indent).append("__internal.renderValue(").append(closure.getExpression()) .append(".__body("); // Java 1.8+ use lambda if (isJava8Plus(model)) { w.append("() -> {").append(CRLF); depth++; blockEnd.push("}), false);"); } // Java 1.7- uses anonymous inner class else { w.append("new ").append(unqualifiedClassName(RockerContent.class)).append("() {").append(CRLF); depth++; blockEnd.push("}), false);"); tab(w, depth + indent).append("@Override").append(CRLF); tab(w, depth + indent).append("public void render() throws IOException, RenderingException {") .append(CRLF); depth++; blockEnd.push("}"); } } else if (unit instanceof ValueClosureEnd) { // Java 1.8+ use lambda if (isJava8Plus(model)) { depth--; tab(w, depth + indent).append(blockEnd.pop()).append(" // value closure end ") .append(sourceRef(unit)).append(CRLF); } // Java 1.7- uses anonymous inner class else { depth--; tab(w, depth + indent).append(blockEnd.pop()).append(CRLF); depth--; tab(w, depth + indent).append(blockEnd.pop()).append(" // value closure end ") .append(sourceRef(unit)).append(CRLF); } } else if (unit instanceof ContentClosureBegin) { ContentClosureBegin closure = (ContentClosureBegin) unit; tab(w, depth + indent).append("RockerContent ").append(closure.getIdentifier()).append(" = "); // Java 1.8+ use lambda if (isJava8Plus(model)) { w.append("() -> {").append(CRLF); depth++; blockEnd.push("};"); } // Java 1.7- uses anonymous inner class else { w.append("new ").append(unqualifiedClassName(com.fizzed.rocker.RockerContent.class)) .append("() {").append(CRLF); depth++; blockEnd.push("};"); tab(w, depth + indent).append("@Override").append(CRLF); tab(w, depth + indent).append("public void render() throws IOException, RenderingException {") .append(CRLF); depth++; blockEnd.push("}"); } } else if (unit instanceof ContentClosureEnd) { // Java 1.8+ use lambda if (isJava8Plus(model)) { depth--; tab(w, depth + indent).append(blockEnd.pop()).append(" // content closure end ") .append(sourceRef(unit)).append(CRLF); } // Java 1.7- uses anonymous inner class else { depth--; tab(w, depth + indent).append(blockEnd.pop()).append(CRLF); depth--; tab(w, depth + indent).append(blockEnd.pop()).append(" // content closure end ") .append(sourceRef(unit)).append(CRLF); } } else if (unit instanceof IfBlockBegin) { IfBlockBegin block = (IfBlockBegin) unit; tab(w, depth + indent).append("if ").append(block.getExpression()).append(" {").append(CRLF); blockEnd.push("}"); depth++; } else if (unit instanceof IfBlockElseIf) { final IfBlockElseIf block = (IfBlockElseIf) unit; depth--; // This keeps else-if nicely formatted in generated code. tab(w, depth + indent).append("} else if ").append(block.getExpression()).append(" {").append(CRLF); depth++; } else if (unit instanceof IfBlockElse) { depth--; tab(w, depth + indent).append("} else {").append(" // else ").append(sourceRef(unit)).append(CRLF); depth++; } else if (unit instanceof IfBlockEnd) { depth--; tab(w, depth + indent).append(blockEnd.pop()).append(" // if end ").append(sourceRef(unit)) .append(CRLF); } else if (unit instanceof WithBlockBegin) { WithBlockBegin block = (WithBlockBegin) unit; WithStatement stmt = block.getStatement(); String statementConsumerName = withStatementConsumerGenerator.register(stmt); final List<WithStatement.VariableWithExpression> variables = stmt.getVariables(); if (isJava8Plus(model)) { tab(w, depth + indent) .append(variables.size() == 1 ? qualifiedClassName(WithBlock.class) : WithStatementConsumerGenerator.WITH_BLOCKS_GENERATED_CLASS_NAME) .append(".with("); // All expressions for (int i = 0; i < variables.size(); i++) { final WithStatement.VariableWithExpression var = variables.get(i); if (i > 0) { w.append(", "); } w.append(var.getValueExpression()); } w.append(", ").append(stmt.isNullSafe() + "").append(", ("); for (int i = 0; i < variables.size(); i++) { final WithStatement.VariableWithExpression var = variables.get(i); if (i > 0) { w.append(", "); } w.append(var.getVariable().getName()); } w.append(") -> {").append(CRLF); depth++; blockEnd.push("});"); } else { tab(w, depth + indent) // Note for standard 1 variable with block we use the predefined consumers. // Otherwise we fallback to the generated ones. .append(variables.size() == 1 ? qualifiedClassName(WithBlock.class) : WithStatementConsumerGenerator.WITH_BLOCKS_GENERATED_CLASS_NAME) .append(".with("); // All expressions for (int i = 0; i < variables.size(); i++) { final WithStatement.VariableWithExpression var = variables.get(i); if (i > 0) { w.append(", "); } w.append(var.getValueExpression()); } w.append(", ").append(stmt.isNullSafe() + "").append(", (new ").append(statementConsumerName) .append('<'); // Types for the .with(..) for (int i = 0; i < variables.size(); i++) { final JavaVariable variable = variables.get(i).getVariable(); if (i > 0) { w.append(", "); } w.append(variable.getType()); } w.append(">() {").append(CRLF); tab(w, depth + indent + 1).append("@Override public void accept("); for (int i = 0; i < variables.size(); i++) { final JavaVariable variable = variables.get(i).getVariable(); if (i > 0) { w.append(", "); } w.append("final ").append(variable.toString()); } w.append(") throws IOException {").append(CRLF); depth++; blockEnd.push("}}));"); } } else if (unit instanceof WithBlockElse) { depth--; if (isJava8Plus(model)) { tab(w, depth + indent).append("}, () -> {").append(CRLF); } else { tab(w, depth + indent).append("}}), (new ") .append(qualifiedClassName(WithBlock.Consumer0.class)).append("() { ") .append("@Override public void accept() throws IOException {").append(CRLF); } depth++; } else if (unit instanceof WithBlockEnd) { depth--; tab(w, depth + indent).append(blockEnd.pop()).append(" // with end ").append(sourceRef(unit)) .append(CRLF); } else if (unit instanceof ForBlockBegin) { ForBlockBegin block = (ForBlockBegin) unit; ForStatement stmt = block.getStatement(); // break support via try and catch mechanism (works across lambdas!) tab(w, depth + indent).append("try {").append(CRLF); depth++; if (stmt.getForm() == ForStatement.Form.GENERAL) { // print out raw statement including parentheses tab(w, depth + indent).append("for ").append(block.getExpression()).append(" {").append(CRLF); blockEnd.push("}"); } else if (stmt.getForm() == ForStatement.Form.ENHANCED) { // Java 1.8+ (use lambdas) if (stmt.hasAnyUntypedArguments() && isJava8Plus(model)) { // build list of lambda vars String localVars = ""; for (JavaVariable arg : stmt.getArguments()) { if (localVars.length() != 0) { localVars += ","; } localVars += arg.getName(); } tab(w, depth + indent).append(Java8Iterator.class.getName()).append(".forEach(") .append(stmt.getValueExpression()).append(", (").append(localVars).append(") -> {") .append(CRLF); blockEnd.push("});"); } else { // is the first argument a "ForIterator" ? boolean forIterator = isForIteratorType(stmt.getArguments().get(0).getType()); int collectionCount = (forIterator ? 2 : 1); int mapCount = (forIterator ? 3 : 2); // type and value we are going to iterate thru String iterateeType = null; String valueExpression = null; if (stmt.getArguments().size() == collectionCount) { iterateeType = stmt.getArguments().get(collectionCount - 1).getTypeAsNonPrimitiveType(); valueExpression = stmt.getValueExpression(); } else if (stmt.getArguments().size() == mapCount) { iterateeType = "java.util.Map.Entry<" + stmt.getArguments().get(mapCount - 2).getTypeAsNonPrimitiveType() + "," + stmt.getArguments().get(mapCount - 1).getTypeAsNonPrimitiveType() + ">"; valueExpression = stmt.getValueExpression() + ".entrySet()"; } // create unique variable name for iterator String forIteratorVarName = "__forIterator" + (++varCounter); // ForIterator for collection and make it final to assure nested anonymous // blocks can access it as well. tab(w, depth + indent).append("final ") .append(com.fizzed.rocker.runtime.CollectionForIterator.class.getName()).append("<") .append(iterateeType).append(">").append(" ").append(forIteratorVarName) .append(" = new ") .append(com.fizzed.rocker.runtime.CollectionForIterator.class.getName()).append("<") .append(iterateeType).append(">").append("(").append(valueExpression).append(");") .append(CRLF); // for loop same regardless of map vs. collection tab(w, depth + indent).append("while (").append(forIteratorVarName).append(".hasNext()) {") .append(CRLF); // if forIterator request assign to local var and make it final to assure nested anonymous // blocks can access it as well. if (forIterator) { tab(w, depth + indent + 1).append("final ") .append(com.fizzed.rocker.ForIterator.class.getName()).append(" ") .append(stmt.getArguments().get(0).getName()).append(" = ") .append(forIteratorVarName).append(";").append(CRLF); } if (stmt.getArguments().size() == collectionCount) { // assign item to local var and make it final to assure nested anonymous // blocks can access it as well. tab(w, depth + indent + 1).append("final ") .append(stmt.getArguments().get(collectionCount - 1).toString()).append(" = ") .append(forIteratorVarName).append(".next();").append(CRLF); } else if (stmt.getArguments().size() == mapCount) { // create unique variable name for iterator String entryVarName = "__entry" + (++varCounter); // assign map entry to local var tab(w, depth + indent + 1).append("final ").append(iterateeType).append(" ") .append(entryVarName).append(" = ").append(forIteratorVarName) .append(".next();").append(CRLF); // assign entry to local values make it final to assure nested anonymous // blocks can access it as well. tab(w, depth + indent + 1).append("final ") .append(stmt.getArguments().get(mapCount - 2).toString()).append(" = ") .append(entryVarName).append(".getKey();").append(CRLF); tab(w, depth + indent + 1).append("final ") .append(stmt.getArguments().get(mapCount - 1).toString()).append(" = ") .append(entryVarName).append(".getValue();").append(CRLF); } else { throw new GeneratorException("Unsupported number of arguments for for loop"); } blockEnd.push("}"); } } depth++; // continue support via try and catch mechanism (works across lambdas!) tab(w, depth + indent).append("try {").append(CRLF); depth++; } else if (unit instanceof ForBlockEnd) { depth--; // continue support via try and catch mechanism (works across lambdas!) tab(w, depth + indent).append("} catch (").append(ContinueException.class.getCanonicalName()) .append(" e) {").append(CRLF); tab(w, depth + indent + 1).append("// support for continuing for loops").append(CRLF); tab(w, depth + indent).append("}").append(CRLF); depth--; tab(w, depth + indent).append(blockEnd.pop()).append(" // for end ").append(sourceRef(unit)) .append(CRLF); depth--; // break support via try and catch mechanism (works across lambdas!) tab(w, depth + indent).append("} catch (").append(BreakException.class.getCanonicalName()) .append(" e) {").append(CRLF); tab(w, depth + indent + 1).append("// support for breaking for loops").append(CRLF); tab(w, depth + indent).append("}").append(CRLF); } else if (unit instanceof BreakStatement) { tab(w, depth + indent).append("__internal.throwBreakException();").append(CRLF); } else if (unit instanceof ContinueStatement) { tab(w, depth + indent).append("__internal.throwContinueException();").append(CRLF); } //log.info(" src (@ {}): [{}]", unit.getSourceRef(), unit.getSourceRef().getConsoleFriendlyText()); } // end of render() tab(w, indent).append("}").append(CRLF); indent--; // end of template class tab(w, indent).append("}").append(CRLF); // Generate class with all gathered consumer interfaces for all withblocks withStatementConsumerGenerator.generate(this, w); if (this.plainTextStrategy == PlainTextStrategy.STATIC_BYTE_ARRAYS_VIA_UNLOADED_CLASS && !plainTextMap.isEmpty()) { w.append(CRLF); tab(w, indent).append("private static class PlainText {").append(CRLF); w.append(CRLF); for (String plainText : plainTextMap.keySet()) { for (Map.Entry<String, String> chunk : plainTextMap.get(plainText).entrySet()) { tab(w, indent + 1).append("static private final String ").append(chunk.getKey()).append(" = \"") .append(StringEscapeUtils.escapeJava(chunk.getValue())).append("\";").append(CRLF); } } w.append(CRLF); tab(w, indent).append("}").append(CRLF); } w.append(CRLF); w.append("}").append(CRLF); }
From source file:ca.phon.app.project.ProjectWindow.java
private void init() { /* Layout *//*from ww w.j av a 2 s . c o m*/ setLayout(new BorderLayout()); final ProjectDataTransferHandler transferHandler = new ProjectDataTransferHandler(this); /* Create components */ newCorpusButton = createNewCorpusButton(); createCorpusButton = createCorpusButton(); corpusList = new JList<String>(); corpusModel = new CorpusListModel(getProject()); corpusList.setModel(corpusModel); corpusList.setCellRenderer(new CorpusListCellRenderer()); corpusList.setVisibleRowCount(20); corpusList.addListSelectionListener(e -> { if (getSelectedCorpus() != null) { String corpus = getSelectedCorpus(); sessionModel.setCorpus(corpus); sessionList.clearSelection(); corpusDetails.setCorpus(corpus); if (getProject().getCorpusSessions(corpus).size() == 0) { onSwapNewAndCreateSession(newSessionButton); } else { onSwapNewAndCreateSession(createSessionButton); } } }); corpusList.addMouseListener(new MouseInputAdapter() { @Override public void mousePressed(MouseEvent e) { doPopup(e); } @Override public void mouseReleased(MouseEvent e) { doPopup(e); } public void doPopup(MouseEvent e) { if (e.isPopupTrigger()) { int clickedIdx = corpusList.locationToIndex(e.getPoint()); if (clickedIdx >= 0 && Arrays.binarySearch(corpusList.getSelectedIndices(), clickedIdx) < 0) { corpusList.setSelectedIndex(clickedIdx); } showCorpusListContextMenu(e.getPoint()); } } }); final DragSource corpusDragSource = new DragSource(); corpusDragSource.createDefaultDragGestureRecognizer(corpusList, DnDConstants.ACTION_COPY, (event) -> { final List<ProjectPath> paths = new ArrayList<>(); for (String corpus : getSelectedCorpora()) { final ProjectPath corpusPath = new ProjectPath(getProject(), corpus, null); paths.add(corpusPath); } final ProjectPathTransferable transferable = new ProjectPathTransferable(paths); event.startDrag(DragSource.DefaultCopyDrop, transferable); }); corpusList.setDragEnabled(true); corpusList.setTransferHandler(transferHandler); corpusDetails = new CorpusDetailsPane(getProject()); corpusDetails.setWrapStyleWord(true); corpusDetails.setRows(6); corpusDetails.setLineWrap(true); corpusDetails.setBackground(Color.white); corpusDetails.setOpaque(true); JScrollPane corpusDetailsScroller = new JScrollPane(corpusDetails); sessionList = new JList<String>(); newSessionButton = createNewSessionButton(); createSessionButton = createSessionButton(); sessionModel = new SessionListModel(getProject()); sessionList.setModel(sessionModel); sessionList.setCellRenderer(new SessionListCellRenderer()); sessionList.setVisibleRowCount(20); sessionList.addListSelectionListener(e -> { if (sessionList.getSelectedValue() != null && !e.getValueIsAdjusting()) { String corpus = getSelectedCorpus(); String session = getSelectedSessionName(); sessionDetails.setSession(corpus, session); } }); sessionList.addMouseListener(new MouseInputAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && e.getButton() == 1) { // get the clicked item int clickedItem = sessionList.locationToIndex(e.getPoint()); if (sessionList.getModel().getElementAt(clickedItem) == null) return; final String session = sessionList.getModel().getElementAt(clickedItem).toString(); final String corpus = ((SessionListModel) sessionList.getModel()).getCorpus(); msgPanel.reset(); msgPanel.setMessageLabel("Opening '" + corpus + "." + session + "'"); msgPanel.setIndeterminate(true); msgPanel.repaint(); SwingUtilities.invokeLater(() -> { final ActionEvent ae = new ActionEvent(sessionList, -1, "openSession"); (new OpenSessionAction(ProjectWindow.this, corpus, session)).actionPerformed(ae); msgPanel.setIndeterminate(false); }); } } @Override public void mousePressed(MouseEvent e) { doPopup(e); } @Override public void mouseReleased(MouseEvent e) { doPopup(e); } public void doPopup(MouseEvent e) { if (e.isPopupTrigger()) { int clickedIdx = sessionList.locationToIndex(e.getPoint()); if (clickedIdx >= 0 && Arrays.binarySearch(sessionList.getSelectedIndices(), clickedIdx) < 0) { sessionList.setSelectedIndex(clickedIdx); } showSessionListContextMenu(e.getPoint()); } } }); sessionList.setDragEnabled(true); sessionList.setTransferHandler(transferHandler); final DragSource sessionDragSource = new DragSource(); sessionDragSource.createDefaultDragGestureRecognizer(sessionList, DnDConstants.ACTION_COPY, (event) -> { final List<ProjectPath> paths = new ArrayList<>(); final String corpus = getSelectedCorpus(); if (corpus == null) return; for (String session : getSelectedSessionNames()) { final ProjectPath sessionPath = new ProjectPath(getProject(), corpus, session); paths.add(sessionPath); } final ProjectPathTransferable transferable = new ProjectPathTransferable(paths); event.startDrag(DragSource.DefaultCopyDrop, transferable); }); sessionDetails = new SessionDetailsPane(getProject()); sessionDetails.setLineWrap(true); sessionDetails.setRows(6); sessionDetails.setWrapStyleWord(true); sessionDetails.setBackground(Color.white); sessionDetails.setOpaque(true); JScrollPane sessionDetailsScroller = new JScrollPane(sessionDetails); JScrollPane corpusScroller = new JScrollPane(corpusList); JScrollPane sessionScroller = new JScrollPane(sessionList); blindModeBox = new JCheckBox("Blind transcription"); blindModeBox.setSelected(false); msgPanel = new StatusPanel(); corpusPanel = new JPanel(new BorderLayout()); corpusPanel.add(newCorpusButton, BorderLayout.NORTH); corpusPanel.add(corpusScroller, BorderLayout.CENTER); corpusPanel.add(corpusDetailsScroller, BorderLayout.SOUTH); sessionPanel = new JPanel(new BorderLayout()); sessionPanel.add(newSessionButton, BorderLayout.NORTH); sessionPanel.add(sessionScroller, BorderLayout.CENTER); sessionPanel.add(sessionDetailsScroller, BorderLayout.SOUTH); final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setLeftComponent(corpusPanel); splitPane.setRightComponent(sessionPanel); splitPane.setResizeWeight(0.5); // invoke later SwingUtilities.invokeLater(() -> { splitPane.setDividerLocation(0.5); }); // the frame layout String projectName = null; projectName = getProject().getName(); DialogHeader header = new DialogHeader(projectName, StringUtils.abbreviate(projectLoadPath, 80)); add(header, BorderLayout.NORTH); CellConstraints cc = new CellConstraints(); final JPanel topPanel = new JPanel(new FormLayout("pref, fill:pref:grow, right:pref", "pref")); topPanel.add(msgPanel, cc.xy(1, 1)); topPanel.add(blindModeBox, cc.xy(3, 1)); add(splitPane, BorderLayout.CENTER); add(topPanel, BorderLayout.SOUTH); // if no corpora are currently available, 'prompt' the user to create a new one if (getProject().getCorpora().size() == 0) { SwingUtilities.invokeLater(() -> { onSwapNewAndCreateCorpus(newCorpusButton); }); } else { SwingUtilities.invokeLater(() -> { corpusList.setSelectedIndex(0); }); } }
From source file:hoot.services.controllers.osm.ChangesetDbWriter.java
/** * Performs the OSM element database update portion for a changeset upload * request and returns the elements modified * <p>//from w ww . ja v a2 s .com * Unlike OSM, we don't keep track of multiple versions of the same element. * <p> * OSM element udpate process * <p> * create = insert new modify = update existing + insert new * <p> * hoot element update process * <p> * create = insert new modify = update existing * * @param changesetId * ID of the changeset being uploaded to * @param changeset * changeset contents * @return changeset upload response */ public Document write(long mapId, long changesetId, String changeset) throws Exception { Document changesetDoc; try { changesetDoc = ChangesetUploadXmlValidator.parseAndValidate(changeset); } catch (Exception e) { throw new RuntimeException("Error parsing changeset diff data: " + StringUtils.abbreviate(changeset, 100) + " (" + e.getMessage() + ")", e); } return write(mapId, changesetId, changesetDoc); }
From source file:hoot.services.controllers.osm.ElementResource.java
/** * <NAME>Element Service - Get Elements By IDs </NAME> * <DESCRIPTION>// ww w.j av a 2 s.c o m * Allows for retrieving multiple nodes, ways, or relations by numeric OSM element ID. Child element of ways * and relations are not added to the output (use the "full" method for that functionality). * The ID of the map owning the element must be specified in the query string. * </DESCRIPTION> * <PARAMETERS> * <mapId> * string; ID or name of the map the requested element belongs to * </mapId> * <elementIds> * string; OSM IDs of the requested elements * </elementIds> * <elementType> * string; OSM type of the requested element; valid values are "node", "way", or "relation" * </elementType> * </PARAMETERS> * <OUTPUT> * XML representation of the requested element * </OUTPUT> * <EXAMPLE> * <URL>http://localhost:8080/hoot-services/osm/api/0.6/node/1?mapId=1</URL> * <REQUEST_TYPE>GET</REQUEST_TYPE> * <INPUT> * </INPUT> * <OUTPUT> * OSM XML * see https://insightcloud.digitalglobe.com/redmine/projects/hootenany/wiki/User_-_OsmElementService#Get-Element-By-ID * </OUTPUT> * </EXAMPLE> * * Returns a single element item's XML for a given map without its element children * * @param mapId ID of the map the element belongs to * @param elementId OSM element ID of the element to retrieve * @param elementType OSM element type of the element to retrieve; valid values are: node, way, * or relation * @return element XML document * @throws Exception * @see https://insightcloud.digitalglobe.com/redmine/projects/hootenany/wiki/User_-_OsmElementService#Get-Element-By-ID */ @GET @Path("{elementType: nodes|ways|relations}") @Consumes({ MediaType.TEXT_PLAIN }) @Produces({ MediaType.TEXT_XML }) public Response getElements(@QueryParam("mapId") String mapId, @QueryParam("elementIds") final String elementIds, @PathParam("elementType") final String elemType) throws Exception { String elementType = elemType.substring(0, elemType.length() - 1); String[] elemIds = elementIds.split(","); final ElementType elementTypeVal = Element.elementTypeFromString(elementType); if (elementTypeVal == null) { ResourceErrorHandler.handleError("Invalid element type: " + elementType, Status.BAD_REQUEST, log); } Connection conn = DbUtils.createConnection(); Document elementDoc = null; try { log.debug("Initializing database connection..."); elementDoc = getElementsXml(mapId, elemIds, elementTypeVal, false, false, conn); } finally { DbUtils.closeConnection(conn); } log.debug("Returning response: " + StringUtils.abbreviate(XmlDocumentBuilder.toString(elementDoc), 100) + " ..."); return Response.ok(new DOMSource(elementDoc), MediaType.APPLICATION_XML) .header("Content-type", MediaType.APPLICATION_XML).build(); }
From source file:hoot.services.writers.osm.ChangesetDbWriter.java
/** * Performs the OSM element database update portion for a changeset upload * request and returns the elements modified * * Unlike OSM, we don't keep track of multiple versions of the same element. * * OSM element udpate process//from w w w. java2 s . c o m * * create = insert new modify = update existing + insert new * * hoot element update process * * create = insert new modify = update existing * * @param changesetId * ID of the changeset being uploaded to * @param reviewedItemsChangeset * changeset contents * @return changeset upload response * @throws Exception */ @SuppressWarnings("unchecked") public Document write(final long mapId, final long changesetId, final String reviewedItemsChangeset) throws Exception { log.debug("Uploading data for changeset with ID: " + changesetId + " ..."); Document reviewedItemsChangesetDoc = null; try { reviewedItemsChangesetDoc = (new ChangesetUploadXmlValidator()) .parseAndValidate(reviewedItemsChangeset); } catch (Exception e) { throw new Exception("Error parsing changeset diff data: " + StringUtils.abbreviate(reviewedItemsChangeset, 100) + " (" + e.getMessage() + ")"); } changeset = new Changeset(mapId, changesetId, conn); this.requestChangesetId = changeset.getId(); changeset.verifyAvailability(); if (changeset.requestChangesExceedMaxElementThreshold(reviewedItemsChangesetDoc)) { throw new Exception("Changeset maximum element threshold exceeded."); } requestChangesetMapId = mapId; Collection<XmlSerializable> changesetDiffElements = new ArrayList<XmlSerializable>(); changesetDiffElements.addAll(write(reviewedItemsChangesetDoc)); return (new ChangesetUploadResponseWriter()).writeResponse(changesetId, (List<XmlSerializable>) (List<?>) changesetDiffElements); }
From source file:edu.kit.dama.ui.repo.components.EntryRenderPanel.java
/** * Reset a single entry, e.g. to reload its state from the database. */// www . j a v a 2s. c o m private void reset() { titleField.setValue(object.getLabel()); titleField.setDescription(object.getLabel()); if (object.getLabel() != null) { titleLabel.setValue(StringUtils.abbreviate(object.getLabel(), 100)); titleLabel.setDescription(object.getLabel()); } else { titleLabel.setValue("dc:title"); titleLabel.setEnabled(false); } if (object.getInvestigation() != null) { descriptionArea.setValue(object.getInvestigation().getDescription()); descriptionLabel.setValue(StringUtils.abbreviate(object.getInvestigation().getDescription(), 250)); descriptionLabel.setDescription(object.getInvestigation().getDescription()); descriptionLabel.setEnabled(true); } else { descriptionLabel.setValue("dc:description"); descriptionLabel.setEnabled(false); } IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext()); try { DigitalObjectType favoriteType = mdm.findSingleResult( "SELECT t FROM DigitalObjectType t WHERE t.identifier='" + MyVaadinUI.FAVORITE_TYPE_IDENTIFIER + "' AND t.typeDomain='" + MyVaadinUI.FAVORITE_TYPE_DOMAIN + "'", DigitalObjectType.class); if (DigitalObjectTypeHelper.isTypeAssignedToObject(object, favoriteType, AuthorizationContext.factorySystemContext())) { //set favorite status starButton.setIcon(new ThemeResource("img/16x16/starred.png")); } else { //set no-favorite status starButton.setIcon(new ThemeResource("img/16x16/unstarred.png")); } } catch (Exception e) { LOGGER.error("Failed to reset 'favorite' status of digital object.", e); } downloadButton.setCaption("Download"); downloadButton.setIcon(new ThemeResource("img/32x32/download.png")); downloadButton.setDescription("Download the data of this digital object."); setupDownloadButton(); }
From source file:com.sonicle.webtop.core.xmpp.XMPPClient.java
private ChatMessage internalSendMessage(EntityBareJid chatJid, Message message) throws XMPPClientException { checkAuthentication();/* w w w .j a v a 2s . c o m*/ final EntityBareJid myJid = userJid.asEntityBareJid(); final String myResource = XMPPHelper.asResourcepartString(userJid.getResourceOrNull()); if (isInstantChat(chatJid)) { synchronized (instantChats) { IChat chatObj = instantChats.get(chatJid); if (chatObj == null) { EntityBareJid withUser = cacheInstantChatToFriend.get(chatJid.toString()); if (withUser != null) { newInstantChat(withUser); chatObj = instantChats.get(chatJid); } } if (chatObj != null) { try { final DateTime now = ChatMessage.nowTimestamp(); chatObj.getRawChat().send(message); if (logger.isTraceEnabled()) { logger.trace("Message sent [{}, {}]", now, StringUtils.abbreviate(message.getBody(), 20)); } ChatMessage chatMessage = new ChatMessage(chatJid, myJid, myResource, userNickname.toString(), now, now, message); // TODO: threadify this? try { listener.onChatRoomMessageSent(chatObj.getChatRoom(), chatMessage); } catch (Throwable t) { logger.error("Listener error", t); } return chatMessage; } catch (SmackException | InterruptedException ex) { throw new XMPPClientException(ex); } } } } else { synchronized (groupChats) { GChat chatObj = groupChats.get(chatJid); if (chatObj != null) { try { final DateTime now = ChatMessage.nowTimestamp(); chatObj.getRawChat().sendMessage(message); if (logger.isTraceEnabled()) { logger.trace("Message sent [{}, {}]", now, StringUtils.abbreviate(message.getBody(), 20)); } ChatMessage chatMessage = new ChatMessage(chatJid, myJid, myResource, userNickname.toString(), now, now, message); // TODO: threadify this? try { listener.onChatRoomMessageSent(chatObj.getChatRoom(), chatMessage); } catch (Throwable t) { logger.error("Listener error", t); } return chatMessage; } catch (SmackException | InterruptedException ex) { throw new XMPPClientException(ex); } } } } throw new XMPPClientException("Chat not found. Please create a chat before try to send messages in it!"); }
From source file:com.denimgroup.threadfix.service.report.ReportsServiceImpl.java
@SuppressWarnings("unchecked") private StringBuffer getDataVulnListReport(List<List<String>> rowParamsList, List<Integer> applicationIdList) { StringBuffer data = new StringBuffer(); data.append("Vulnerability List \n\n"); if (applicationIdList != null) { List<String> teamNames = applicationDao.getTeamNames(applicationIdList); String teamName = (teamNames != null && teamNames.size() == 1) ? teamNames.get(0) : "All"; data.append("Team: ").append(teamName).append(" \n"); String appName = ""; if (applicationIdList.size() == 1) { Application app = applicationDao.retrieveById(applicationIdList.get(0)); if (app != null) { appName = app.getName(); }//from w ww. ja v a2 s.com } else { appName = "All"; } data.append("Application: ").append(appName).append(" \n \n"); } DefaultConfiguration configuration = defaultConfigService.loadCurrentConfiguration(); List<CSVExportField> exportFields = configuration.getCsvExportFields(); if (exportFields.size() > 0) { String exportFieldsStr = join(", ", defaultConfigService.getDisplayNamesFromExportFields(exportFields)) + "\n"; data.append(exportFieldsStr); } else { data.append(getCSVExportHeaderString()); } for (List<String> row : rowParamsList) { for (int i = 0; i < row.size(); i++) { String str = ""; if (row.get(i) != null) { str = row.get(i); } if (str.length() > 31800) { str = StringUtils.abbreviate(str, 31800) + "\n...data exceeds space allotted for cell."; } str = StringEscapeUtils.escapeCsv(str); if (i < row.size() - 1) { data.append(str).append(","); } else { data.append(str).append(" \n"); } } } return data; }
From source file:io.bitsquare.gui.components.paymentmethods.BankForm.java
@Override protected void autoFillNameTextField() { if (useCustomAccountNameCheckBox != null && !useCustomAccountNameCheckBox.isSelected()) { String bankId = null;/*from ww w. j a v a 2s . com*/ String countryCode = bankAccountContractData.getCountryCode(); if (countryCode == null) countryCode = ""; if (BankUtil.isBankIdRequired(countryCode)) { bankId = bankIdInputTextField.getText(); if (bankId.length() > 9) bankId = StringUtils.abbreviate(bankId, 9); } else if (BankUtil.isBranchIdRequired(countryCode)) { bankId = branchIdInputTextField.getText(); if (bankId.length() > 9) bankId = StringUtils.abbreviate(bankId, 9); } else if (BankUtil.isBankNameRequired(countryCode)) { bankId = bankNameInputTextField.getText(); if (bankId.length() > 9) bankId = StringUtils.abbreviate(bankId, 9); } String accountNr = accountNrInputTextField.getText(); if (accountNr.length() > 9) accountNr = StringUtils.abbreviate(accountNr, 9); String method = BSResources.get(paymentAccount.getPaymentMethod().getId()); if (bankId != null && !bankId.isEmpty()) accountNameTextField.setText(method.concat(": ").concat(bankId).concat(", ").concat(accountNr)); else accountNameTextField.setText(method.concat(": ").concat(accountNr)); } }