code
stringlengths
73
34.1k
label
stringclasses
1 value
public void run() { if (maxTime < 0) { return; } long timeMillis = (long)maxTime * 60 * 1000; endTime = new Date((new Date()).getTime() + timeMillis); while (!cancel && endTime.after(new Date())) { try { Thread.sleep(1000); ...
java
public Collection<Instruction> getInstructions() { return new AbstractCollection<Instruction>() { public Iterator<Instruction> iterator() { return new Iterator<Instruction>() { private Instruction mNext = mFirst; public boolean hasNext() { ...
java
public LocalVariable createLocalParameter(String name, TypeDesc type) { LocalVariable var = new LocalVariableImpl (mLocalVariables.size(), name, type, mNextFixedVariableNumber); mLocalVariables.add(var); mNextFixedVariableNumber += type.isDoubleWord() ? 2 : 1; return var; ...
java
public Resolution intercept(ExecutionContext context) throws Exception { HttpServletRequest request = context.getActionBeanContext().getRequest(); if (resourceBundleFactory != null) { ResourceBundle bundle = resourceBundleFactory.getDefaultBundle(request.getLocale()); setMessageResourceBundle(request, ...
java
public Resolution intercept(ExecutionContext executionContext) throws Exception { Resolution resolution; if (securityManager != null) { // Add the security manager to the request. // This is used (for example) by the security tag. executionContext.getActionBeanContext().getRequest().setAttribute(Sec...
java
protected Resolution interceptEventHandling(ExecutionContext executionContext) throws Exception { // Before handling the event, check if access is allowed. // If not explicitly allowed, access is denied. Resolution resolution; if (Boolean.TRUE.equals(getAccessAllowed(executionContext))) { resolution ...
java
public static TypeDesc forDescriptor(final String desc) throws IllegalArgumentException { TypeDesc type = cDescriptorsToInstances.get(desc); if (type != null) { return type; } // TODO: Support generics in descriptor. String rootDesc = desc; int cursor = 0; ...
java
public void valueUnbound(HttpSessionBindingEvent event) { for (SessionFieldMapper fieldMapper : this.values()) { if (fieldMapper.runnable != null) fieldMapper.runnable.cancel(); } }
java
public void sessionWillPassivate(HttpSessionEvent event) { for (Entry<String, SessionFieldMapper> entry : this.entrySet()) { if (!entry.getValue().serializable) { event.getSession().removeAttribute(entry.getKey()); } } }
java
private void cleanup() { Entry<K, V>[] tab = this.table; for (int i = tab.length ; i-- > 0 ;) { for (Entry<K, V> e = tab[i], prev = null; e != null; e = e.next) { if (e.get() == null) { // Clean up after a cleared Reference. this.modCo...
java
@Override protected void setMessageResourceBundle(HttpServletRequest request, ResourceBundle bundle) { request.setAttribute(REQ_ATTR_MESSAGE_RESOURCE_BUNDLE, bundle); }
java
public List<ProblemInput> getProblemInputs() { return (inputs == null ? Collections.emptyList() : Arrays.asList(inputs)); }
java
public ProblemInput getProblemInput(final int index) { final List<ProblemInput> inputs = getProblemInputs(); if (index < 0 || inputs.size() <= index) { throw new ArrayIndexOutOfBoundsException(); } return inputs.get(index); }
java
private void readObject(final ObjectInputStream stream) throws OptionalDataException, ClassNotFoundException, IOException { stream.registerValidation(this, 0); stream.defaultReadObject(); }
java
public final static boolean canThrowException(byte opcode) { switch (opcode) { default: return false; case IALOAD: case LALOAD: case FALOAD: case DALOAD: case AALOAD: case BALOAD: case CALOAD: case SALOAD: case IASTORE: ...
java
public static Map<String, BeanProperty> getAllProperties(Class clazz) { synchronized (cPropertiesCache) { Map<String, BeanProperty> properties; SoftReference<Map<String, BeanProperty>> ref = cPropertiesCache.get(clazz); if (ref != null) { properties = ref.get(...
java
private static String extractPropertyName(Method method, String prefix) { String name = method.getName(); if (!name.startsWith(prefix)) { return null; } if (name.length() == prefix.length()) { return ""; } name = name.substring(prefix.length()); ...
java
protected void saveFields(Collection<Field> fields, ActionBean actionBean, HttpSession session) throws IllegalAccessException { for (Field field : fields) { if (!field.isAccessible()) { field.setAccessible(true); } setAttribute(session, getFieldKey(field,...
java
protected void restoreFields(Collection<Field> fields, ActionBean actionBean, ActionBeanContext context) throws IllegalAccessException { HttpSession session = context.getRequest().getSession(false); if (session != null) { Set<String> parameters = this.getParameters(context.getRequest()); ...
java
protected Set<String> getParameters(HttpServletRequest request) { Set<String> parameters = new HashSet<String>(); Enumeration<?> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String parameter = (String) paramNames.nextElement(); // ...
java
protected String getFieldKey(Field field, Class<? extends ActionBean> actionBeanClass) { // Use key attribute if it is defined. String sessionKey = ((Session)field.getAnnotation(Session.class)).key(); if (sessionKey != null && !"".equals(sessionKey)) { return sessionKey; ...
java
protected Collection<Field> getSessionFields(Class<?> clazz) { Collection<Field> fields = fieldMap.get(clazz); if (fields == null) { fields = ReflectUtil.getFields(clazz); Iterator<Field> iterator = fields.iterator(); while (iterator.hasNext()) { ...
java
@Deprecated public static Object getAttribute(HttpSession session, String key) { return session.getAttribute(key); }
java
protected Object setAttribute(HttpSession session, String key, Object object, boolean serializable, int maxTime) { if (object == null) { // If object is null, remove attribute. Object ret; synchronized (session) { ret = session.getAttribute(key); ...
java
@Override protected void setMessageResourceBundle(HttpServletRequest request, ResourceBundle bundle) { Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle, request.getLocale())); LOGGER.debug("Enabled JSTL localization using: ", bundle); LOGGER.debug("Loaded resour...
java
@Override protected void setOtherResourceBundles(HttpServletRequest request) { Locale locale = request.getLocale(); if (errorBundleName != null) { ResourceBundle errorBundle = getLocalizationBundleFactory().getErrorMessageBundle(locale); Config.set(request, errorBundleName, ...
java
private Object evaluateRoleExpression(ActionBean bean, String expression) { try { LOG.debug("Evaluating expression: '" + expression + '\''); // This is somewhat of a hack until the ExpressionEvaluator becomes more accessible. ParameterName name = new ParameterName("security"); List<Object> values = ne...
java
public static MethodDesc forDescriptor(String desc) throws IllegalArgumentException { try { int cursor = 0; char c; if ((c = desc.charAt(cursor++)) != '(') { throw invalidDescriptor(desc); } StringBuffer buf = new StringB...
java
public synchronized T get(final int timeoutMillis) throws E { if (mReal != null) { return mReal; } if (mBogus != null && mMinRetryDelayMillis < 0) { return mBogus; } if (mCreateThread == null) { mCreateThread = new CreateThread(); ...
java
private Constructor<T> getWrapper() { Class<T> clazz; synchronized (cWrapperCache) { clazz = (Class<T>) cWrapperCache.get(mType); if (clazz == null) { clazz = createWrapper(); cWrapperCache.put(mType, clazz); } } try { ...
java
public void loadLocal(LocalVariable local) { if (local == null) { throw new IllegalArgumentException("No local variable specified"); } int stackAdjust = local.getType().isDoubleWord() ? 2 : 1; mInstructions.new LoadLocalInstruction(stackAdjust, local); }
java
private void nullConvert(Label end) { LocalVariable temp = createLocalVariable("temp", TypeDesc.OBJECT); storeLocal(temp); loadLocal(temp); Label notNull = createLabel(); ifNullBranch(notNull, false); loadNull(); branch(end); notNull.setLocation(); ...
java
public void invokeVirtual(String methodName, TypeDesc ret, TypeDesc[] params) { invokeVirtual(mClassFile.getClassName(), methodName, ret, params); }
java
private Context getContext(ExecutionContext executionContext) { // Get context id. HttpServletRequest request = executionContext.getActionBeanContext().getRequest(); String parameter = request.getParameter(ID_PARAMETER); // Return context. if (parameter != null) { ...
java
private Resolution createContextAndRedirect(ExecutionContext executionContext, WaitPage annotation) throws IOException { // Create context used to call the event in background. Context context = this.createContext(executionContext); context.actionBean = executionContext.getActionBean(); ...
java
private Resolution checkStatus(ExecutionContext executionContext, Context context) throws Exception { // Resolution execution must not be executed while we are checking status. synchronized (context.actionBean) { if (context.status == Context.Status.INIT) { // If a delay was ...
java
protected void copyErrors(ActionBeanContext source, ActionBeanContext destination) { destination.getValidationErrors().putAll(source.getValidationErrors()); }
java
protected void removeExpired(Map<Integer, Context> contexts) { Iterator<Context> contextsIter = contexts.values().iterator(); while (contextsIter.hasNext()) { Context context = contextsIter.next(); if (context.completeMoment != null && System.currentTimeMillis...
java
public void init(Configuration configuration) throws Exception { if (configuration.getBootstrapPropertyResolver().getProperty(CONTEXT_TIMEOUT_NAME) != null) { log.debug("Configuring context timeout with value ", configuration.getBootstrapPropertyResolver().getProperty(CONTEXT_TIMEOUT_NAME)); ...
java
public ClassFile[] getInnerClasses() { if (mInnerClasses == null) { return new ClassFile[0]; } return mInnerClasses.toArray(new ClassFile[mInnerClasses.size()]); }
java
public MethodInfo addMethod(String declaration) { MethodDeclarationParser p = new MethodDeclarationParser(declaration); return addMethod(p.getModifiers(), p.getMethodName(), p.getReturnType(), p.getParameters()); }
java
public void setTarget(String target) throws IllegalArgumentException { int major, minor; if (target == null || "1.0".equals(target) || "1.1".equals(target)) { major = 45; minor = 3; if (target == null) { target = "1.0"; } } else if ("1.2".equa...
java
public void setVersion(int major, int minor) { if (major > 65535 || minor > 65535) { throw new IllegalArgumentException("Version number element cannot exceed 65535"); } mVersion = (minor << 16) | (major & 0xffff); String target; switch (major) { default: ...
java
public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("DisassemblyTool [-f <format style>] <file or class name>"); System.out.println(); System.out.println("The format style may be \"assembly\" (the default) or \"builder\""); ...
java
protected Boolean determineAccessOnElement(ActionBean bean, Method handler, AnnotatedElement element) { // Default decision: none. Boolean allowed = null; if (element.isAnnotationPresent(DenyAll.class)) { // The element denies access. allowed = false; } else if (element.isAnnotationPresent(PermitA...
java
public void init(Configuration configuration) throws Exception { bundleName = configuration.getServletContext().getInitParameter(Config.FMT_LOCALIZATION_CONTEXT); if (bundleName == null) { throw new StripesRuntimeException("JSTL has no resource bundle configured. Please set the context " + ...
java
public void run() { try { // Open connection to URL calling this interceptor. HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Pass in the session id cookie to maintain the same session. log.trace("passing in cookies: ", cook...
java
public Class defineClass() { byte[] bytes; try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); writeTo(bout); bytes = bout.toByteArray(); } catch (IOException e) { InternalError ie = new InternalError(e.toString()); ie.initC...
java
private static int hashCapacity(int min) { BigInteger capacity = BigInteger.valueOf(min * 2 + 1); while (!capacity.isProbablePrime(10)) { capacity = capacity.add(BigInteger.valueOf(2)); } return capacity.intValue(); }
java
private static List[] caseMethods(int caseCount, BeanProperty[] props) { List[] cases = new List[caseCount]; for (int i=0; i<props.length; i++) { BeanProperty prop = props[i]; int hashCode = prop.getName().hashCode(); int caseVal...
java
private static BeanProperty[][] getBeanProperties(Class beanType, PropertySet set) { List readProperties = new ArrayList(); List writeProperties = new ArrayList(); Map map = BeanIntrospector.getAllProperties(beanType); Iterator it = map.values().iterator(); while (it.hasNext())...
java
public OutputStream openStream() throws IllegalStateException { if (mClass != null) { throw new IllegalStateException("New class has already been defined"); } ByteArrayOutputStream data = mData; if (data != null) { throw new IllegalStateException("Stream already o...
java
public Class defineClass(ClassFile cf) { try { cf.writeTo(openStream()); } catch (IOException e) { throw new InternalError(e.toString()); } return getNewClass(); }
java
public Class getNewClass() throws IllegalStateException, ClassFormatError { if (mClass != null) { return mClass; } ByteArrayOutputStream data = mData; if (data == null) { throw new IllegalStateException("Class not defined yet"); } byte[] bytes = d...
java
int available(Context context) { // package protected for access from I/O streams return context.buffer != null ? context.pos - context.readPos : 0; }
java
public static Map<String, Object> parseData(String data) { Map<String, Object> ret = new HashMap<String, Object>(); String[] split = data.split("&"); for (String s : split) { int idx = s.indexOf('='); try { if (idx != -1) { ret.put(URLDecoder.decode(s.substring(0, idx), "UTF-8"), URLDecoder.decode(...
java
public static String capitalizeHeader(String header) { StringTokenizer st = new StringTokenizer(header, "-"); StringBuilder out = new StringBuilder(); while (st.hasMoreTokens()) { String l = st.nextToken(); out.append(Character.toUpperCase(l.charAt(0))); if (l.length() > 1) { out.append(l.substring(1...
java
private ExternalNode3 combineExternalNodes(ExternalNode3 n1, ExternalNode3 n2) { if (n1 == null || n2 == null) { throw new IllegalArgumentException("Input nodes must not be null"); } DecisionType combinedDecision = algo.combine(n1.getDecision(), n2.getDecision()); ExternalNo...
java
private List<ObligationExpression> getFulfilledObligationExpressions( List<ObligationExpression> oes, DecisionType decision) { List<ObligationExpression> fulfilledOEs = new ArrayList<ObligationExpression>(); if (oes != null && oes.size() > 0) { for (ObligationExpres...
java
private InternalNodeState combineInternalNodeStates(InternalNodeState inState, ExternalNode3 externalNode) { ExternalNode3 n1 = inState.getExternalNode(); ExternalNode3 n = combineExternalNodes(n1, externalNode); return new InternalNodeState(n); }
java
@SuppressWarnings("rawtypes") private void setEffectNode(AbstractNode midd, ExternalNode3 extNode) throws MIDDException { // Replace current external nodes in the MIDD with the extNode (XACML 3 external node) if (!(midd instanceof InternalNode)) { throw new IllegalArgumentException("MID...
java
public int read() throws IOException { if (leftover != null && leftover.remaining() > 0) { int b = leftover.get(); if (leftover.remaining() == 0) { leftover = null; } return b; } return input.read(); }
java
public String readLine() throws IOException { StringBuilder bldr = new StringBuilder(); while (true) { int b = read(); if (b == -1 || b == 10) { break; } else if (b != '\r') { bldr.append((char) ((byte) b)); } } return bldr.toString(); }
java
public String readLineUntilBoundary() throws IOException { StringBuilder bldr = new StringBuilder(); while (true) { int b = read(); if (bldr.indexOf(boundary) == 0) { leftover = ByteBuffer.wrap(boundaryBytes); return null; } else if (b == -1 || b == 10) { break; } else if (b != '\r') { b...
java
public static <V> V defaultIfException( StatementWithReturnValue<V> statement, Class<? extends Throwable> exceptionType, V defaultValue) { try { return statement.evaluate(); } catch (RuntimeException e) { if (exceptionType.isAssignableFrom(e.getClass())) ...
java
public String getValue(String key) { KeyValue kv = getKV(key); return kv == null ? null : kv.getValue(); }
java
public void setValue(String key, String value) { KeyValue kv = getKV(key); if (kv != null) { kv.setValue(value); } else if (key != null) { map.add(new KeyValue(key,value)); } }
java
public void removeKey(String key) { if (key != null && !key.isEmpty()) { for (int i=0; i<map.size(); i++) { KeyValue kv = map.get(i); if (key.equals(kv.getKey())) { map.remove(i); return; } } ...
java
public boolean match(final T value) throws MIDDException { for (Interval<T> interval : this.intervals) { if (interval.hasValue(value)) { return true; } } return false; }
java
protected final <T> void doBind( Multibinder<T> binder, Class<? extends T> type ) { checkNotNull( type ); binder.addBinding().to( type ); }
java
@SuppressWarnings("unchecked") public void addChild(final AbstractEdge<?> edge, final AbstractNode child) { if (child == null || edge == null || edge.getIntervals() == null || edge.getIntervals().size() == 0) { throw new IllegalArgumentException("Cannot add null child or empty ed...
java
public AbstractNode getChild(Interval<T> interval) throws MIDDException { for (AbstractEdge<T> e : this.edges) { if (e.containsInterval(interval)) { return e.getSubDiagram(); } } return null; }
java
@SuppressWarnings("rawtypes") public List<Interval> getIntervals() { List<Interval> lstIntervals = new ArrayList<Interval>(); for (AbstractEdge<T> e : this.edges) { lstIntervals.addAll(e.getIntervals()); } return lstIntervals; }
java
public AbstractEdge<T> match(T value) throws UnmatchedException, MIDDException { for (AbstractEdge<T> e : this.edges) { if (e.match(value)) { return e; } } throw new UnmatchedException("No matching edge found for value " + value); }
java
public AbstractNode createFromConjunctionClauses(Map<String, AttributeInfo> intervals) throws MIDDParsingException, MIDDException { if (intervals == null || intervals.size() == 0) { return ExternalNode.newInstance(); // return true-value external node } // Create edges from interva...
java
private final static byte[] getAlphabet(final int options) { if ((options & Base64.URL_SAFE) == Base64.URL_SAFE) { return Base64._URL_SAFE_ALPHABET; } else if ((options & Base64.ORDERED) == Base64.ORDERED) { return Base64._ORDERED_ALPHABET; } else { return Base64._STANDARD_ALPHABET; } ...
java
private final static void usage(final String msg) { System.err.println(msg); System.err.println("Usage: java Base64 -e|-d inputfile outputfile"); }
java
public String toHeader() { StringBuilder header = new StringBuilder(); header.append(name).append('=').append(value); if (domain != null) { header.append("; ").append("Domain=").append(domain); } if (path != null) { header.append("; ").append("Path=").append(path); } if (expireTime > -1) { header...
java
public static String generateRandomString(int nbytes) { byte[] salt = new byte[nbytes]; Random r = new SecureRandom(); r.nextBytes(salt); return bytesToHex(salt); }
java
public static boolean fixedTimeEqual(String lhs, String rhs) { boolean equal = (lhs.length() == rhs.length() ? true : false); // If not equal, work on a single operand to have same length. if(!equal) { rhs = lhs; } int len = lhs.length(); for(int i=0;i<len;i++) { if(lhs.charAt(i) == rhs.charAt(i...
java
private void initialize(InputStream input) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(input)); String line; Matcher m; while ((line = reader.readLine()) != null) { m = TYPE_PATTERN.matcher(line); if (m.find()) { String type = m.group(1); ...
java
private static final String getExtension(String fileName) { return fileName.indexOf('.') == -1 ? null : fileName.substring(fileName.lastIndexOf('.') + 1); }
java
public boolean containsInterval(Interval<T> i) { for (Interval<T> item : intervals) { if (item.contains(i)) { return true; } } return false; }
java
public void addHeader(String key, Object value) { List<Object> values = headers.get(key); if (values == null) { headers.put(key, values = new ArrayList<Object>()); } values.add(value); }
java
public void setResponse(String response) { this.response = response; try { this.responseLength = response.getBytes("UTF-8").length; } catch (UnsupportedEncodingException e) { this.responseLength = response.length(); } }
java
public void setResponse(InputStream response) { this.response = response; try { this.responseLength = response.available(); } catch (IOException e) { // This shouldn't happen. } }
java
public void start() { if (socket == null) { throw new RuntimeException("Cannot bind a server that has not been initialized!"); } running = true; Thread t = new Thread(this); t.setName("HttpServer"); t.start(); }
java
@Override public void run() { while (running) { try { // Read the request service.execute(new HttpSession(this, socket.accept())); } catch (IOException e) { // Ignore mostly. } } }
java
public void dispatchRequest(HttpRequest httpRequest) throws IOException { for (HttpRequestHandler handler : handlers) { HttpResponse resp = handler.handleRequest(httpRequest); if (resp != null) { httpRequest.getSession().sendResponse(resp); return; } } if (!hasCapability(HttpCapability.THREADEDRE...
java
public WwwAuthenticateHeader createWwwAuthenticateHeader() throws HawkException { WwwAuthenticateBuilder headerBuilder = WwwAuthenticateHeader .wwwAuthenticate(); if (hasTs()) { if (!hasTsm()) { String hmac = this.generateHmac(); headerBuilder.ts(getTs()).tsm(hmac); } else { headerBuilder...
java
public boolean isValidTimestampMac(String hmac) throws HawkException { String this_hmac = this.generateHmac(); return Util.fixedTimeEqual(this_hmac, hmac); }
java
private String getBaseString() { if (!hasTs()) { throw new IllegalStateException( "This HawkWwwAuthenticateContext has no timestamp"); } return new StringBuilder(HAWK_TS_PREFIX).append(SLF).append(getTs()) .append(SLF).toString(); }
java
private String generateHmac() throws HawkException { String baseString = getBaseString(); Mac mac; try { mac = Mac.getInstance(getAlgorithm().getMacName()); } catch (NoSuchAlgorithmException e) { throw new HawkException("Unknown algorithm " + getAlgorithm().getMacName(), e); } SecretKeySpec se...
java
public static HawkWwwAuthenticateContextBuilder_A tsAndTsm(long l, String tsm) { return new HawkWwwAuthenticateContextBuilder().ts(l).tsm(tsm); }
java
public int addAttribute(String attrId) { if (attributeMapper.containsKey(attrId)) { return attributeMapper.get(attrId); // attribute-id has existed } attributeMapper.put(attrId, varIdCounter); varIdCounter++; return attributeMapper.get(attrId); }
java
public String getAttributeId(int variableId) throws MIDDParsingException { if (!attributeMapper.containsValue(variableId)) { throw new MIDDParsingException("Variable identifier '" + variableId + "' not found"); } for (String attrId : attributeMapper.keySet()) { if (attri...
java
public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException { Object encoding = context.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING); if (encoding != null && encoding.toString().equalsIgnoreCase("lzf")) { OutputStream old = context.getOutputStream(...
java
public AuthorizationHeader createAuthorizationHeader() throws HawkException { String hmac = this.generateHmac(); AuthorizationBuilder headerBuilder = AuthorizationHeader .authorization().ts(ts).nonce(nonce).id(getId()).mac(hmac); if (hasExt()) { headerBuilder.ext(getExt()); } if (hasApp()) { ...
java
public boolean verifyServerAuthorizationMatches(AuthorizationHeader header) { if (!Util.fixedTimeEqual(header.getId(), this.getId())) { return false; } if (header.getTs() != this.getTs()) { return false; } if (!Util.fixedTimeEqual(header.getNonce(), this.getNonce())) { return false; } return tru...
java
public boolean isValidMac(String hmac) throws HawkException { String this_hmac = this.generateHmac(); return Util.fixedTimeEqual(this_hmac, hmac); }
java