code
stringlengths
73
34.1k
label
stringclasses
1 value
private static int findNext(boolean reverse, int pos) { boolean backwards = IS_BACKWARDS_CHECKBOX.isSelected(); backwards = backwards ? !reverse : reverse; String pattern = (String) FIND_FIELD.getSelectedItem(); if (pattern != null && pattern.length() > 0) { try { Document doc = textComponent.getDocument(); doc.getText(0, doc.getLength(), SEGMENT); } catch (Exception e) { // should NEVER reach here e.printStackTrace(); } pos += textComponent.getSelectedText() == null ? (backwards ? -1 : 1) : 0; char first = backwards ? pattern.charAt(pattern.length() - 1) : pattern.charAt(0); char oppFirst = Character.isUpperCase(first) ? Character.toLowerCase(first) : Character.toUpperCase(first); int start = pos; boolean wrapped = WRAP_SEARCH_CHECKBOX.isSelected(); int end = backwards ? 0 : SEGMENT.getEndIndex(); pos += backwards ? -1 : 1; int length = textComponent.getDocument().getLength(); if (pos > length) { pos = wrapped ? 0 : length; } boolean found = false; while (!found && (backwards ? pos > end : pos < end)) { found = !MATCH_CASE_CHECKBOX.isSelected() && SEGMENT.array[pos] == oppFirst; found = found ? found : SEGMENT.array[pos] == first; if (found) { pos += backwards ? -(pattern.length() - 1) : 0; for (int i = 0; found && i < pattern.length(); i++) { char c = pattern.charAt(i); found = SEGMENT.array[pos + i] == c; if (!MATCH_CASE_CHECKBOX.isSelected() && !found) { c = Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c); found = SEGMENT.array[pos + i] == c; } } } if (!found) { pos += backwards ? -1 : 1; if (pos == end && wrapped) { pos = backwards ? SEGMENT.getEndIndex() : 0; end = start; wrapped = false; } } } pos = found ? pos : -1; } return pos; }
java
protected static void invalidateSwitchPoints() { if (LOG_ENABLED) { LOG.info("invalidating switch point"); } SwitchPoint old = switchPoint; switchPoint = new SwitchPoint(); synchronized(IndyInterface.class) { SwitchPoint.invalidateAll(new SwitchPoint[]{old}); } }
java
public static CallSite bootstrapCurrent(Lookup caller, String name, MethodType type) { return realBootstrap(caller, name, CALL_TYPES.METHOD.ordinal(), type, false, true, false); }
java
private static CallSite realBootstrap(Lookup caller, String name, int callID, MethodType type, boolean safe, boolean thisCall, boolean spreadCall) { // since indy does not give us the runtime types // we produce first a dummy call site, which then changes the target to one, // that does the method selection including the the direct call to the // real method. MutableCallSite mc = new MutableCallSite(type); MethodHandle mh = makeFallBack(mc,caller.lookupClass(),name,callID,type,safe,thisCall,spreadCall); mc.setTarget(mh); return mc; }
java
public void addCell(TableLayoutCell cell) { GridBagConstraints constraints = cell.getConstraints(); constraints.insets = new Insets(cellpadding, cellpadding, cellpadding, cellpadding); add(cell.getComponent(), constraints); }
java
public void addClass(ClassNode node) { node = node.redirect(); String name = node.getName(); ClassNode stored = classes.get(name); if (stored != null && stored != node) { // we have a duplicate class! // One possibility for this is, that we declared a script and a // class in the same file and named the class like the file SourceUnit nodeSource = node.getModule().getContext(); SourceUnit storedSource = stored.getModule().getContext(); String txt = "Invalid duplicate class definition of class " + node.getName() + " : "; if (nodeSource == storedSource) { // same class in same source txt += "The source " + nodeSource.getName() + " contains at least two definitions of the class " + node.getName() + ".\n"; if (node.isScriptBody() || stored.isScriptBody()) { txt += "One of the classes is an explicit generated class using the class statement, the other is a class generated from" + " the script body based on the file name. Solutions are to change the file name or to change the class name.\n"; } } else { txt += "The sources " + nodeSource.getName() + " and " + storedSource.getName() + " each contain a class with the name " + node.getName() + ".\n"; } nodeSource.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(txt, node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber()), nodeSource) ); } classes.put(name, node); if (classesToCompile.containsKey(name)) { ClassNode cn = classesToCompile.get(name); cn.setRedirect(node); classesToCompile.remove(name); } }
java
private String getSlashyPath(final String path) { String changedPath = path; if (File.separatorChar != '/') changedPath = changedPath.replace(File.separatorChar, '/'); return changedPath; }
java
public static void write(Path self, String text, String charset) throws IOException { Writer writer = null; try { writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.forName(charset)); writer.write(text); writer.flush(); Writer temp = writer; writer = null; temp.close(); } finally { closeWithWarning(writer); } }
java
public static void append(Path self, Object text) throws IOException { Writer writer = null; try { writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.defaultCharset()); InvokerHelper.write(writer, text); writer.flush(); Writer temp = writer; writer = null; temp.close(); } finally { closeWithWarning(writer); } }
java
public static int count(CharSequence self, CharSequence text) { int answer = 0; for (int idx = 0; true; idx++) { idx = self.toString().indexOf(text.toString(), idx); // break once idx goes to -1 or for case of empty string once // we get to the end to avoid JDK library bug (see GROOVY-5858) if (idx < answer) break; ++answer; } return answer; }
java
public static <T extends CharSequence> T eachMatch(T self, CharSequence regex, @ClosureParams(value=FromString.class, options={"List<String>","String[]"}) Closure closure) { eachMatch(self.toString(), regex.toString(), closure); return self; }
java
public static String eachMatch(String self, String regex, @ClosureParams(value=FromString.class, options={"List<String>","String[]"}) Closure closure) { return eachMatch(self, Pattern.compile(regex), closure); }
java
public static String expandLine(CharSequence self, int tabStop) { String s = self.toString(); int index; while ((index = s.indexOf('\t')) != -1) { StringBuilder builder = new StringBuilder(s); int count = tabStop - index % tabStop; builder.deleteCharAt(index); for (int i = 0; i < count; i++) builder.insert(index, " "); s = builder.toString(); } return s; }
java
public static String find(CharSequence self, CharSequence regex, @ClosureParams(value=SimpleType.class, options="java.lang.String[]") Closure closure) { return find(self.toString(), Pattern.compile(regex.toString()), closure); }
java
public static String getAt(CharSequence self, Collection indices) { StringBuilder answer = new StringBuilder(); for (Object value : indices) { if (value instanceof Range) { answer.append(getAt(self, (Range) value)); } else if (value instanceof Collection) { answer.append(getAt(self, (Collection) value)); } else { int idx = DefaultTypeTransformation.intUnbox(value); answer.append(getAt(self, idx)); } } return answer.toString(); }
java
public static CharSequence getAt(CharSequence text, int index) { index = normaliseIndex(index, text.length()); return text.subSequence(index, index + 1); }
java
public static String getAt(GString text, int index) { return (String) getAt(text.toString(), index); }
java
public static CharSequence getAt(CharSequence text, IntRange range) { return getAt(text, (Range) range); }
java
public static CharSequence getAt(CharSequence text, Range range) { RangeInfo info = subListBorders(text.length(), range); CharSequence sequence = text.subSequence(info.from, info.to); return info.reverse ? reverse(sequence) : sequence; }
java
public static String getAt(GString text, Range range) { return getAt(text.toString(), range); }
java
public static List getAt(Matcher self, Collection indices) { List result = new ArrayList(); for (Object value : indices) { if (value instanceof Range) { result.addAll(getAt(self, (Range) value)); } else { int idx = DefaultTypeTransformation.intUnbox(value); result.add(getAt(self, idx)); } } return result; }
java
public static String getAt(String text, int index) { index = normaliseIndex(index, text.length()); return text.substring(index, index + 1); }
java
public static String getAt(String text, IntRange range) { return getAt(text, (Range) range); }
java
public static String getAt(String text, Range range) { RangeInfo info = subListBorders(text.length(), range); String answer = text.substring(info.from, info.to); if (info.reverse) { answer = reverse(answer); } return answer; }
java
public static int getCount(Matcher matcher) { int counter = 0; matcher.reset(); while (matcher.find()) { counter++; } return counter; }
java
public static boolean isAllWhitespace(CharSequence self) { String s = self.toString(); for (int i = 0; i < s.length(); i++) { if (!Character.isWhitespace(s.charAt(i))) return false; } return true; }
java
public static boolean isBigDecimal(CharSequence self) { try { new BigDecimal(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
public static boolean isBigInteger(CharSequence self) { try { new BigInteger(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
public static boolean isDouble(CharSequence self) { try { Double.valueOf(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
public static boolean isFloat(CharSequence self) { try { Float.valueOf(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
public static boolean isInteger(CharSequence self) { try { Integer.valueOf(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
public static boolean isLong(CharSequence self) { try { Long.valueOf(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
public static StringBuffer leftShift(String self, Object value) { return new StringBuffer(self).append(value); }
java
public static StringBuilder leftShift(StringBuilder self, Object value) { self.append(value); return self; }
java
public static String minus(CharSequence self, Object target) { String s = self.toString(); String text = DefaultGroovyMethods.toString(target); int index = s.indexOf(text); if (index == -1) return s; int end = index + text.length(); if (s.length() > end) { return s.substring(0, index) + s.substring(end); } return s.substring(0, index); }
java
public static String minus(CharSequence self, Pattern pattern) { return pattern.matcher(self).replaceFirst(""); }
java
public static String multiply(CharSequence self, Number factor) { String s = self.toString(); int size = factor.intValue(); if (size == 0) return ""; else if (size < 0) { throw new IllegalArgumentException("multiply() should be called with a number of 0 or greater not: " + size); } StringBuilder answer = new StringBuilder(s); for (int i = 1; i < size; i++) { answer.append(s); } return answer.toString(); }
java
public static String next(CharSequence self) { StringBuilder buffer = new StringBuilder(self); if (buffer.length() == 0) { buffer.append(Character.MIN_VALUE); } else { char last = buffer.charAt(buffer.length() - 1); if (last == Character.MAX_VALUE) { buffer.append(Character.MIN_VALUE); } else { char next = last; next++; buffer.setCharAt(buffer.length() - 1, next); } } return buffer.toString(); }
java
public static String normalize(final CharSequence self) { final String s = self.toString(); int nx = s.indexOf('\r'); if (nx < 0) { return s; } final int len = s.length(); final StringBuilder sb = new StringBuilder(len); int i = 0; do { sb.append(s, i, nx); sb.append('\n'); if ((i = nx + 1) >= len) break; if (s.charAt(i) == '\n') { // skip the LF in CR LF if (++i >= len) break; } nx = s.indexOf('\r', i); } while (nx > 0); sb.append(s, i, len); return sb.toString(); }
java
public static String plus(CharSequence left, Object value) { return left + DefaultGroovyMethods.toString(value); }
java
public static String plus(Number value, String right) { return DefaultGroovyMethods.toString(value) + right; }
java
public static List<String> readLines(CharSequence self) throws IOException { return IOGroovyMethods.readLines(new StringReader(self.toString())); }
java
public static String replaceAll(final CharSequence self, final CharSequence regex, final CharSequence replacement) { return self.toString().replaceAll(regex.toString(), replacement.toString()); }
java
public static String replaceFirst(final CharSequence self, final CharSequence regex, final CharSequence replacement) { return self.toString().replaceFirst(regex.toString(), replacement.toString()); }
java
public static void setIndex(Matcher matcher, int idx) { int count = getCount(matcher); if (idx < -count || idx >= count) { throw new IndexOutOfBoundsException("index is out of range " + (-count) + ".." + (count - 1) + " (index = " + idx + ")"); } if (idx == 0) { matcher.reset(); } else if (idx > 0) { matcher.reset(); for (int i = 0; i < idx; i++) { matcher.find(); } } else if (idx < 0) { matcher.reset(); idx += getCount(matcher); for (int i = 0; i < idx; i++) { matcher.find(); } } }
java
public static <T> T splitEachLine(CharSequence self, CharSequence regex, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException { return splitEachLine(self, Pattern.compile(regex.toString()), closure); }
java
public static <T> T splitEachLine(CharSequence self, Pattern pattern, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException { final List<String> list = readLines(self); T result = null; for (String line : list) { List vals = Arrays.asList(pattern.split(line)); result = closure.call(vals); } return result; }
java
public static String takeWhile(GString self, @ClosureParams(value=SimpleType.class, options="char") Closure condition) { return (String) takeWhile(self.toString(), condition); }
java
public static List<String> toList(CharSequence self) { String s = self.toString(); int size = s.length(); List<String> answer = new ArrayList<String>(size); for (int i = 0; i < size; i++) { answer.add(s.substring(i, i + 1)); } return answer; }
java
public static String unexpand(CharSequence self, int tabStop) { String s = self.toString(); if (s.length() == 0) return s; try { StringBuilder builder = new StringBuilder(); for (String line : readLines((CharSequence) s)) { builder.append(unexpandLine(line, tabStop)); builder.append("\n"); } // remove the normalized ending line ending if it was not present if (!s.endsWith("\n")) { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } catch (IOException e) { /* ignore */ } return s; }
java
public static String unexpandLine(CharSequence self, int tabStop) { StringBuilder builder = new StringBuilder(self.toString()); int index = 0; while (index + tabStop < builder.length()) { // cut original string in tabstop-length pieces String piece = builder.substring(index, index + tabStop); // count trailing whitespace characters int count = 0; while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1))))) count++; // replace if whitespace was found if (count > 0) { piece = piece.substring(0, tabStop - count) + '\t'; builder.replace(index, index + tabStop, piece); index = index + tabStop - (count - 1); } else index = index + tabStop; } return builder.toString(); }
java
public boolean hasPossibleMethod(String name, Expression arguments) { int count = 0; if (arguments instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) arguments; // TODO this won't strictly be true when using list expansion in argument calls count = tuple.getExpressions().size(); } ClassNode node = this; do { for (MethodNode method : getMethods(name)) { if (method.getParameters().length == count && !method.isStatic()) { return true; } } node = node.getSuperClass(); } while (node != null); return false; }
java
private void checkOrMarkPrivateAccess(Expression source, FieldNode fn) { if (fn!=null && Modifier.isPrivate(fn.getModifiers()) && (fn.getDeclaringClass() != typeCheckingContext.getEnclosingClassNode() || typeCheckingContext.getEnclosingClosure()!=null) && fn.getDeclaringClass().getModule() == typeCheckingContext.getEnclosingClassNode().getModule()) { addPrivateFieldOrMethodAccess(source, fn.getDeclaringClass(), StaticTypesMarker.PV_FIELDS_ACCESS, fn); } }
java
private void checkOrMarkPrivateAccess(Expression source, MethodNode mn) { if (mn==null) { return; } ClassNode declaringClass = mn.getDeclaringClass(); ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode(); if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) { int mods = mn.getModifiers(); boolean sameModule = declaringClass.getModule() == enclosingClassNode.getModule(); String packageName = declaringClass.getPackageName(); if (packageName==null) { packageName = ""; } if ((Modifier.isPrivate(mods) && sameModule) || (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName()))) { addPrivateFieldOrMethodAccess(source, sameModule? declaringClass : enclosingClassNode, StaticTypesMarker.PV_METHODS_ACCESS, mn); } } }
java
private boolean ensureValidSetter(final Expression expression, final Expression leftExpression, final Expression rightExpression, final SetterInfo setterInfo) { // for expressions like foo = { ... } // we know that the RHS type is a closure // but we must check if the binary expression is an assignment // because we need to check if a setter uses @DelegatesTo VariableExpression ve = new VariableExpression("%", setterInfo.receiverType); MethodCallExpression call = new MethodCallExpression( ve, setterInfo.name, rightExpression ); call.setImplicitThis(false); visitMethodCallExpression(call); MethodNode directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET); if (directSetterCandidate==null) { // this may happen if there's a setter of type boolean/String/Class, and that we are using the property // notation AND that the RHS is not a boolean/String/Class for (MethodNode setter : setterInfo.setters) { ClassNode type = getWrapper(setter.getParameters()[0].getOriginType()); if (Boolean_TYPE.equals(type) || STRING_TYPE.equals(type) || CLASS_Type.equals(type)) { call = new MethodCallExpression( ve, setterInfo.name, new CastExpression(type,rightExpression) ); call.setImplicitThis(false); visitMethodCallExpression(call); directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET); if (directSetterCandidate!=null) { break; } } } } if (directSetterCandidate != null) { for (MethodNode setter : setterInfo.setters) { if (setter == directSetterCandidate) { leftExpression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, directSetterCandidate); storeType(leftExpression, getType(rightExpression)); break; } } } else { ClassNode firstSetterType = setterInfo.setters.iterator().next().getParameters()[0].getOriginType(); addAssignmentError(firstSetterType, getType(rightExpression), expression); return true; } return false; }
java
private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) { if (args.length!=1) return; if (!receiver.isArray()) return; if (!isIntCategory(getUnwrapper(args[0]))) return; if ("getAt".equals(name)) { MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],"arg")}, null, null); node.setDeclaringClass(receiver.redirect()); methods.add(node); } else if ("setAt".equals(name)) { MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],"arg")}, null, null); node.setDeclaringClass(receiver.redirect()); methods.add(node); } }
java
private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) { if (!type.isUsingGenerics()) return type; Map<String, GenericsType> connections = new HashMap(); //TODO: inner classes mean a different this-type. This is ignored here! extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass()); type= applyGenericsContext(connections, type); return type; }
java
public static byte[] decodeBase64(String value) { int byteShift = 4; int tmp = 0; boolean done = false; final StringBuilder buffer = new StringBuilder(); for (int i = 0; i != value.length(); i++) { final char c = value.charAt(i); final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66; if (sixBit < 64) { if (done) throw new RuntimeException("= character not at end of base64 value"); // TODO: change this exception type tmp = (tmp << 6) | sixBit; if (byteShift-- != 4) { buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF)); } } else if (sixBit == 64) { byteShift--; done = true; } else if (sixBit == 66) { // RFC 2045 says that I'm allowed to take the presence of // these characters as evidence of data corruption // So I will throw new RuntimeException("bad character in base64 value"); // TODO: change this exception type } if (byteShift == 0) byteShift = 4; } try { return buffer.toString().getBytes("ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Base 64 decode produced byte values > 255"); // TODO: change this exception type } }
java
protected void runStatements(Reader reader, PrintStream out) throws IOException { log.debug("runStatements()"); StringBuilder txt = new StringBuilder(); String line = ""; BufferedReader in = new BufferedReader(reader); while ((line = in.readLine()) != null) { line = getProject().replaceProperties(line); if (line.indexOf("--") >= 0) { txt.append("\n"); } } // Catch any statements not followed by ; if (!txt.toString().equals("")) { execGroovy(txt.toString(), out); } }
java
public static String toJson(Date date) { if (date == null) { return NULL_VALUE; } CharBuf buffer = CharBuf.create(26); writeDate(date, buffer); return buffer.toString(); }
java
public static String toJson(Calendar cal) { if (cal == null) { return NULL_VALUE; } CharBuf buffer = CharBuf.create(26); writeDate(cal.getTime(), buffer); return buffer.toString(); }
java
private static void writeNumber(Class<?> numberClass, Number value, CharBuf buffer) { if (numberClass == Integer.class) { buffer.addInt((Integer) value); } else if (numberClass == Long.class) { buffer.addLong((Long) value); } else if (numberClass == BigInteger.class) { buffer.addBigInteger((BigInteger) value); } else if (numberClass == BigDecimal.class) { buffer.addBigDecimal((BigDecimal) value); } else if (numberClass == Double.class) { Double doubleValue = (Double) value; if (doubleValue.isInfinite()) { throw new JsonException("Number " + value + " can't be serialized as JSON: infinite are not allowed in JSON."); } if (doubleValue.isNaN()) { throw new JsonException("Number " + value + " can't be serialized as JSON: NaN are not allowed in JSON."); } buffer.addDouble(doubleValue); } else if (numberClass == Float.class) { Float floatValue = (Float) value; if (floatValue.isInfinite()) { throw new JsonException("Number " + value + " can't be serialized as JSON: infinite are not allowed in JSON."); } if (floatValue.isNaN()) { throw new JsonException("Number " + value + " can't be serialized as JSON: NaN are not allowed in JSON."); } buffer.addFloat(floatValue); } else if (numberClass == Byte.class) { buffer.addByte((Byte) value); } else if (numberClass == Short.class) { buffer.addShort((Short) value); } else { // Handle other Number implementations buffer.addString(value.toString()); } }
java
private static void writeCharSequence(CharSequence seq, CharBuf buffer) { if (seq.length() > 0) { buffer.addJsonEscapedString(seq.toString()); } else { buffer.addChars(EMPTY_STRING_CHARS); } }
java
public static Enum castToEnum(Object object, Class<? extends Enum> type) { if (object==null) return null; if (type.isInstance(object)) return (Enum) object; if (object instanceof String || object instanceof GString) { return Enum.valueOf(type, object.toString()); } throw new GroovyCastException(object, type); }
java
public void setTargetBytecode(String version) { if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) { this.targetBytecode = version; } }
java
public List depthFirst() { List answer = new NodeList(); answer.add(this); answer.addAll(depthFirstRest()); return answer; }
java
public static String getGetterName(String propertyName, Class type) { String prefix = type == boolean.class || type == Boolean.class ? "is" : "get"; return prefix + MetaClassHelper.capitalize(propertyName); }
java
public static ProxyMetaClass getInstance(Class theClass) throws IntrospectionException { MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry(); MetaClass meta = metaRegistry.getMetaClass(theClass); return new ProxyMetaClass(metaRegistry, theClass, meta); }
java
private Expression correctClassClassChain(PropertyExpression pe) { LinkedList<Expression> stack = new LinkedList<Expression>(); ClassExpression found = null; for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) { if (it instanceof ClassExpression) { found = (ClassExpression) it; break; } else if (!(it.getClass() == PropertyExpression.class)) { return pe; } stack.addFirst(it); } if (found == null) return pe; if (stack.isEmpty()) return pe; Object stackElement = stack.removeFirst(); if (!(stackElement.getClass() == PropertyExpression.class)) return pe; PropertyExpression classPropertyExpression = (PropertyExpression) stackElement; String propertyNamePart = classPropertyExpression.getPropertyAsString(); if (propertyNamePart == null || !propertyNamePart.equals("class")) return pe; found.setSourcePosition(classPropertyExpression); if (stack.isEmpty()) return found; stackElement = stack.removeFirst(); if (!(stackElement.getClass() == PropertyExpression.class)) return pe; PropertyExpression classPropertyExpressionContainer = (PropertyExpression) stackElement; classPropertyExpressionContainer.setObjectExpression(found); return pe; }
java
public static void closeWithWarning(Closeable c) { if (c != null) { try { c.close(); } catch (IOException e) { LOG.warning("Caught exception during close(): " + e); } } }
java
public V get(K key) { ManagedReference<V> ref = internalMap.get(key); if (ref!=null) return ref.get(); return null; }
java
public void put(final K key, V value) { ManagedReference<V> ref = new ManagedReference<V>(bundle, value) { @Override public void finalizeReference() { super.finalizeReference(); internalMap.remove(key, get()); } }; internalMap.put(key, ref); }
java
public String getSample(int line, int column, Janitor janitor) { String sample = null; String text = source.getLine(line, janitor); if (text != null) { if (column > 0) { String marker = Utilities.repeatString(" ", column - 1) + "^"; if (column > 40) { int start = column - 30 - 1; int end = (column + 10 > text.length() ? text.length() : column + 10 - 1); sample = " " + text.substring(start, end) + Utilities.eol() + " " + marker.substring(start, marker.length()); } else { sample = " " + text + Utilities.eol() + " " + marker; } } else { sample = text; } } return sample; }
java
public static void withInstance(String url, Closure c) throws SQLException { Sql sql = null; try { sql = newInstance(url); c.call(sql); } finally { if (sql != null) sql.close(); } }
java
public synchronized void withTransaction(Closure closure) throws SQLException { boolean savedCacheConnection = cacheConnection; cacheConnection = true; Connection connection = null; boolean savedAutoCommit = true; try { connection = createConnection(); savedAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); callClosurePossiblyWithConnection(closure, connection); connection.commit(); } catch (SQLException e) { handleError(connection, e); throw e; } catch (RuntimeException e) { handleError(connection, e); throw e; } catch (Error e) { handleError(connection, e); throw e; } catch (Exception e) { handleError(connection, e); throw new SQLException("Unexpected exception during transaction", e); } finally { if (connection != null) { try { connection.setAutoCommit(savedAutoCommit); } catch (SQLException e) { LOG.finest("Caught exception resetting auto commit: " + e.getMessage() + " - continuing"); } } cacheConnection = false; closeResources(connection, null); cacheConnection = savedCacheConnection; if (dataSource != null && !cacheConnection) { useConnection = null; } } }
java
public static Object invoke(Object object, String methodName, Object[] parameters) { try { Class[] classTypes = new Class[parameters.length]; for (int i = 0; i < classTypes.length; i++) { classTypes[i] = parameters[i].getClass(); } Method method = object.getClass().getMethod(methodName, classTypes); return method.invoke(object, parameters); } catch (Throwable t) { return InvokerHelper.invokeMethod(object, methodName, parameters); } }
java
public static String[] tokenizeUnquoted(String s) { List tokens = new LinkedList(); int first = 0; while (first < s.length()) { first = skipWhitespace(s, first); int last = scanToken(s, first); if (first < last) { tokens.add(s.substring(first, last)); } first = last; } return (String[])tokens.toArray(new String[tokens.size()]); }
java
@SuppressWarnings("unchecked") private void addPrivateFieldsAccessors(ClassNode node) { Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS); if (accessedFields==null) return; Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS); if (privateConstantAccessors!=null) { // already added return; } int acc = -1; privateConstantAccessors = new HashMap<String, MethodNode>(); final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC; for (FieldNode fieldNode : node.getFields()) { if (accessedFields.contains(fieldNode)) { acc++; Parameter param = new Parameter(node.getPlainNodeReference(), "$that"); Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param); Statement stmt = new ExpressionStatement(new PropertyExpression( receiver, fieldNode.getName() )); MethodNode accessor = node.addMethod("pfaccess$"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt); privateConstantAccessors.put(fieldNode.getName(), accessor); } } node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors); }
java
public static boolean isPostJDK5(String bytecodeVersion) { return JDK5.equals(bytecodeVersion) || JDK6.equals(bytecodeVersion) || JDK7.equals(bytecodeVersion) || JDK8.equals(bytecodeVersion); }
java
public void setTargetDirectory(String directory) { if (directory != null && directory.length() > 0) { this.targetDirectory = new File(directory); } else { this.targetDirectory = null; } }
java
protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException { Class c = this.findLoadedClass(name); if (c != null) return c; c = (Class) customClasses.get(name); if (c != null) return c; try { c = oldFindClass(name); } catch (ClassNotFoundException cnfe) { // IGNORE } if (c == null) c = super.loadClass(name, resolve); if (resolve) resolveClass(c); return c; }
java
public NodeList getAt(String name) { NodeList answer = new NodeList(); for (Object child : this) { if (child instanceof Node) { Node childNode = (Node) child; Object temp = childNode.get(name); if (temp instanceof Collection) { answer.addAll((Collection) temp); } else { answer.add(temp); } } } return answer; }
java
public String text() { String previousText = null; StringBuilder buffer = null; for (Object child : this) { String text = null; if (child instanceof String) { text = (String) child; } else if (child instanceof Node) { text = ((Node) child).text(); } if (text != null) { if (previousText == null) { previousText = text; } else { if (buffer == null) { buffer = new StringBuilder(); buffer.append(previousText); } buffer.append(text); } } } if (buffer != null) { return buffer.toString(); } if (previousText != null) { return previousText; } return ""; }
java
private boolean isAllNumeric(TokenStream stream) { List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens(); for(Token token:tokens) { try { Integer.parseInt(token.getText()); } catch(NumberFormatException e) { return false; } } return true; }
java
private List<TokenStream> collectTokenStreams(TokenStream stream) { // walk through the token stream and build a collection // of sub token streams that represent possible date locations List<Token> currentGroup = null; List<List<Token>> groups = new ArrayList<List<Token>>(); Token currentToken; int currentTokenType; StringBuilder tokenString = new StringBuilder(); while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) { currentTokenType = currentToken.getType(); tokenString.append(DateParser.tokenNames[currentTokenType]).append(" "); // we're currently NOT collecting for a possible date group if(currentGroup == null) { // skip over white space and known tokens that cannot be the start of a date if(currentTokenType != DateLexer.WHITE_SPACE && DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) { currentGroup = new ArrayList<Token>(); currentGroup.add(currentToken); } } // we're currently collecting else { // preserve white space if(currentTokenType == DateLexer.WHITE_SPACE) { currentGroup.add(currentToken); } else { // if this is an unknown token, we'll close out the current group if(currentTokenType == DateLexer.UNKNOWN) { addGroup(currentGroup, groups); currentGroup = null; } // otherwise, the token is known and we're currently collecting for // a group, so we'll add it to the current group else { currentGroup.add(currentToken); } } } } if(currentGroup != null) { addGroup(currentGroup, groups); } _logger.info("STREAM: " + tokenString.toString()); List<TokenStream> streams = new ArrayList<TokenStream>(); for(List<Token> group:groups) { if(!group.isEmpty()) { StringBuilder builder = new StringBuilder(); builder.append("GROUP: "); for (Token token : group) { builder.append(DateParser.tokenNames[token.getType()]).append(" "); } _logger.info(builder.toString()); streams.add(new CommonTokenStream(new NattyTokenSource(group))); } } return streams; }
java
private void addGroup(List<Token> group, List<List<Token>> groups) { if(group.isEmpty()) return; // remove trailing tokens that should be ignored while(!group.isEmpty() && IGNORED_TRAILING_TOKENS.contains( group.get(group.size() - 1).getType())) { group.remove(group.size() - 1); } // if the group still has some tokens left, we'll add it to our list of groups if(!group.isEmpty()) { groups.add(group); } }
java
public void seekToDayOfWeek(String direction, String seekType, String seekAmount, String dayOfWeek) { int dayOfWeekInt = Integer.parseInt(dayOfWeek); int seekAmountInt = Integer.parseInt(seekAmount); assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT)); assert(seekType.equals(SEEK_BY_DAY) || seekType.equals(SEEK_BY_WEEK)); assert(dayOfWeekInt >= 1 && dayOfWeekInt <= 7); markDateInvocation(); int sign = direction.equals(DIR_RIGHT) ? 1 : -1; if(seekType.equals(SEEK_BY_WEEK)) { // set our calendar to this weeks requested day of the week, // then add or subtract the week(s) _calendar.set(Calendar.DAY_OF_WEEK, dayOfWeekInt); _calendar.add(Calendar.DAY_OF_YEAR, seekAmountInt * 7 * sign); } else if(seekType.equals(SEEK_BY_DAY)) { // find the closest day do { _calendar.add(Calendar.DAY_OF_YEAR, sign); } while(_calendar.get(Calendar.DAY_OF_WEEK) != dayOfWeekInt); // now add/subtract any additional days if(seekAmountInt > 0) { _calendar.add(Calendar.WEEK_OF_YEAR, (seekAmountInt - 1) * sign); } } }
java
public void seekToDayOfMonth(String dayOfMonth) { int dayOfMonthInt = Integer.parseInt(dayOfMonth); assert(dayOfMonthInt >= 1 && dayOfMonthInt <= 31); markDateInvocation(); dayOfMonthInt = Math.min(dayOfMonthInt, _calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); _calendar.set(Calendar.DAY_OF_MONTH, dayOfMonthInt); }
java
public void seekToDayOfYear(String dayOfYear) { int dayOfYearInt = Integer.parseInt(dayOfYear); assert(dayOfYearInt >= 1 && dayOfYearInt <= 366); markDateInvocation(); dayOfYearInt = Math.min(dayOfYearInt, _calendar.getActualMaximum(Calendar.DAY_OF_YEAR)); _calendar.set(Calendar.DAY_OF_YEAR, dayOfYearInt); }
java
public void seekToMonth(String direction, String seekAmount, String month) { int seekAmountInt = Integer.parseInt(seekAmount); int monthInt = Integer.parseInt(month); assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT)); assert(monthInt >= 1 && monthInt <= 12); markDateInvocation(); // set the day to the first of month. This step is necessary because if we seek to the // current day of a month whose number of days is less than the current day, we will // pushed into the next month. _calendar.set(Calendar.DAY_OF_MONTH, 1); // seek to the appropriate year if(seekAmountInt > 0) { int currentMonth = _calendar.get(Calendar.MONTH) + 1; int sign = direction.equals(DIR_RIGHT) ? 1 : -1; int numYearsToShift = seekAmountInt + (currentMonth == monthInt ? 0 : (currentMonth < monthInt ? sign > 0 ? -1 : 0 : sign > 0 ? 0 : -1)); _calendar.add(Calendar.YEAR, (numYearsToShift * sign)); } // now set the month _calendar.set(Calendar.MONTH, monthInt - 1); }
java
public void setExplicitTime(String hours, String minutes, String seconds, String amPm, String zoneString) { int hoursInt = Integer.parseInt(hours); int minutesInt = minutes != null ? Integer.parseInt(minutes) : 0; assert(amPm == null || amPm.equals(AM) || amPm.equals(PM)); assert(hoursInt >= 0); assert(minutesInt >= 0 && minutesInt < 60); markTimeInvocation(amPm); // reset milliseconds to 0 _calendar.set(Calendar.MILLISECOND, 0); // if no explicit zone is given, we use our own TimeZone zone = null; if(zoneString != null) { if(zoneString.startsWith(PLUS) || zoneString.startsWith(MINUS)) { zoneString = GMT + zoneString; } zone = TimeZone.getTimeZone(zoneString); } _calendar.setTimeZone(zone != null ? zone : _defaultTimeZone); _calendar.set(Calendar.HOUR_OF_DAY, hoursInt); // hours greater than 12 are in 24-hour time if(hoursInt <= 12) { int amPmInt = amPm == null ? (hoursInt >= 12 ? Calendar.PM : Calendar.AM) : amPm.equals(PM) ? Calendar.PM : Calendar.AM; _calendar.set(Calendar.AM_PM, amPmInt); // calendar is whacky at 12 o'clock (must use 0) if(hoursInt == 12) hoursInt = 0; _calendar.set(Calendar.HOUR, hoursInt); } if(seconds != null) { int secondsInt = Integer.parseInt(seconds); assert(secondsInt >= 0 && secondsInt < 60); _calendar.set(Calendar.SECOND, secondsInt); } else { _calendar.set(Calendar.SECOND, 0); } _calendar.set(Calendar.MINUTE, minutesInt); }
java
public void seekToHoliday(String holidayString, String direction, String seekAmount) { Holiday holiday = Holiday.valueOf(holidayString); assert(holiday != null); seekToIcsEvent(HOLIDAY_ICS_FILE, holiday.getSummary(), direction, seekAmount); }
java
public void seekToHolidayYear(String holidayString, String yearString) { Holiday holiday = Holiday.valueOf(holidayString); assert(holiday != null); seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary()); }
java
public void seekToSeason(String seasonString, String direction, String seekAmount) { Season season = Season.valueOf(seasonString); assert(season!= null); seekToIcsEvent(SEASON_ICS_FILE, season.getSummary(), direction, seekAmount); }
java
public void seekToSeasonYear(String seasonString, String yearString) { Season season = Season.valueOf(seasonString); assert(season != null); seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary()); }
java
private void resetCalendar() { _calendar = getCalendar(); if (_defaultTimeZone != null) { _calendar.setTimeZone(_defaultTimeZone); } _currentYear = _calendar.get(Calendar.YEAR); }
java
private Date seasonalDateFromIcs(String icsFileName, String eventSummary, int year) { Map<Integer, Date> dates = getDatesFromIcs(icsFileName, eventSummary, year, year); return dates.get(year - (eventSummary.equals(Holiday.NEW_YEARS_EVE.getSummary()) ? 1 : 0)); }
java
private void markDateInvocation() { _updatePreviousDates = !_dateGivenInGroup; _dateGivenInGroup = true; _dateGroup.setDateInferred(false); if(_firstDateInvocationInGroup) { // if a time has been given within the current date group, // we capture the current time before resetting the calendar if(_timeGivenInGroup) { int hours = _calendar.get(Calendar.HOUR_OF_DAY); int minutes = _calendar.get(Calendar.MINUTE); int seconds = _calendar.get(Calendar.SECOND); resetCalendar(); _calendar.set(Calendar.HOUR_OF_DAY, hours); _calendar.set(Calendar.MINUTE, minutes); _calendar.set(Calendar.SECOND, seconds); } else { resetCalendar(); } _firstDateInvocationInGroup = false; } }
java
private Calendar cleanHistCalendar(Calendar cal) { cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR, 0); return cal; }
java
public static Calendar parseDividendDate(String date) { if (!Utils.isParseable(date)) { return null; } date = date.trim(); SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date), Locale.US); format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); try { Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); parsedDate.setTime(format.parse(date)); if (parsedDate.get(Calendar.YEAR) == 1970) { // Not really clear which year the dividend date is... making a reasonable guess. int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH); int year = today.get(Calendar.YEAR); if (monthDiff > 6) { year -= 1; } else if (monthDiff < -6) { year += 1; } parsedDate.set(Calendar.YEAR, year); } return parsedDate; } catch (ParseException ex) { log.warn("Failed to parse dividend date: " + date); log.debug("Failed to parse dividend date: " + date, ex); return null; } }
java