List of usage examples for org.apache.commons.lang3 StringUtils strip
public static String strip(String str, final String stripChars)
Strips any of a set of characters from the start and end of a String.
From source file:org.gradle.integtests.fixtures.logging.GroupedOutputFixture.java
private String parse(String output) { tasks = new HashMap<String, GroupedTaskFixture>(); String strippedOutput = LogContent.of(output).removeAnsiChars().withNormalizedEol(); Matcher matcher = TASK_OUTPUT_PATTERN.matcher(strippedOutput); while (matcher.find()) { String taskName = matcher.group(1); String taskOutcome = matcher.group(2); String taskOutput = StringUtils.strip(matcher.group(3), "\n"); GroupedTaskFixture task = tasks.get(taskName); if (task == null) { task = new GroupedTaskFixture(taskName); tasks.put(taskName, task);//from w w w . j a v a 2 s . com } task.addOutput(taskOutput); task.setOutcome(taskOutcome); } return strippedOutput; }
From source file:org.jboss.as.test.integration.security.common.CoreUtils.java
/** * Strips square brackets - '[' and ']' from the given string. It can be used for instance to remove the square brackets * around IPv6 address in a URL./*from w ww.j a v a 2s .c o m*/ * * @param str string to strip * @return str without square brackets in it */ public static String stripSquareBrackets(final String str) { return StringUtils.strip(str, "[]"); }
From source file:org.jcamp.parser.CommonSpectrumJCAMPReader.java
License:asdf
/** * remove any remaining <>.//w w w .j av a 2s . c o m * * @param content * @return */ protected static String clean(String content) { return StringUtils.strip(content, "<>"); }
From source file:org.jsweet.transpiler.extension.Java2TypeScriptAdapter.java
@Override public boolean substituteMethodInvocation(MethodInvocationElement invocationElement) { Element targetType = invocationElement.getMethod().getEnclosingElement(); // This is some sort of hack to avoid invoking erased methods. // If the containing class is erased, we still invoke it because we // don't know if the class may be provided externally. // Pitfalls: (1) may erase invocations that are provided externally, (2) // if the invocation is the target of an enclosing invocation or field // access, TS compilation will fail. // So, we should probably find a better way to erase invocations (or at // least do it conditionally). if (hasAnnotationType(invocationElement.getMethod(), ANNOTATION_ERASED)) { print("null"); return true; }/*w w w . jav a 2 s . c o m*/ if (invocationElement.getTargetExpression() != null) { targetType = invocationElement.getTargetExpression().getTypeAsElement(); } String targetMethodName = invocationElement.getMethodName(); String targetClassName = targetType.toString(); if ("println".equals(targetMethodName)) { if (invocationElement.getTargetExpression() != null) { if ("System.out".equals(invocationElement.getTargetExpression().toString())) { PrinterAdapter print = print("console.info("); if (invocationElement.getArgumentCount() > 0) print.print(invocationElement.getArgument(0)); print.print(")"); return true; } if ("System.err".equals(invocationElement.getTargetExpression().toString())) { PrinterAdapter print = print("console.error("); if (invocationElement.getArgumentCount() > 0) print.print(invocationElement.getArgument(0)); print.print(")"); return true; } } } if ("super".equals(invocationElement.getMethodName())) { // we omit call to super if class extends nothing or if parent is an // interface if (getParent(JCClassDecl.class).extending == null // || context.isInterface(getParent(JCClassDecl.class).extending.type.tsym)) { return true; } // special case when subclassing a Java exception type if (((MethodInvocationElementSupport) invocationElement).getTree().meth instanceof JCIdent) { String superClassName = ((JCIdent) ((MethodInvocationElementSupport) invocationElement) .getTree().meth).sym.getEnclosingElement().getQualifiedName().toString(); if (context.getBaseThrowables().contains(superClassName)) { // ES6 would take the cause, but we ignore it so far for // backward compatibility // PATCH: // https://github.com/Microsoft/TypeScript/issues/5069 if (invocationElement.getArgumentCount() > 0) { print("super(").print(invocationElement.getArgument(0)).print(")"); print("; this.message=").print(invocationElement.getArgument(0)); } else { print("super()"); } return true; } } } if (targetType != null && targetType.getKind() == ElementKind.ENUM && (invocationElement.getTargetExpression() != null && !"this".equals(invocationElement.getTargetExpression().toString()))) { // TODO: enum type simple name will not be valid when uses as fully // qualified name (not imported) String relTarget = context.useModules ? targetType.getSimpleName().toString() : getRootRelativeName((Symbol) targetType); switch (targetMethodName) { case "name": print(relTarget).print("[").print(invocationElement.getTargetExpression()).print("]"); return true; case "ordinal": print(relTarget).print("[").print(relTarget).print("[") .print(invocationElement.getTargetExpression()).print("]").print("]"); return true; case "valueOf": if (invocationElement.getArgumentCount() == 1) { print("<any>").print(invocationElement.getTargetExpression()).print("[") .print(invocationElement.getArgument(0)).print("]"); return true; } break; case "values": print("function() { " + VAR_DECL_KEYWORD + " result: number[] = []; for(" + VAR_DECL_KEYWORD + " val in ").print(relTarget).print( ") { if(!isNaN(<any>val)) { result.push(parseInt(val,10)); } } return result; }()"); return true; } // enum objets wrapping if (invocationElement.getTargetExpression() != null) { if (invocationElement.getMethod().getModifiers().contains(Modifier.STATIC)) { print(invocationElement.getTargetExpression()) .print(Java2TypeScriptTranslator.ENUM_WRAPPER_CLASS_SUFFIX + ".") .print(invocationElement.getMethodName()).print("(") .printArgList(invocationElement.getArguments()).print(")"); return true; } } print(relTarget).print("[\"" + Java2TypeScriptTranslator.ENUM_WRAPPER_CLASS_WRAPPERS + "\"][") .print(invocationElement.getTargetExpression()).print("].") .print(invocationElement.getMethodName()).print("(") .printArgList(invocationElement.getArguments()).print(")"); return true; } if (targetClassName != null && targetMethodName != null) { switch (targetClassName) { case UTIL_CLASSNAME: case DEPRECATED_UTIL_CLASSNAME: switch (targetMethodName) { case "$export": if (!invocationElement.getArgument(0).isStringLiteral()) { report(invocationElement.getArgument(0), JSweetProblem.STRING_LITERAL_EXPECTED); } String varName = "_exportedVar_" + StringUtils.strip(invocationElement.getArgument(0).toString(), "\""); getPrinter().footer.append(VAR_DECL_KEYWORD + " " + varName + ";\n"); if (invocationElement.getArgumentCount() == 1) { print(varName); } else { print("{ " + varName + " = ").print(invocationElement.getArgument(1)).print("; "); print("console.log('" + JSweetTranspiler.EXPORTED_VAR_BEGIN + StringUtils.strip(invocationElement.getArgument(0).toString(), "\"") + "='+") .print(varName).print("+'" + JSweetTranspiler.EXPORTED_VAR_END + "') }"); } return true; case "array": case "function": case "string": case "bool": case "number": case "integer": case "object": printCastMethodInvocation(invocationElement); return true; case "any": print("(<any>"); printCastMethodInvocation(invocationElement); print(")"); return true; case "union": getPrinter().typeChecker.checkUnionTypeAssignment(context.types, getParent(), ((MethodInvocationElementSupport) invocationElement).getTree()); print("(<any>"); printCastMethodInvocation(invocationElement); print(")"); return true; case "typeof": print("typeof ").print(invocationElement.getArgument(0)); return true; case "equalsStrict": print("(").print(invocationElement.getArgument(0)).print(" === ") .print(invocationElement.getArgument(1)).print(")"); return true; case "notEqualsStrict": print("(").print(invocationElement.getArgument(0)).print(" !== ") .print(invocationElement.getArgument(1)).print(")"); return true; case "equalsLoose": print("(").print(invocationElement.getArgument(0)).print(" == ") .print(invocationElement.getArgument(1)).print(")"); return true; case "notEqualsLoose": print("(").print(invocationElement.getArgument(0)).print(" != ") .print(invocationElement.getArgument(1)).print(")"); return true; case "$map": if (invocationElement.getArgumentCount() % 2 != 0) { report(invocationElement, JSweetProblem.UNTYPED_OBJECT_ODD_PARAMETER_COUNT); } print("{"); com.sun.tools.javac.util.List<JCExpression> args = ((MethodInvocationElementSupport) invocationElement) .getTree().args; while (args != null && args.head != null) { String key = args.head.toString(); if (args.head.getTag() == Tag.LITERAL && key.startsWith("\"")) { key = key.substring(1, key.length() - 1); if (JJavaName.isJavaIdentifier(key)) { print(key); } else { print("\"" + key + "\""); } } else { report(invocationElement.getArgument(0), JSweetProblem.UNTYPED_OBJECT_WRONG_KEY, args.head.toString()); } print(": "); getPrinter().print(args.tail.head); ; args = args.tail.tail; if (args != null && args.head != null) { print(","); } } print("}"); return true; case "$apply": print("(<any>").print(invocationElement.getArgument(0)).print(")(") .printArgList(invocationElement.getArgumentTail()).print(")"); return true; case "$new": print("new (<any>").print(invocationElement.getArgument(0)).print(")(") .printArgList(invocationElement.getArgumentTail()).print(")"); return true; } } } if (targetMethodName != null) { switch (targetMethodName) { case INDEXED_GET_FUCTION_NAME: if (isWithinGlobals(targetClassName)) { if (invocationElement.getArgumentCount() == 1) { report(invocationElement, JSweetProblem.GLOBAL_INDEXER_GET); return true; } else { if (invocationElement.getArgument(0).toString().equals(GLOBALS_CLASS_NAME + ".class") || invocationElement.getArgument(0).toString() .endsWith("." + GLOBALS_CLASS_NAME + ".class")) { report(invocationElement, JSweetProblem.GLOBAL_INDEXER_GET); return true; } } } if (invocationElement.getTargetExpression() != null && !(UTIL_CLASSNAME.equals(targetClassName) || DEPRECATED_UTIL_CLASSNAME.equals(targetClassName))) { print(invocationElement.getTargetExpression()).print("[") .print(invocationElement.getArgument(0)).print("]"); } else { if (invocationElement.getArgumentCount() == 1) { print("this[").print(invocationElement.getArguments().get(0)).print("]"); } else { print(invocationElement.getArguments().get(0)).print("[") .print(invocationElement.getArguments().get(1)).print("]"); } } return true; case INDEXED_GET_STATIC_FUCTION_NAME: if (invocationElement.getArgumentCount() == 1 && isWithinGlobals(targetClassName)) { report(invocationElement, JSweetProblem.GLOBAL_INDEXER_GET); return true; } print(invocationElement.getTargetExpression()).print("[").print(invocationElement.getArgument(0)) .print("]"); return true; case INDEXED_SET_FUCTION_NAME: if (isWithinGlobals(targetClassName)) { if (invocationElement.getArgumentCount() == 2) { report(invocationElement, JSweetProblem.GLOBAL_INDEXER_SET); return true; } else { if (invocationElement.getArgument(0).toString().equals(GLOBALS_CLASS_NAME + ".class") || invocationElement.getArgument(0).toString() .endsWith(GLOBALS_CLASS_NAME + ".class")) { report(invocationElement, JSweetProblem.GLOBAL_INDEXER_SET); return true; } } } if (invocationElement.getTargetExpression() != null && !(UTIL_CLASSNAME.equals(targetClassName) || DEPRECATED_UTIL_CLASSNAME.equals(targetClassName))) { // check the type through the getter for (Element e : invocationElement.getTargetExpression().getTypeAsElement() .getEnclosedElements()) { if (e instanceof ExecutableElement && INDEXED_GET_FUCTION_NAME.equals(e.getSimpleName().toString())) { ExecutableElement getter = (ExecutableElement) e; TypeMirror getterType = getter.getReturnType(); TypeMirror getterIndexType = getter.getParameters().get(0).asType(); TypeMirror invokedIndexType = invocationElement.getArgument(0).getType(); TypeMirror invokedValueType = invocationElement.getArgument(1).getType(); boolean sameIndexType = types().isSameType(getterIndexType, invokedIndexType); if (sameIndexType && !types().isAssignable(invokedValueType, getterType)) { report(invocationElement.getArgument(1), JSweetProblem.INDEXED_SET_TYPE_MISMATCH, getterType); } } } print(invocationElement.getTargetExpression()).print("[") .print(invocationElement.getArgument(0)).print("] = ") .print(invocationElement.getArgument(1)); } else { if (invocationElement.getArgumentCount() == 2) { print("this[").print(invocationElement.getArgument(0)).print("] = <any>") .print(invocationElement.getArgument(1)); } else { print(invocationElement.getArgument(0)).print("[").print(invocationElement.getArgument(1)) .print("] = <any>").print(invocationElement.getArgument(2)); } } return true; case INDEXED_SET_STATIC_FUCTION_NAME: if (invocationElement.getArgumentCount() == 2 && isWithinGlobals(targetClassName)) { report(invocationElement, JSweetProblem.GLOBAL_INDEXER_SET); return true; } print(invocationElement.getTargetExpression()).print("[") .print(invocationElement.getArguments().get(0)).print("] = ") .print(invocationElement.getArguments().get(1)); return true; case INDEXED_DELETE_FUCTION_NAME: if (isWithinGlobals(targetClassName)) { if (invocationElement.getArgumentCount() == 1) { report(invocationElement, JSweetProblem.GLOBAL_DELETE); return true; } else { if (invocationElement.getArgument(0).toString().equals(GLOBALS_CLASS_NAME + ".class") || invocationElement.getArguments().get(0).toString() .endsWith(GLOBALS_CLASS_NAME + ".class")) { report(invocationElement, JSweetProblem.GLOBAL_DELETE); return true; } } } if (invocationElement.getTargetExpression() != null && !(UTIL_CLASSNAME.equals(targetClassName) || DEPRECATED_UTIL_CLASSNAME.equals(targetClassName))) { print("delete ").print(invocationElement.getTargetExpression()).print("[") .print(invocationElement.getArguments().get(0)).print("]"); } else { if (invocationElement.getArgumentCount() == 1) { print("delete this[").print(invocationElement.getArgument(0)).print("]"); } else { print("delete ").print(invocationElement.getArgument(0)).print("[") .print(invocationElement.getArgument(1)).print("]"); } } return true; case INDEXED_DELETE_STATIC_FUCTION_NAME: if (invocationElement.getArgumentCount() == 1 && isWithinGlobals(targetClassName)) { report(invocationElement, JSweetProblem.GLOBAL_DELETE); return true; } if (invocationElement.getTargetExpression() != null && !(UTIL_CLASSNAME.equals(targetClassName) || DEPRECATED_UTIL_CLASSNAME.equals(targetClassName))) { print("delete ").print(invocationElement.getTargetExpression()).print("[") .print(invocationElement.getArgument(0)).print("]"); } else { if (invocationElement.getArgumentCount() == 1) { print("delete ").print("this[").print(invocationElement.getArgument(0)).print("]"); } else { print("delete ").print(invocationElement.getArgument(0)).print("[") .print(invocationElement.getArgument(1)).print("]"); } } return true; } } if (invocationElement.getTargetExpression() == null && "$super".equals(targetMethodName)) { print("super(").printArgList(invocationElement.getArguments()).print(")"); return true; } if (invocationElement.getTargetExpression() != null && targetClassName != null && (targetClassName.startsWith(UTIL_PACKAGE + ".function.") || targetClassName.startsWith(Function.class.getPackage().getName()))) { if (!TypeChecker.jdkAllowed && targetClassName.startsWith(Function.class.getPackage().getName()) && TypeChecker.FORBIDDEN_JDK_FUNCTIONAL_METHODS.contains(targetMethodName)) { report(invocationElement, JSweetProblem.JDK_METHOD, targetMethodName); } printFunctionalInvocation(invocationElement.getTargetExpression(), targetMethodName, invocationElement.getArguments()); return true; } if (invocationElement.getTargetExpression() != null && targetClassName != null && targetClassName.equals(java.lang.Runnable.class.getName())) { printFunctionalInvocation(invocationElement.getTargetExpression(), targetMethodName, invocationElement.getArguments()); return true; } // built-in Java support if (targetClassName != null) { // expand macros switch (targetMethodName) { case "getMessage": if (targetType instanceof TypeElement) { if (types().isAssignable(targetType.asType(), util().getType(Throwable.class))) { print(invocationElement.getTargetExpression()).print(".message"); return true; } } break; case "getCause": if (targetType instanceof TypeElement) { if (types().isAssignable(targetType.asType(), util().getType(Throwable.class))) { print("(<Error>null)"); return true; } } break; case "printStackTrace": if (targetType instanceof TypeElement) { if (types().isAssignable(targetType.asType(), util().getType(Throwable.class))) { print("console.error(").print(invocationElement.getTargetExpression()).print(".message, ") .print(invocationElement.getTargetExpression()).print(")"); return true; } } break; } switch (targetClassName) { case "java.lang.String": case "java.lang.CharSequence": switch (targetMethodName) { case "valueOf": printMacroName(targetMethodName); if (invocationElement.getArgumentCount() == 3) { print("((str, index, len) => str.join('').substring(index, index + len))(") .printArgList(invocationElement.getArguments()).print(")"); } else { print("new String(").printArgList(invocationElement.getArguments()).print(").toString()"); } return true; case "subSequence": printMacroName(targetMethodName); print(invocationElement.getTargetExpression()).print(".substring(") .printArgList(invocationElement.getArguments()).print(")"); return true; // this macro should use 'includes' in ES6 case "contains": printMacroName(targetMethodName); print(invocationElement.getTargetExpression()).print(".indexOf(") .printArgList(invocationElement.getArguments()).print(") != -1"); return true; case "length": print(invocationElement.getTargetExpression()).print(".length"); return true; // this macro is not needed in ES6 case "startsWith": printMacroName(targetMethodName); print("((str, searchString, position = 0) => str.substr(position, searchString.length) === searchString)(") .print(invocationElement.getTargetExpression()).print(", ") .printArgList(invocationElement.getArguments()).print(")"); return true; case "endsWith": printMacroName(targetMethodName); print("((str, searchString) => { " + VAR_DECL_KEYWORD + " pos = str.length - searchString.length; " + VAR_DECL_KEYWORD + " lastIndex = str.indexOf(searchString, pos); return lastIndex !== -1 && lastIndex === pos; })(") .print(invocationElement.getTargetExpression()).print(", ") .printArgList(invocationElement.getArguments()).print(")"); return true; // this macro is not needed in ES6 case "codePointAt": printMacroName(targetMethodName); print(invocationElement.getTargetExpression()).print(".charCodeAt(") .printArgList(invocationElement.getArguments()).print(")"); return true; case "isEmpty": printMacroName(targetMethodName); print("(").print(invocationElement.getTargetExpression()).print(".length === 0)"); return true; case "compareToIgnoreCase": printMacroName(targetMethodName); print(invocationElement.getTargetExpression()).print(".toUpperCase().localeCompare(") .printArgList(invocationElement.getArguments()).print(".toUpperCase())"); return true; case "compareTo": printMacroName(targetMethodName); print(invocationElement.getTargetExpression()).print(".localeCompare(") .printArgList(invocationElement.getArguments()).print(")"); return true; case "equalsIgnoreCase": printMacroName(targetMethodName); print("((o1, o2) => o1.toUpperCase() === (o2===null?o2:o2.toUpperCase()))(") .print(invocationElement.getTargetExpression()).print(", ") .printArgList(invocationElement.getArguments()).print(")"); return true; case "toChars": printMacroName(targetMethodName); print("String.fromCharCode(").printArgList(invocationElement.getArguments()).print(")"); return true; // In ES6, we can use the Array.from method case "getBytes": printMacroName(targetMethodName); print("(").print(invocationElement.getTargetExpression()) .print(").split('').map(s => s.charCodeAt(0))"); return true; // In ES6, we can use the Array.from method case "toCharArray": printMacroName(targetMethodName); print("(").print(invocationElement.getTargetExpression()).print(").split('')"); return true; case "replaceAll": printMacroName(targetMethodName); print(invocationElement.getTargetExpression()).print(".replace(new RegExp(") .print(invocationElement.getArguments().get(0)).print(", 'g'),") .print(invocationElement.getArguments().get(1)).print(")"); return true; case "replace": printMacroName(targetMethodName); print(invocationElement.getTargetExpression()).print(".split(") .print(invocationElement.getArguments().get(0)).print(").join(") .print(invocationElement.getArguments().get(1)).print(")"); return true; case "lastIndexOf": print(invocationElement.getTargetExpression()).print(".lastIndexOf(") .printArgList(invocationElement.getArguments()).print(")"); return true; case "indexOf": if (invocationElement.getArgumentCount() == 1 && util().isNumber(invocationElement.getArgument(0).getType())) { print(invocationElement.getTargetExpression()).print(".indexOf(String.fromCharCode(") .print(invocationElement.getArgument(0)).print("))"); } else { print(invocationElement.getTargetExpression()).print(".indexOf(") .printArgList(invocationElement.getArguments()).print(")"); } return true; case "toLowerCase": if (invocationElement.getArgumentCount() > 0) { printMacroName(targetMethodName); print(invocationElement.getTargetExpression()).print(".toLowerCase()"); return true; } break; case "toUpperCase": if (invocationElement.getArgumentCount() > 0) { printMacroName(targetMethodName); print(invocationElement.getTargetExpression()).print(".toUpperCase()"); return true; } break; } break; case "java.lang.Character": switch (targetMethodName) { case "toChars": printMacroName(targetMethodName); print("String.fromCharCode(").printArgList(invocationElement.getArguments()).print(")"); return true; } break; case "java.lang.Float": case "java.lang.Double": case "java.lang.Integer": case "java.lang.Byte": case "java.lang.Long": case "java.lang.Short": switch (targetMethodName) { case "isNaN": printMacroName(targetMethodName); if (invocationElement.getArgumentCount() > 0) { print("isNaN(").printArgList(invocationElement.getArguments()).print(")"); return true; } else { print("isNaN(").print(invocationElement.getTargetExpression()).print(")"); return true; } case "isInfinite": printMacroName(targetMethodName); if (invocationElement.getArgumentCount() > 0) { print("((value) => Number.NEGATIVE_INFINITY === value || Number.POSITIVE_INFINITY === value)(") .printArgList(invocationElement.getArguments()).print(")"); return true; } else { print("((value) => Number.NEGATIVE_INFINITY === value || Number.POSITIVE_INFINITY === value)(") .print(invocationElement.getTargetExpression()).print(")"); return true; } case "intValue": printMacroName(targetMethodName); print("(").print(invocationElement.getTargetExpression()).print("|0").print(")"); return true; case "shortValue": printMacroName(targetMethodName); print("(").print(invocationElement.getTargetExpression()).print("|0").print(")"); return true; case "byteValue": printMacroName(targetMethodName); print("(").print(invocationElement.getTargetExpression()).print("|0").print(")"); return true; case "floatValue": printMacroName(targetMethodName); print(invocationElement.getTargetExpression()); return true; case "doubleValue": printMacroName(targetMethodName); print(invocationElement.getTargetExpression()); return true; case "longValue": printMacroName(targetMethodName); print(invocationElement.getTargetExpression()); return true; case "compare": if (invocationElement.getArgumentCount() == 2) { printMacroName(targetMethodName); print("(").print(invocationElement.getArgument(0)).print(" - ") .print(invocationElement.getArgument(1)).print(")"); return true; } break; case "toString": if (invocationElement.getArgumentCount() > 0) { printMacroName(targetMethodName); print("(''+(").print(invocationElement.getArgument(0)).print("))"); return true; } } break; case "java.lang.Math": switch (targetMethodName) { case "cbrt": printMacroName(targetMethodName); print("Math.pow(").printArgList(invocationElement.getArguments()).print(", 1/3)"); return true; case "copySign": printMacroName(targetMethodName); print("((magnitude, sign) => { if (sign < 0) { return (magnitude < 0) ? magnitude : -magnitude; } else { return (magnitude > 0) ? magnitude : -magnitude; } })(") .printArgList(invocationElement.getArguments()).print(")"); return true; case "cosh": printMacroName(targetMethodName); print("(x => (Math.exp(x) + Math.exp(-x)) / 2)(").printArgList(invocationElement.getArguments()) .print(")"); return true; case "expm1": printMacroName(targetMethodName); print("(d => { if (d == 0.0 || d === Number.NaN) { return d; } else if (!Number.POSITIVE_INFINITY === d && !Number.NEGATIVE_INFINITY === d) { if (d < 0) { return -1; } else { return Number.POSITIVE_INFINITY; } } })(") .printArgList(invocationElement.getArguments()).print(")"); return true; case "hypot": printMacroName(targetMethodName); print("(x => Math.sqrt(x * x + y * y))(").printArgList(invocationElement.getArguments()) .print(")"); return true; case "log10": printMacroName(targetMethodName); print("(x => Math.log(x) * Math.LOG10E)(").printArgList(invocationElement.getArguments()) .print(")"); return true; case "log1p": printMacroName(targetMethodName); print("(x => Math.log(x + 1))(").printArgList(invocationElement.getArguments()).print(")"); return true; case "rint": printMacroName(targetMethodName); print("(d => { if (d === Number.NaN) { return d; } else if (Number.POSITIVE_INFINITY === d || Number.NEGATIVE_INFINITY === d) { return d; } else if(d == 0) { return d; } else { return Math.round(d); } })(") .printArgList(invocationElement.getArguments()).print(")"); return true; case "scalb": printMacroName(targetMethodName); print("((d, scaleFactor) => { if (scaleFactor >= 31 || scaleFactor <= -31) { return d * Math.pow(2, scaleFactor); } else if (scaleFactor > 0) { return d * (1 << scaleFactor); } else if (scaleFactor == 0) { return d; } else { return d * 1 / (1 << -scaleFactor); } })(") .printArgList(invocationElement.getArguments()).print(")"); return true; case "signum": printMacroName(targetMethodName); print("(f => { if (f > 0) { return 1; } else if (f < 0) { return -1; } else { return 0; } })(") .printArgList(invocationElement.getArguments()).print(")"); return true; case "sinh": printMacroName(targetMethodName); print("(x => (Math.exp(x) - Math.exp(-x)) / 2)(").printArgList(invocationElement.getArguments()) .print(")"); return true; case "tanh": printMacroName(targetMethodName); print("(x => { if (x == Number.POSITIVE_INFINITY) { return 1; } else if (x == Number.NEGATIVE_INFINITY) { return -1; } double e2x = Math.exp(2 * x); return (e2x - 1) / (e2x + 1); })(") .printArgList(invocationElement.getArguments()).print(")"); return true; case "toDegrees": printMacroName(targetMethodName); print("(x => x * 180 / Math.PI)(").printArgList(invocationElement.getArguments()).print(")"); return true; case "toRadians": printMacroName(targetMethodName); print("(x => x * Math.PI / 180)(").printArgList(invocationElement.getArguments()).print(")"); return true; case "nextUp": delegateToEmulLayer(targetClassName, targetMethodName, invocationElement); return true; case "nextDown": delegateToEmulLayer(targetClassName, targetMethodName, invocationElement); return true; case "ulp": delegateToEmulLayer(targetClassName, targetMethodName, invocationElement); return true; case "IEEEremainder": delegateToEmulLayer(targetClassName, targetMethodName, invocationElement); return true; default: print("Math." + targetMethodName + "(").printArgList(invocationElement.getArguments()) .print(")"); return true; } case "java.lang.Class": switch (targetMethodName) { case "getName": if (context.options.isSupportGetClass()) { printMacroName(targetMethodName); getPrinter().print("(c => c[\"" + Java2TypeScriptTranslator.CLASS_NAME_IN_CONSTRUCTOR + "\"]?c[\"" + Java2TypeScriptTranslator.CLASS_NAME_IN_CONSTRUCTOR + "\"]:c[\"name\"])("); printTarget(invocationElement.getTargetExpression()); print(")"); return true; } else { if (invocationElement.getTargetExpression() != null && invocationElement.getTargetExpression().toString().endsWith(".class")) { printMacroName(targetMethodName); print("\"").print(util().getQualifiedName( ((DeclaredType) invocationElement.getTargetExpression().getType()) .getTypeArguments().get(0))) .print("\""); return true; } } break; case "getSimpleName": if (context.options.isSupportGetClass()) { printMacroName(targetMethodName); print("(c => c[\"" + Java2TypeScriptTranslator.CLASS_NAME_IN_CONSTRUCTOR + "\"]?c[\"" + Java2TypeScriptTranslator.CLASS_NAME_IN_CONSTRUCTOR + "\"].substring(c[\"" + Java2TypeScriptTranslator.CLASS_NAME_IN_CONSTRUCTOR + "\"].lastIndexOf('.')+1):c[\"name\"].substring(c[\"name\"].lastIndexOf('.')+1))("); printTarget(invocationElement.getTargetExpression()); print(")"); return true; } else { if (invocationElement.getTargetExpression() != null && invocationElement.getTargetExpression().toString().endsWith(".class")) { printMacroName(targetMethodName); print("\"").print(util().getQualifiedName( ((DeclaredType) invocationElement.getTargetExpression().getType()) .getTypeArguments().get(0))) .print("\""); return true; } } break; } break; // case "java.util.Date": // switch (targetMethodName) { // case "setFullYear": // printMacroName(targetMethodName); // print(fieldAccess.getExpression()).print(".setYear(").printArgList(invocation.args).print(")"); // // } // break; } if (invocationElement.getTargetExpression() != null && isMappedType(targetClassName) && targetClassName.startsWith("java.lang.")) { if (invocationElement.getMethod().getModifiers().contains(Modifier.STATIC)) { // delegation to javaemul delegateToEmulLayer(targetClassName, targetMethodName, invocationElement); return true; } else { switch (targetMethodName) { case "equals": printMacroName(targetMethodName); print("("); printTarget(invocationElement.getTargetExpression()).print(" === ") .printArgList(invocationElement.getArguments()).print(")"); return true; } } } } switch (targetMethodName) { case "getClass": print("(<any>"); printTarget(invocationElement.getTargetExpression()); print(".constructor)"); return true; case "hashCode": printMacroName(targetMethodName); print("(<any>(o => { if(o.hashCode) { return o.hashCode(); } else { return o.toString(); } })("); printTarget(invocationElement.getTargetExpression()); print("))"); return true; case "clone": if (!invocationElement.getMethod().getModifiers().contains(Modifier.STATIC) && invocationElement.getArgumentCount() == 0) { printMacroName(targetMethodName); if (invocationElement.getTargetExpression() != null && "super".equals(invocationElement.getTargetExpression().toString())) { JCClassDecl parent = getParent(JCClassDecl.class); if (parent.sym.getSuperclass() != null && !context.symtab.objectType.equals(parent.sym.getSuperclass())) { print("((o:any) => { if(super.clone!=undefined) { return super.clone(); } else { let clone = Object.create(o); for(let p in o) { if (o.hasOwnProperty(p)) clone[p] = o[p]; } return clone; } })(this)"); } else { print("((o:any) => { let clone = Object.create(o); for(let p in o) { if (o.hasOwnProperty(p)) clone[p] = o[p]; } return clone; })(this)"); } } else { print("((o:any) => { if(o.clone!=undefined) { return (<any>o).clone(); } else { let clone = Object.create(o); for(let p in o) { if (o.hasOwnProperty(p)) clone[p] = o[p]; } return clone; } })("); printTarget(invocationElement.getTargetExpression()); print(")"); } return true; } } return super.substituteMethodInvocation(invocationElement); }
From source file:org.jsweet.transpiler.typescript.Java2TypeScriptAdapter.java
protected boolean substituteMethodInvocation(JCMethodInvocation invocation, JCFieldAccess fieldAccess, TypeSymbol targetType, String targetClassName, String targetMethodName) { if (targetType != null && targetType.getKind() == ElementKind.ENUM && !"this".equals(fieldAccess.selected.toString())) { // TODO: enum type simple name will not be valid when uses as fully // qualified name (not imported) String relTarget = context.useModules ? targetType.getSimpleName().toString() : getRootRelativeName(targetType); if (targetMethodName.equals("name")) { print(relTarget).print("[").print(fieldAccess.selected).print("]"); return true; }/*w w w . j a v a2 s . c o m*/ if (targetMethodName.equals("ordinal")) { print(relTarget).print("[").print(relTarget).print("[").print(fieldAccess.selected).print("]") .print("]"); return true; } if (targetMethodName.equals("valueOf") && invocation.getArguments().size() == 1) { print("<any>").print(fieldAccess.selected).print("[").print(invocation.getArguments().head) .print("]"); return true; } if (targetMethodName.equals("values")) { getPrinter() .print("function() { " + VAR_DECL_KEYWORD + " result: number[] = []; for(" + VAR_DECL_KEYWORD + " val in ") .print(relTarget) .print(") { if(!isNaN(<any>val)) { result.push(parseInt(val,10)); } } return result; }()"); return true; } // enum objets wrapping if (fieldAccess != null && fieldAccess.sym instanceof MethodSymbol) { if (((MethodSymbol) fieldAccess.sym).isStatic()) { print(fieldAccess.selected).print(Java2TypeScriptTranslator.ENUM_WRAPPER_CLASS_SUFFIX + ".") .print(fieldAccess.name.toString()).print("(").printArgList(invocation.getArguments()) .print(")"); return true; } } print(relTarget).print("[\"" + Java2TypeScriptTranslator.ENUM_WRAPPER_CLASS_WRAPPERS + "\"][") .print(fieldAccess.selected).print("].").print(fieldAccess.name.toString()).print("(") .printArgList(invocation.getArguments()).print(")"); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "$export")) { if (invocation.args.head.getKind() != Kind.STRING_LITERAL) { report(invocation.args.head, JSweetProblem.STRING_LITERAL_EXPECTED); } String varName = "_exportedVar_" + StringUtils.strip(invocation.args.head.toString(), "\""); getPrinter().footer.append(VAR_DECL_KEYWORD + " " + varName + ";\n"); if (invocation.args.size() == 1) { print(varName); } else { print(varName + " = ").print(invocation.args.tail.head).print("; "); getPrinter() .print("console.log('" + JSweetTranspiler.EXPORTED_VAR_BEGIN + StringUtils.strip(invocation.args.head.toString(), "\"") + "='+") .print(varName).print("+'" + JSweetTranspiler.EXPORTED_VAR_END + "')"); } return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "array")) { printCastMethodInvocation(invocation); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "function")) { printCastMethodInvocation(invocation); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "string")) { printCastMethodInvocation(invocation); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "bool")) { printCastMethodInvocation(invocation); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "number")) { printCastMethodInvocation(invocation); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "integer")) { printCastMethodInvocation(invocation); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "any")) { print("(<any>"); printCastMethodInvocation(invocation); print(")"); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "object")) { printCastMethodInvocation(invocation); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "union")) { getPrinter().typeChecker.checkUnionTypeAssignment(context.types, getParent(), invocation); print("(<any>"); printCastMethodInvocation(invocation); print(")"); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "typeof")) { print("typeof ").print(invocation.getArguments().head); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "equalsStrict")) { print("(").print(invocation.getArguments().head).print(" === ") .print(invocation.getArguments().tail.head).print(")"); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "notEqualsStrict")) { print("(").print(invocation.getArguments().head).print(" !== ") .print(invocation.getArguments().tail.head).print(")"); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "equalsLoose")) { print("(").print(invocation.getArguments().head).print(" == ") .print(invocation.getArguments().tail.head).print(")"); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "notEqualsLoose")) { print("(").print(invocation.getArguments().head).print(" != ") .print(invocation.getArguments().tail.head).print(")"); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "$map")) { if (invocation.args.size() % 2 != 0) { report(invocation, JSweetProblem.UNTYPED_OBJECT_ODD_PARAMETER_COUNT); } print("{"); com.sun.tools.javac.util.List<JCExpression> args = invocation.args; while (args != null && args.head != null) { String key = args.head.toString(); if (args.head.getTag() == Tag.LITERAL && key.startsWith("\"")) { key = key.substring(1, key.length() - 1); if (JJavaName.isJavaIdentifier(key)) { print(key); } else { print("\"" + key + "\""); } } else { report(args.head, JSweetProblem.UNTYPED_OBJECT_WRONG_KEY, args.head.toString()); } print(": "); print(args.tail.head); args = args.tail.tail; if (args != null && args.head != null) { print(","); } } print("}"); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "$apply")) { print("(<any>").print(invocation.args.head).print(")(").printArgList(invocation.args.tail).print(")"); return true; } if (matchesMethod(targetClassName, targetMethodName, UTIL_CLASSNAME, "$new")) { print("new (<any>").print(invocation.args.head).print(")(").printArgList(invocation.args.tail) .print(")"); return true; } if (matchesMethod(targetClassName, targetMethodName, null, INDEXED_GET_FUCTION_NAME)) { if (isWithinGlobals(targetClassName)) { if (invocation.getArguments().size() == 1) { report(invocation, JSweetProblem.GLOBAL_INDEXER_GET); return true; } else { if (invocation.args.head.toString().endsWith(GLOBALS_CLASS_NAME + ".class")) { report(invocation, JSweetProblem.GLOBAL_INDEXER_GET); return true; } } } if (fieldAccess != null && !UTIL_CLASSNAME.equals(targetClassName)) { print(fieldAccess.selected).print("[").print(invocation.args.head).print("]"); } else { if (invocation.args.length() == 1) { print("this[").print(invocation.args.head).print("]"); } else { print(invocation.args.head).print("[").print(invocation.args.tail.head).print("]"); } } return true; } if (matchesMethod(targetClassName, targetMethodName, null, INDEXED_GET_STATIC_FUCTION_NAME)) { if (invocation.getArguments().size() == 1 && isWithinGlobals(targetClassName)) { report(invocation, JSweetProblem.GLOBAL_INDEXER_GET); return true; } print(fieldAccess.selected).print("[").print(invocation.args.head).print("]"); return true; } if (matchesMethod(targetClassName, targetMethodName, null, INDEXED_SET_FUCTION_NAME)) { if (isWithinGlobals(targetClassName)) { if (invocation.getArguments().size() == 2) { report(invocation, JSweetProblem.GLOBAL_INDEXER_SET); return true; } else { if (invocation.args.head.toString().endsWith(GLOBALS_CLASS_NAME + ".class")) { report(invocation, JSweetProblem.GLOBAL_INDEXER_SET); return true; } } } if (fieldAccess != null && !UTIL_CLASSNAME.equals(targetClassName)) { // check the type through the getter for (Symbol e : fieldAccess.selected.type.tsym.getEnclosedElements()) { if (e instanceof MethodSymbol && INDEXED_GET_FUCTION_NAME.equals(e.getSimpleName().toString())) { MethodSymbol getMethod = (MethodSymbol) e; TypeSymbol getterType = getMethod.getReturnType().tsym; TypeSymbol getterIndexType = getMethod.getParameters().get(0).type.tsym; TypeSymbol invokedIndexType = invocation.args.head.type.tsym; TypeSymbol invokedValueType = invocation.args.tail.head.type.tsym; boolean sameIndexType = getterIndexType.equals(invokedIndexType); if (sameIndexType && !Util.isAssignable(context.types, getterType, invokedValueType)) { report(invocation.args.tail.head, JSweetProblem.INDEXED_SET_TYPE_MISMATCH, getterType); } } } print(fieldAccess.selected).print("[").print(invocation.args.head).print("] = ") .print(invocation.args.tail.head); } else { if (invocation.args.length() == 2) { print("this[").print(invocation.args.head).print("] = <any>").print(invocation.args.tail.head); } else { print(invocation.args.head).print("[").print(invocation.args.tail.head).print("] = <any>") .print(invocation.args.tail.tail.head); } } return true; } if (matchesMethod(targetClassName, targetMethodName, null, INDEXED_SET_STATIC_FUCTION_NAME)) { if (invocation.getArguments().size() == 2 && isWithinGlobals(targetClassName)) { report(invocation, JSweetProblem.GLOBAL_INDEXER_SET); return true; } print(fieldAccess.selected).print("[").print(invocation.args.head).print("] = ") .print(invocation.args.tail.head); return true; } if (matchesMethod(targetClassName, targetMethodName, null, INDEXED_DELETE_FUCTION_NAME)) { if (isWithinGlobals(targetClassName)) { if (invocation.getArguments().size() == 1) { report(invocation, JSweetProblem.GLOBAL_DELETE); return true; } else { if (invocation.args.head.toString().endsWith(GLOBALS_CLASS_NAME + ".class")) { report(invocation, JSweetProblem.GLOBAL_DELETE); return true; } } } if (fieldAccess != null && !UTIL_CLASSNAME.equals(targetClassName)) { print("delete ").print(fieldAccess.selected).print("[").print(invocation.args.head).print("]"); } else { if (invocation.args.length() == 1) { print("delete this[").print(invocation.args.head).print("]"); } else { print("delete ").print(invocation.args.head).print("[").print(invocation.args.tail.head) .print("]"); } } return true; } if (matchesMethod(targetClassName, targetMethodName, null, INDEXED_DELETE_STATIC_FUCTION_NAME)) { if (invocation.getArguments().size() == 1 && isWithinGlobals(targetClassName)) { report(invocation, JSweetProblem.GLOBAL_DELETE); return true; } if (fieldAccess != null && !UTIL_CLASSNAME.equals(targetClassName)) { print("delete ").print(fieldAccess.selected).print("[").print(invocation.args.head).print("]"); } else { if (invocation.args.length() == 1) { print("delete ").print("this[").print(invocation.args.head).print("]"); } else { print("delete ").print(invocation.args.head).print("[").print(invocation.args.tail.head) .print("]"); } } return true; } if (targetClassName != null && targetClassName.endsWith(GLOBALS_CLASS_NAME) && (invocation.getMethodSelect() instanceof JCFieldAccess)) { if (context.useModules) { // if(!context.getImportedNames(getCompilationUnit().getSourceFile().getName()).contains(targetMethodName)) // { // // } if (!((ClassSymbol) targetType).sourcefile.getName() .equals(getCompilationUnit().sourcefile.getName())) { // TODO: when using several qualified Globals classes, we // need to disambiguate (use qualified name with // underscores) print(GLOBALS_CLASS_NAME).print("."); } } Map<String, VarSymbol> vars = new HashMap<>(); Util.fillAllVariablesInScope(vars, getStack(), invocation, getParent(JCMethodDecl.class)); if (vars.containsKey(targetMethodName)) { report(invocation, JSweetProblem.HIDDEN_INVOCATION, targetMethodName); } Symbol s = Util.findFirstMethodDeclarationInType(targetType, targetMethodName); if (s == null) { print(targetMethodName).print("(").printArgList(invocation.args).print(")"); } else { getPrinter().printIdentifier(s).print("(").printArgList(invocation.args).print(")"); } return true; } if (fieldAccess == null && matchesMethod(targetClassName, targetMethodName, null, "$super")) { print("super(").printArgList(invocation.args).print(")"); return true; } if (fieldAccess != null && targetClassName != null && (targetClassName.startsWith(UTIL_PACKAGE + ".function.") || targetClassName.startsWith(Function.class.getPackage().getName()))) { if (!TypeChecker.jdkAllowed && targetClassName.startsWith(Function.class.getPackage().getName()) && TypeChecker.FORBIDDEN_JDK_FUNCTIONAL_METHODS.contains(targetMethodName)) { report(invocation, JSweetProblem.JDK_METHOD, targetMethodName); } print(fieldAccess.getExpression()).print("(").printArgList(invocation.args).print(")"); return true; } if (fieldAccess != null && targetClassName != null && targetClassName.equals(java.lang.Runnable.class.getName())) { print(fieldAccess.getExpression()).print("(").printArgList(invocation.args).print(")"); return true; } // built-in Java support if (targetClassName != null) { // expand macros switch (targetMethodName) { case "getMessage": if (targetType instanceof ClassSymbol) { if (Util.hasParent((ClassSymbol) targetType, "java.lang.Throwable")) { print(fieldAccess.getExpression()).print(".message"); return true; } } break; case "getCause": if (targetType instanceof ClassSymbol) { if (Util.hasParent((ClassSymbol) targetType, "java.lang.Throwable")) { print("(<Error>null)"); return true; } } break; case "printStackTrace": if (targetType instanceof ClassSymbol) { if (Util.hasParent((ClassSymbol) targetType, "java.lang.Throwable")) { print("console.error(").print(fieldAccess.getExpression()).print(".message, ") .print(fieldAccess.getExpression()).print(")"); return true; } } break; } switch (targetClassName) { case "java.lang.String": case "java.lang.CharSequence": switch (targetMethodName) { case "valueOf": printMacroName(targetMethodName); if (invocation.args.length() == 3) { print("((str, index, len) => str.join('').substring(index, index + len))(") .printArgList(invocation.args).print(")"); } else { print("new String(").printArgList(invocation.args).print(").toString()"); } return true; case "subSequence": printMacroName(targetMethodName); print(fieldAccess.getExpression()).print(".substring(").printArgList(invocation.args) .print(")"); return true; // this macro should use 'includes' in ES6 case "contains": printMacroName(targetMethodName); print(fieldAccess.getExpression()).print(".indexOf(").printArgList(invocation.args) .print(") != -1"); return true; case "length": print(fieldAccess.getExpression()).print(".length"); return true; // this macro is not needed in ES6 case "startsWith": printMacroName(targetMethodName); getPrinter().print( "((str, searchString, position = 0) => str.substr(position, searchString.length) === searchString)(") .print(fieldAccess.getExpression()).print(", ").printArgList(invocation.args) .print(")"); return true; case "endsWith": printMacroName(targetMethodName); getPrinter().print("((str, searchString) => { " + VAR_DECL_KEYWORD + " pos = str.length - searchString.length; " + VAR_DECL_KEYWORD + " lastIndex = str.indexOf(searchString, pos); return lastIndex !== -1 && lastIndex === pos; })(") .print(fieldAccess.getExpression()).print(", ").printArgList(invocation.args) .print(")"); return true; // this macro is not needed in ES6 case "codePointAt": printMacroName(targetMethodName); print(fieldAccess.getExpression()).print(".charCodeAt(").printArgList(invocation.args) .print(")"); return true; case "isEmpty": printMacroName(targetMethodName); print("(").print(fieldAccess.getExpression()).print(".length === 0)"); return true; case "compareToIgnoreCase": printMacroName(targetMethodName); print(fieldAccess.getExpression()).print(".toUpperCase().localeCompare(") .printArgList(invocation.args).print(".toUpperCase())"); return true; case "compareTo": printMacroName(targetMethodName); print(fieldAccess.getExpression()).print(".localeCompare(").printArgList(invocation.args) .print(")"); return true; case "equalsIgnoreCase": printMacroName(targetMethodName); print("((o1, o2) => o1.toUpperCase() === (o2===null?o2:o2.toUpperCase()))(") .print(fieldAccess.getExpression()).print(", ").printArgList(invocation.args) .print(")"); return true; case "toChars": printMacroName(targetMethodName); print("String.fromCharCode(").printArgList(invocation.args).print(")"); return true; // In ES6, we can use the Array.from method case "getBytes": printMacroName(targetMethodName); print("(").print(fieldAccess.getExpression()).print(").split('').map(s => s.charCodeAt(0))"); return true; // In ES6, we can use the Array.from method case "toCharArray": printMacroName(targetMethodName); print("(").print(fieldAccess.getExpression()).print(").split('')"); return true; case "replaceAll": printMacroName(targetMethodName); print(fieldAccess.getExpression()).print(".replace(new RegExp(").print(invocation.args.head) .print(", 'g'),").print(invocation.args.tail.head).print(")"); return true; case "replace": printMacroName(targetMethodName); print(fieldAccess.getExpression()).print(".split(").print(invocation.args.head).print(").join(") .print(invocation.args.tail.head).print(")"); return true; case "lastIndexOf": print(fieldAccess.getExpression()).print(".lastIndexOf(").printArgList(invocation.args) .print(")"); return true; case "indexOf": print(fieldAccess.getExpression()).print(".indexOf(").printArgList(invocation.args).print(")"); return true; case "toLowerCase": if (!invocation.args.isEmpty()) { printMacroName(targetMethodName); print(fieldAccess.getExpression()).print(".toLowerCase()"); return true; } break; case "toUpperCase": if (!invocation.args.isEmpty()) { printMacroName(targetMethodName); print(fieldAccess.getExpression()).print(".toUpperCase()"); return true; } break; } break; case "java.lang.Character": switch (targetMethodName) { case "toChars": printMacroName(targetMethodName); print("String.fromCharCode(").printArgList(invocation.args).print(")"); return true; } break; case "java.lang.Float": case "java.lang.Double": case "java.lang.Integer": case "java.lang.Byte": case "java.lang.Long": case "java.lang.Short": switch (targetMethodName) { case "isNaN": printMacroName(targetMethodName); if (!invocation.args.isEmpty()) { print("isNaN(").printArgList(invocation.args).print(")"); return true; } else { print("isNaN(").print(fieldAccess.getExpression()).print(")"); return true; } case "isInfinite": printMacroName(targetMethodName); if (!invocation.args.isEmpty()) { getPrinter().print( "((value) => Number.NEGATIVE_INFINITY === value || Number.POSITIVE_INFINITY === value)(") .printArgList(invocation.args).print(")"); return true; } else { getPrinter().print( "((value) => Number.NEGATIVE_INFINITY === value || Number.POSITIVE_INFINITY === value)(") .print(fieldAccess.getExpression()).print(")"); return true; } case "intValue": printMacroName(targetMethodName); print("(").print(fieldAccess.getExpression()).print("|0").print(")"); return true; case "toString": if (!invocation.args.isEmpty()) { printMacroName(targetMethodName); print("(''+").print(invocation.args.head).print(")"); return true; } } break; case "java.lang.Math": switch (targetMethodName) { case "cbrt": printMacroName(targetMethodName); print("Math.pow(").printArgList(invocation.args).print(", 1/3)"); return true; case "copySign": printMacroName(targetMethodName); getPrinter().print( "((magnitude, sign) => { if (sign < 0) { return (magnitude < 0) ? magnitude : -magnitude; } else { return (magnitude > 0) ? magnitude : -magnitude; } })(") .printArgList(invocation.args).print(")"); return true; case "cosh": printMacroName(targetMethodName); print("(x => (Math.exp(x) + Math.exp(-x)) / 2)(").printArgList(invocation.args).print(")"); return true; case "expm1": printMacroName(targetMethodName); getPrinter().print( "(d => { if (d == 0.0 || d === Number.NaN) { return d; } else if (!Number.POSITIVE_INFINITY === d && !Number.NEGATIVE_INFINITY === d) { if (d < 0) { return -1; } else { return Number.POSITIVE_INFINITY; } } })(") .printArgList(invocation.args).print(")"); return true; case "hypot": printMacroName(targetMethodName); print("(x => Math.sqrt(x * x + y * y))(").printArgList(invocation.args).print(")"); return true; case "log10": printMacroName(targetMethodName); print("(x => Math.log(x) * Math.LOG10E)(").printArgList(invocation.args).print(")"); return true; case "log1p": printMacroName(targetMethodName); print("(x => Math.log(x + 1))(").printArgList(invocation.args).print(")"); return true; case "rint": printMacroName(targetMethodName); getPrinter().print( "(d => { if (d === Number.NaN) { return d; } else if (Number.POSITIVE_INFINITY === d || Number.NEGATIVE_INFINITY === d) { return d; } else if(d == 0) { return d; } else { return Math.round(d); } })(") .printArgList(invocation.args).print(")"); return true; case "scalb": printMacroName(targetMethodName); getPrinter().print( "((d, scaleFactor) => { if (scaleFactor >= 31 || scaleFactor <= -31) { return d * Math.pow(2, scaleFactor); } else if (scaleFactor > 0) { return d * (1 << scaleFactor); } else if (scaleFactor == 0) { return d; } else { return d * 1 / (1 << -scaleFactor); } })(") .printArgList(invocation.args).print(")"); return true; case "signum": printMacroName(targetMethodName); getPrinter().print( "(f => { if (f > 0) { return 1; } else if (f < 0) { return -1; } else { return 0; } })(") .printArgList(invocation.args).print(")"); return true; case "sinh": printMacroName(targetMethodName); print("(x => (Math.exp(x) - Math.exp(-x)) / 2)(").printArgList(invocation.args).print(")"); return true; case "tanh": printMacroName(targetMethodName); getPrinter().print( "(x => { if (x == Number.POSITIVE_INFINITY) { return 1; } else if (x == Number.NEGATIVE_INFINITY) { return -1; } double e2x = Math.exp(2 * x); return (e2x - 1) / (e2x + 1); })(") .printArgList(invocation.args).print(")"); return true; case "toDegrees": printMacroName(targetMethodName); print("(x => x * 180 / Math.PI)(").printArgList(invocation.args).print(")"); return true; case "toRadians": printMacroName(targetMethodName); print("(x => x * Math.PI / 180)(").printArgList(invocation.args).print(")"); return true; case "nextUp": delegateToEmulLayer(targetClassName, targetMethodName, invocation); return true; case "nextDown": delegateToEmulLayer(targetClassName, targetMethodName, invocation); return true; case "ulp": delegateToEmulLayer(targetClassName, targetMethodName, invocation); return true; case "IEEEremainder": delegateToEmulLayer(targetClassName, targetMethodName, invocation); return true; default: print("Math." + targetMethodName + "(").printArgList(invocation.args).print(")"); return true; } case "java.lang.Class": switch (targetMethodName) { case "getName": if (context.options.isSupportGetClass()) { printMacroName(targetMethodName); getPrinter().print("(c => c[\"" + Java2TypeScriptTranslator.CLASS_NAME_IN_CONSTRUCTOR + "\"]?c[\"" + Java2TypeScriptTranslator.CLASS_NAME_IN_CONSTRUCTOR + "\"]:c[\"name\"])("); printTarget(fieldAccess.getExpression()); print(")"); return true; } else { if (fieldAccess != null && fieldAccess.selected.toString().endsWith(".class")) { printMacroName(targetMethodName); print("\"").print(fieldAccess.selected.type.getTypeArguments().get(0).tsym .getQualifiedName().toString()).print("\""); return true; } } break; case "getSimpleName": if (context.options.isSupportGetClass()) { printMacroName(targetMethodName); print("(c => c[\"" + Java2TypeScriptTranslator.CLASS_NAME_IN_CONSTRUCTOR + "\"]?c[\"" + Java2TypeScriptTranslator.CLASS_NAME_IN_CONSTRUCTOR + "\"].substring(c[\"" + Java2TypeScriptTranslator.CLASS_NAME_IN_CONSTRUCTOR + "\"].lastIndexOf('.')+1):c[\"name\"].substring(c[\"name\"].lastIndexOf('.')+1))("); printTarget(fieldAccess.getExpression()); print(")"); return true; } else { if (fieldAccess != null && fieldAccess.selected.toString().endsWith(".class")) { printMacroName(targetMethodName); print("\"").print(fieldAccess.selected.type.getTypeArguments().get(0).tsym .getSimpleName().toString()).print("\""); return true; } } break; } break; // case "java.util.Date": // switch (targetMethodName) { // case "setFullYear": // printMacroName(targetMethodName); // print(fieldAccess.getExpression()).print(".setYear(").printArgList(invocation.args).print(")"); // // } // break; } if (fieldAccess != null && typesMapping.containsKey(targetClassName) && targetClassName.startsWith("java.lang.")) { if (fieldAccess.sym.isStatic()) { // delegation to javaemul delegateToEmulLayer(targetClassName, targetMethodName, invocation); return true; } else { switch (targetMethodName) { case "equals": printMacroName(targetMethodName); print("("); printTarget(fieldAccess.getExpression()).print(" === ").printArgList(invocation.args) .print(")"); return true; case "hashCode": printMacroName(targetMethodName); print("(<any>"); printTarget(fieldAccess.getExpression()).print(".toString())"); return true; case "clone": printMacroName(targetMethodName); delegateToEmulLayerStatic(targetClassName, targetMethodName, fieldAccess.getExpression()); return true; } } } } if ("getClass".equals(targetMethodName)) { print("(<any>"); if (fieldAccess != null) { printTarget(fieldAccess.getExpression()); } else { print("this"); } print(".constructor)"); return true; } if (!JSweetConfig.isJDKReplacementMode()) { Log log = Log.instance(context); if (String.class.getName().equals(targetClassName)) { log.rawError(invocation.pos, "Invalid use of native Java class. Use string(a_java_string) to convert to JSweet String first."); } } return super.substituteMethodInvocation(invocation); }
From source file:org.jtwig.loader.impl.ClasspathLoader.java
protected String normalizeName(String name) { if (StringUtils.startsWithIgnoreCase(name, "classpath:")) { name = StringUtils.removeStartIgnoreCase(name, "classpath:"); }/*from w w w. j a v a 2 s . c o m*/ name = "/" + StringUtils.strip(name, "/\\"); String path = new File(name).toURI().normalize().getRawPath(); return StringUtils.stripStart(path, "/\\"); }
From source file:org.jtwig.loader.impl.FileLoader.java
protected void validateName(String name) throws ResourceException { name = StringUtils.strip(name, "/"); String[] parts = StringUtils.split(name, "/"); int level = 0; for (String part : parts) { if ("..".equals(part)) { --level;//from ww w.ja v a 2 s. co m } else if (".".equals(part)) { ++level; } if (level < 0) { throw new ResourceException("Cannot load template outside allowed directories."); } } }
From source file:org.jtwig.util.LoaderUtil.java
public static String getCacheKey(String relative) { if (StringUtils.isBlank(relative)) { return null; }//from w ww. j a v a 2 s . c o m return StringUtils.strip(relative, "/").replaceAll("/+", "_"); }
From source file:org.karndo.piracy.Scraper.java
/** * /* w ww .j a v a 2 s. c o m*/ * @param url * @param io * @return */ public LinkedList<PiracyEvent> parse_piracy_data(String url, InputOutput io) throws IOException { //use the private method in this class to get the data String data = get_piracy_data(url); System.out.println(data); //strip everything before "icons" String temp = StringUtils.strip(data, "head.ready(function() {fabrikMap45 = new FbGoogleMapViz('table_map', {\"icons\":["); temp = "\"" + temp; //after stripping the first section, the data can be split using the //'curly brackets' String[] events = StringUtils.split(temp, "{"); LinkedList<PiracyEvent> events_list = new LinkedList<PiracyEvent>(); //some parameters for holding data from the event strings PiracyEvent event1 = null; double longitude = 0.0; double latitude = 0.0; String attack_id = ""; String vessel_type = ""; String status = ""; Date date = null; for (String str : events) { try { //Strip out the latitude and longitude String lat1 = StringUtils.strip(StringUtils.substringBetween(str, "\"0\":", ","), "\""); String long1 = StringUtils.strip(StringUtils.substringBetween(str, "\"1\":", ","), "\""); //parse the values into doubles latitude = Double.parseDouble(lat1); longitude = Double.parseDouble(long1); //strip out the attack id. attack_id = StringUtils.strip(StringUtils.substringBetween(str, "\"2\":", "<br \\/>"), "\"Attack ID:"); //strip out the date String date_str = StringUtils.strip(StringUtils.substringBetween(str, "Date:", "<br"), "Date:"); // TODO change this to a GMT time-format date = DateUtils.parseDate(StringUtils.trim(date_str), "yyyy-MM-dd"); //strip out the Vessel type vessel_type = StringUtils.strip(StringUtils.substringBetween(str, "Vessel:", "<br \\/>"), "Vessel:"); //strip out the status status = StringUtils.strip(StringUtils.substringBetween(str, "Status:", "<br \\/>"), "Status:"); //create a piracy event event1 = new PiracyEvent(latitude, longitude, attack_id, date, StringUtils.trim(status), StringUtils.trim(vessel_type)); events_list.add(event1); //print to the supplied InputOutput from the main window io.getOut().println(event1); } catch (ParseException ex) { System.err.println("A parse exception occurred parsing the date"); System.err.println(ex.getMessage()); } finally { } } return events_list; }
From source file:org.lizardirc.beancounter.commands.earthquake.GeoJsonFeatureProperty.java
public Stream<String> getAlternateIds() { return Stream.of(StringUtils.strip(ids, ", ").split(",")).distinct(); }