code
stringlengths
73
34.1k
label
stringclasses
1 value
public static Map.Entry<String, String> match(Map<String, String> categoriesByPackage, String pkg) { if (categoriesByPackage != null && pkg != null) { for (Map.Entry<String, String> e : categoriesByPackage.entrySet()) { if (Minimatch.minimatch(pkg.replaceAll("\\.", "/"), e.getKey().r...
java
private static long getCachedLastModified(ServletContext servletContext, HeaderAndPath hap) { // Get the cache @SuppressWarnings("unchecked") Map<HeaderAndPath,GetLastModifiedCacheValue> cache = (Map<HeaderAndPath,GetLastModifiedCacheValue>)servletContext.getAttribute(GET_LAST_MODIFIED_CACHE_ATTRIBUTE_NAME); if...
java
public static long getLastModified(ServletContext servletContext, HttpServletRequest request, String path) { return getLastModified( servletContext, request, path, FileUtils.getExtension(path) ); }
java
@Override protected long getLastModified(HttpServletRequest req) { try { ReadableInstant mostRecent = null; for( Tuple2<Book,ReadableInstant> sitemapBook : getSitemapBooks( getServletContext(), req, (HttpServletResponse)req.getAttribute(RESPONSE_IN_REQUEST_ATTRIBUTE) ) ) { Rea...
java
private static boolean hasSiteMapUrl( final ServletContext servletContext, final HttpServletRequest req, final HttpServletResponse resp, final SortedSet<View> views, final Book book, PageRef pageRef ) throws ServletException, IOException { Boolean result = CapturePage.traversePagesAnyOrder( servletCon...
java
protected String getMessageType(final String message) { if (StringUtils.isBlank(defaultMessageType) || MESSAGE_TYPE_TEXT_VALUE .equalsIgnoreCase(defaultMessageType) || MESSAGE_TYPE_LONG_TEXT_VALUE.equalsIgnoreCase(defaultMessageType)) { return message.length() > getMaxLengthOfOneSms() ? MESSAG...
java
protected String createSendTime(final Date sendTime) { if (sendTime == null || new Date(System.currentTimeMillis() + 1000L * 60L).after(sendTime)) { return null; } String customSendTimePattern = StringUtils.isBlank(this.sendTimePattern) ? DEFAULT_SEND_TIME_PATTERN : this.sendTimePa...
java
protected TrustManager[] createTrustAllManagers() { return new TrustManager[]{ new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, ...
java
private String encode(final String value, final Charset charset) { if (StringUtils.isBlank(value)) { return ""; } try { return URLEncoder.encode(value, charset.name()); } catch (UnsupportedEncodingException e) { return value; } }
java
public static SourceMapGenerator fromSourceMap(SourceMapConsumer aSourceMapConsumer) { String sourceRoot = aSourceMapConsumer.sourceRoot; SourceMapGenerator generator = new SourceMapGenerator(aSourceMapConsumer.file, sourceRoot); aSourceMapConsumer.eachMapping().forEach(mapping -> { ...
java
public void setSourceContent(String aSourceFile, String aSourceContent) { String source = aSourceFile; if (this._sourceRoot != null) { source = Util.relative(this._sourceRoot, source); } if (aSourceContent != null) { // Add the source content to the _sourcesConte...
java
private String serializeMappings() { int previousGeneratedColumn = 0; int previousGeneratedLine = 1; int previousOriginalColumn = 0; int previousOriginalLine = 0; int previousName = 0; int previousSource = 0; String result = ""; Mapping mapping; in...
java
public SourceMap toJSON() { SourceMap map = new SourceMap(); map.version = this._version; map.sources = this._sources.toArray(); map.names = this._names.toArray(); map.mappings = serializeMappings(); map.file = this._file; map.sourceRoot = this._sourceRoot; ...
java
public Result<V,E> get( K key, Refresher<? super K,? extends V,? extends E> refresher ) { Result<V,E> result = get(key); if(result == null) result = put(key, refresher); return result; }
java
public Result<V,E> get(K key) { CacheEntry entry = map.get(key); if(entry == null) { return null; } else { return entry.getResult(); } }
java
public Result<V,E> put( K key, Refresher<? super K,? extends V,? extends E> refresher ) { Result<V,E> result = runRefresher(refresher, key); put(key, refresher, result); return result; }
java
public void put( K key, Refresher<? super K,? extends V,? extends E> refresher, V value ) { put(key, refresher, new Result<V,E>(value)); }
java
@Override public void doTag() throws JspTagException, IOException { try { final PageContext pageContext = (PageContext)getJspContext(); NavigationTreeRenderer.writeNavigationTree( pageContext.getServletContext(), pageContext.getELContext(), (HttpServletRequest)pageContext.getRequest(), (HttpSer...
java
public static BasicSourceMapConsumer fromSourceMap(SourceMapGenerator aSourceMap) { BasicSourceMapConsumer smc = new BasicSourceMapConsumer(); ArraySet<String> names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); ArraySet<String> sources = smc._sources = ArraySet.fromArra...
java
void computeColumnSpans() { for (int index = 0; index < _generatedMappings().size(); ++index) { ParsedMapping mapping = _generatedMappings().get(index); // Mappings do not contain a field for the last generated columnt. We // can come up with an optimistic estimate, however,...
java
@Override public boolean hasContentsOfAllSources() { if (sourcesContent == null) { return false; } return this.sourcesContent.size() >= this._sources.size() && !this.sourcesContent.stream().anyMatch(sc -> sc == null); }
java
public static String createFingerprint(Class cl, Method m) { return FingerprintGenerator.fingerprint(cl, m); }
java
public static void enrichContext(Context context) { context.setPostProperty(Context.MEMORY_TOTAL, Runtime.getRuntime().totalMemory()); context.setPostProperty(Context.MEMORY_FREE, Runtime.getRuntime().freeMemory()); context.setPostProperty(Context.MEMORY_USED, Runtime.getRuntime().totalMemory() - Runtime.getRunti...
java
public Version getVersion(String product) throws IllegalArgumentException { String three = properties.getProperty(product); if(three==null) throw new IllegalArgumentException(accessor.getMessage("PropertiesVersions.getVersion.productNotFound", product)); return Version.valueOf(three+"."+getBuild()); }
java
public int getBuild() throws IllegalArgumentException { String build = properties.getProperty("build.number"); if(build==null) throw new IllegalArgumentException(accessor.getMessage("PropertiesVersions.getVersion.buildNotFound")); return Integer.parseInt(build); }
java
public int getNextFiles(final File[] files, final int batchSize) throws IOException { int c=0; while(c<batchSize) { File file=getNextFile(); if(file==null) break; files[c++]=file; } return c; }
java
protected boolean isFilesystemRoot(String filename) throws IOException { String[] roots=getFilesystemRoots(); for(int c=0, len=roots.length;c<len;c++) { if(roots[c].equals(filename)) return true; } return false; }
java
private FilesystemIteratorRule getBestRule(final String filename) { String longestPrefix = null; FilesystemIteratorRule rule = null; // First search the path and all of its parents for the first regular rule String path = filename; while(true) { // Check the current path for an exact match //System.out....
java
public static ServletContextCache getCache(ServletContext servletContext) { ServletContextCache cache = (ServletContextCache)servletContext.getAttribute(ATTRIBUTE_KEY); if(cache == null) { // It is possible this is called during context initialization before the listener cache = new ServletContextCache(servle...
java
public URL getResource(String path) throws MalformedURLException { Result<URL,MalformedURLException> result = getResourceCache.get(path, getResourceRefresher); MalformedURLException exception = result.getException(); if(exception != null) throw exception; return result.getValue(); }
java
protected int binarySearch(int value) { int left = 0; int right = size-1; while(left <= right) { int mid = (left + right)>>1; int midValue = elementData[mid]; if(value==midValue) return mid; if(value<midValue) right = mid-1; else left = mid+1; } return -(left+1); }
java
@Override public int indexOf(int elem) { // Find the location to insert the object at int pos=binarySearch(elem); // Not found if(pos<0) return -1; // Found one, iterate backwards to the first one while(pos>0 && elementData[pos-1]==elem) pos--; return pos; }
java
@Override public boolean add(int o) { // Shortcut for empty int mySize=size(); if(mySize==0) { super.add(o); } else { // Shortcut for adding to end (makes imports of already-sorted data operate at constant-time instead of logarithmic complexity) if(o>=elementData[mySize-1]) { super.add(o); } el...
java
@Override public boolean addAll(Collection<? extends Integer> c) { Iterator<? extends Integer> iter=c.iterator(); boolean didOne=false; while(iter.hasNext()) { add(iter.next().intValue()); didOne=true; } return didOne; }
java
@XmlElement(name = "successfullySent", required = true) @JsonProperty(value = "successfullySent", required = true) public boolean isSuccessfullySent() { return successfullySent; }
java
@Override // @NotThreadSafe public byte get(long position) throws IOException { return mappedBuffers.get(getBufferNum(position)).get(getIndex(position)); }
java
public static void dispatchInclude(RequestDispatcher dispatcher, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SkipPageException { final boolean isOutmostInclude = request.getAttribute(IS_INCLUDED_REQUEST_ATTRIBUTE_NAME) == null; if(logger.isLoggable(Level.FINE)) lo...
java
public static void setLocation(HttpServletRequest request, HttpServletResponse response, String location) { if(request.getAttribute(IS_INCLUDED_REQUEST_ATTRIBUTE_NAME) == null) { // Not included, setHeader directly response.setHeader("Location", location); } else { // Is included, set attribute so top leve...
java
public static void sendError(HttpServletRequest request, HttpServletResponse response, int status, String message) throws IOException { if(request.getAttribute(IS_INCLUDED_REQUEST_ATTRIBUTE_NAME) == null) { // Not included, sendError directly if(message == null) { response.sendError(status); } else { ...
java
protected String createAndlogStackTrace(Failure failure) { StringBuilder sb = new StringBuilder(); if (failure.getMessage() != null && !failure.getMessage().isEmpty()) { sb.append("Failure message: ").append(failure.getMessage()); } if (failure.getException() != null) { ...
java
protected final String getFingerprint(Description description) { return TestResultDataUtils.getFingerprint(description.getTestClass(), description.getMethodName()); }
java
protected final String getPackage(Class cls) { return cls.getPackage() != null ? cls.getPackage().getName() : "defaultPackage"; }
java
public static String getHumanName(String methodName) { char[] name = methodName.toCharArray(); StringBuilder humanName = new StringBuilder(); boolean digit = false; boolean upper = true; int upCount = 0; for (int i = 0; i < name.length; i++) { if (i == 0) {...
java
private static void waitForAll(Iterable<? extends Future<?>> futures) throws InterruptedException, ExecutionException { for(Future<?> future : futures) { future.get(); } }
java
public static StringMessage decode(ByteArray encodedMessage) { if(encodedMessage.size == 0) return EMPTY_STRING_MESSAGE; return new StringMessage(new String(encodedMessage.array, 0, encodedMessage.size, CHARSET)); }
java
@Override public ByteArray encodeAsByteArray() { if(message.isEmpty()) return ByteArray.EMPTY_BYTE_ARRAY; return new ByteArray(message.getBytes(CHARSET)); }
java
public static int readCompressedInt(InputStream in) throws IOException { int b1=in.read(); if(b1==-1) throw new EOFException(); if((b1&0x80)!=0) { // 31 bit int b2=in.read(); if(b2==-1) throw new EOFException(); int b3=in.read(); if(b3==-1) throw new EOFException(); int b4=in.read(); if(b4==-...
java
public String readLongUTF() throws IOException { int length = readCompressedInt(); StringBuilder SB = new StringBuilder(length); for(int position = 0; position<length; position+=20480) { int expectedLen = length - position; if(expectedLen>20480) expectedLen = 20480; String block = readUTF(); if(block....
java
public void synchronize(DefaultTreeModel treeModel, Tree<E> tree) throws IOException, SQLException { assert SwingUtilities.isEventDispatchThread() : ApplicationResources.accessor.getMessage("assert.notRunningInSwingEventThread"); synchronize(treeModel, tree.getRootNodes()); }
java
@SuppressWarnings("unchecked") public void synchronize(DefaultTreeModel treeModel, List<Node<E>> children) throws IOException, SQLException { assert SwingUtilities.isEventDispatchThread() : ApplicationResources.accessor.getMessage("assert.notRunningInSwingEventThread"); if(children==null) { // No children allow...
java
private void checkDates() { DateTime created = this.dateCreated; DateTime published = this.datePublished; DateTime modified = this.dateModified; DateTime reviewed = this.dateReviewed; if( created != null && published != null && published.compareTo(created) < 0 ) throw new IllegalArgumentException("...
java
public Map<String,Element> getElementsById() { synchronized(lock) { if(elementsById == null) return Collections.emptyMap(); if(frozen) return elementsById; return AoCollections.unmodifiableCopyMap(elementsById); } }
java
public Set<String> getGeneratedIds() { synchronized(lock) { if(generatedIds == null) return Collections.emptySet(); if(frozen) return generatedIds; return AoCollections.unmodifiableCopySet(generatedIds); } }
java
public void addElement(Element element) { synchronized(lock) { checkNotFrozen(); element.setPage(this); // elements if(elements == null) elements = new ArrayList<>(); elements.add(element); // elementsById addToElementsById(element, false); } }
java
public static void closeQuietly(final MessageConsumer consumer) { if (consumer != null) { try { consumer.close(); } catch (JMSException je) { if (je.getCause() instanceof InterruptedException) { LOG.trace("ActiveMQ caugh...
java
public static void closeQuietly(final MessageProducer producer) { if (producer != null) { try { producer.close(); } catch (JMSException je) { if (je.getCause() instanceof InterruptedException) { LOG.trace("ActiveMQ caugh...
java
public static ByteArrayMessage decode(String encodedMessage) { if(encodedMessage.isEmpty()) return EMPTY_BYTE_ARRAY_MESSAGE; return new ByteArrayMessage(Base64Coder.decode(encodedMessage)); }
java
public static String encode(String value) { if(value==null) return null; StringBuilder encoded=null; int len=value.length(); for(int c=0;c<len;c++) { char ch=value.charAt(c); if( (ch<' ' && ch!='\n' && ch!='\r') || ch=='\\' ) { if(encoded==null) { encoded=new StringBuilder(); if(...
java
public static DescriptionDescriptor createDescription(DescriptionType descriptionType, Store store) { DescriptionDescriptor descriptionDescriptor = store.create(DescriptionDescriptor.class); descriptionDescriptor.setLang(descriptionType.getLang()); descriptionDescriptor.setValue(descriptionType....
java
public static IconDescriptor createIcon(IconType iconType, Store store) { IconDescriptor iconDescriptor = store.create(IconDescriptor.class); iconDescriptor.setLang(iconType.getLang()); PathType largeIcon = iconType.getLargeIcon(); if (largeIcon != null) { iconDescriptor.setL...
java
public static DisplayNameDescriptor createDisplayName(DisplayNameType displayNameType, Store store) { DisplayNameDescriptor displayNameDescriptor = store.create(DisplayNameDescriptor.class); displayNameDescriptor.setLang(displayNameType.getLang()); displayNameDescriptor.setValue(displayNameType....
java
public static String getRequestEncoding(ServletRequest request) { String requestEncoding = request.getCharacterEncoding(); return requestEncoding != null ? requestEncoding : DEFAULT_REQUEST_ENCODING; }
java
public static void getAbsoluteURL(HttpServletRequest request, String relPath, Appendable out) throws IOException { out.append(request.isSecure() ? "https://" : "http://"); out.append(request.getServerName()); int port = request.getServerPort(); if(port!=(request.isSecure() ? 443 : 80)) out.append(':').append(In...
java
public static String getRedirectLocation( HttpServletRequest request, HttpServletResponse response, String servletPath, String href ) throws MalformedURLException, UnsupportedEncodingException { // Convert page-relative paths to context-relative path, resolving ./ and ../ href = getAbsolutePath(servletPath...
java
public static void sendRedirect( HttpServletResponse response, String location, int status ) throws IllegalStateException, IOException { // Response must not be committed if(response.isCommitted()) throw new IllegalStateException("Unable to redirect: Response already committed"); response.setHeader("Locat...
java
public static void sendRedirect( HttpServletRequest request, HttpServletResponse response, String href, int status ) throws IllegalStateException, IOException { sendRedirect( response, getRedirectLocation( request, response, request.getServletPath(), href ), status ); }
java
public static String getContextRequestUri(HttpServletRequest request) { String requestUri = request.getRequestURI(); String contextPath = request.getContextPath(); int cpLen = contextPath.length(); if(cpLen > 0) { assert requestUri.startsWith(contextPath); return requestUri.substring(cpLen); } else { ...
java
public static <S extends HttpServlet> void doOptions( HttpServletResponse response, Class<S> stopClass, Class<? extends S> thisClass, String doGet, String doPost, String doPut, String doDelete, Class<?>[] paramTypes ) { boolean ALLOW_GET = false; boolean ALLOW_HEAD = false; boolean ALLOW_POST = f...
java
public int getPort() { if (port != 0) { return port; } else { final Connector connector = connectorHolder.get(); if (connector != null) { Preconditions.checkState(connector.getLocalPort() > 0, "no port was set and the connector is not yet s...
java
public static boolean isAllowed(ServletContext servletContext, ServletRequest request) { return Boolean.parseBoolean(servletContext.getInitParameter(ENABLE_INIT_PARAM)) && isAllowedAddr(request.getRemoteAddr()) ; }
java
public static void addFileOpener(ServletContext servletContext, FileOpener fileOpener, String ... extensions) { synchronized(fileOpenersLock) { @SuppressWarnings("unchecked") Map<String,FileOpener> fileOpeners = (Map<String,FileOpener>)servletContext.getAttribute(FILE_OPENERS_REQUEST_ATTRIBUTE_NAME); if(file...
java
public static void removeFileOpener(ServletContext servletContext, String ... extensions) { synchronized(fileOpenersLock) { @SuppressWarnings("unchecked") Map<String,FileOpener> fileOpeners = (Map<String,FileOpener>)servletContext.getAttribute(FILE_OPENERS_REQUEST_ATTRIBUTE_NAME); if(fileOpeners != null) { ...
java
public static void addCookie( HttpServletRequest request, HttpServletResponse response, String cookieName, String value, String comment, int maxAge, boolean secure, boolean contextOnlyPath ) { Cookie newCookie = new Cookie(cookieName, value); if(comment!=null) newCookie.setComment(comment); newCo...
java
public static void removeCookie( HttpServletRequest request, HttpServletResponse response, String cookieName, boolean secure, boolean contextOnlyPath ) { addCookie(request, response, cookieName, "Removed", null, 0, secure, contextOnlyPath); }
java
@Override public int compareTo(Column o) { int diff = name.compareToIgnoreCase(o.name); if(diff!=0) return diff; return name.compareTo(o.name); }
java
@Override public int read() throws IOException { int c = in.read(); if (c == -1) return -1; md5.Update(c); return c; }
java
@Override public int read (byte bytes[], int offset, int length) throws IOException { int r; if ((r = in.read(bytes, offset, length)) == -1) return -1; md5.Update(bytes, offset, r); return r; }
java
void addBundle(EditableResourceBundle bundle) { Locale locale = bundle.getBundleLocale(); if(!locales.contains(locale)) throw new AssertionError("locale not in locales: "+locale); bundles.put(locale, bundle); }
java
public EditableResourceBundle getResourceBundle(Locale locale) { EditableResourceBundle localeBundle = bundles.get(locale); if(localeBundle==null) { ResourceBundle resourceBundle = ResourceBundle.getBundle(baseName, locale); if(!resourceBundle.getLocale().equals(locale)) throw new AssertionError("ResourceBund...
java
public static Boolean getEnvironmentBoolean(String name, Boolean defaultValue) { if (envVars == null) { throw new IllegalStateException("The environment vars must be provided before calling getEnvironmentBoolean."); } String value = getEnvironmentString(name, null); if (val...
java
public static Integer getEnvironmentInteger(String name, Integer defaultValue) { if (envVars == null) { throw new IllegalStateException("The environment vars must be provided before calling getEnvironmentInteger."); } String value = getEnvironmentString(name, null); if (val...
java
public static String getEnvironmentString(String name, String defaultValue) { if (envVars == null) { throw new IllegalStateException("The environment vars must be provided before calling getEnvironmentString."); } return envVars.get(ENV_PREFIX + name) != null ? envVars.get(ENV_PREFI...
java
@Override public String encodeAsString() throws IOException { final int size = messages.size(); if(size == 0) return ""; StringBuilder sb = new StringBuilder(); sb.append(size).append(DELIMITER); int count = 0; for(Message message : messages) { count++; String str = message.encodeAsString(); sb ...
java
@Override public ByteArray encodeAsByteArray() throws IOException { final int size = messages.size(); if(size == 0) return ByteArray.EMPTY_BYTE_ARRAY; AoByteArrayOutputStream bout = new AoByteArrayOutputStream(); try { try (DataOutputStream out = new DataOutputStream(bout)) { out.writeInt(size); in...
java
protected void setLength(long length) throws IOException { if(length<0) throw new IllegalArgumentException("Invalid length: "+length); synchronized(this) { file.seek(8); file.writeLong(length); if(length==0) setFirstIndex(0); } }
java
private boolean isExcludedPath(String requestURI) { if (requestURI == null) return false; if (_excludedPaths != null) { for (String excludedPath : _excludedPaths) { if (requestURI.startsWith(excludedPath)) { ...
java
@SuppressWarnings("unchecked") public static boolean isRunnable(Class cl, Method method, List<FilterDefinition> filters) { // Get the ROX annotations ProbeTest mAnnotation = method.getAnnotation(ProbeTest.class); ProbeTestClass cAnnotation = method.getDeclaringClass().getAnnotation(ProbeTest...
java
private String readUid(File uidFile) { String uid = null; // Try to read the shared UID try (BufferedReader br = new BufferedReader(new FileReader(uidFile))) { String line; while ((line = br.readLine()) != null) { uid = line; } } catc...
java
public static Version getInstance( int major, int minor, int release, int build ) { return new Version(major, minor, release, build); }
java
public static Version valueOf(String version) throws IllegalArgumentException { NullArgumentException.checkNotNull(version, "version"); int dot1Pos = version.indexOf('.'); if(dot1Pos==-1) throw new IllegalArgumentException(version); int dot2Pos = version.indexOf('.', dot1Pos+1); if(dot2Pos==-1) throw new Ille...
java
public static Config getConfig() { final Configuration systemConfig = new SystemConfiguration(); final String configName = systemConfig.getString(CONFIG_PROPERTY_NAME); final String configLocation = systemConfig.getString(CONFIG_LOCATION_PROPERTY_NAME); Preconditions.checkState(confi...
java
public static Config getConfig(@Nonnull final URI configLocation, @Nullable final String configName) { final ConfigFactory configFactory = new ConfigFactory(configLocation, configName); return new Config(configFactory.load()); }
java
public static Config getOverriddenConfig(@Nonnull final Config config, @Nullable final AbstractConfiguration ... overrideConfigurations) { if (overrideConfigurations == null || overrideConfigurations.length == 0) { return config; } final CombinedConfiguration cc = new CombinedCo...
java
public int start() throws Exception { if(isStarted.compareAndSet(false, true)) { try { for(Reporter reporter : reporters) { reporter.start(); } } catch(Exception e) { stop(); throw e; } } return reporters.size();...
java
public void stop() { if(isStarted.compareAndSet(true, false)) { for(Reporter reporter : reporters) { reporter.stop(); } } }
java
public static <T> T xmlNodeToObject(final Node node, final Class<T> valueType, final JAXBContext jaxbContext) throws JAXBException { if (node == null) { return null; } Validate.notNull(valueType, "valueType must not be null"); if (jaxbContext == null) { return valueType.cast(get...
java
public static <T> T jsonMapToObject(final Map<String, Object> map, final Class<T> valueType, final ObjectMapper objectMapper) throws IOException { if (map == null) { return null; } Validate.notNull(valueType, "valueType must not be null"); if (objectMapper == null) { return DEFAULT_OBJ...
java
static <T> ArraySet<T> fromArray(List<T> aArray, Boolean aAllowDuplicates) { ArraySet<T> set = new ArraySet<>(); for (int i = 0, len = aArray.size(); i < len; i++) { set.add(aArray.get(i), aAllowDuplicates); } return set; }
java
Integer indexOf(T t) { if (t == null) { return null; } Integer i = _set.get(t); if (i == null) { return -1; } return i; }
java
T at(Integer i) { if (i == null) { return null; } if (i >= _array.size()) { return null; } return _array.get(i); }
java