List of usage examples for java.util Collections list
public static <T> ArrayList<T> list(Enumeration<T> e)
From source file:com.carreygroup.JARVIS.Demon.java
/** * Get IP address from first non-localhost interface * @param ipv4 true=return ipv4, false=return ipv6 * @return address or empty string// w w w. ja va2 s .c om */ public static String getLoaclIPAddress(boolean useIPv4) { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (useIPv4) { if (isIPv4) return sAddr; } else { if (!isIPv4) { int delim = sAddr.indexOf('%'); // drop ip6 port suffix return delim < 0 ? sAddr : sAddr.substring(0, delim); } } } } } } catch (Exception ex) { } // for now eat exceptions return ""; }
From source file:dynamicrefactoring.util.io.FileManager.java
/** * Copia un directorio empaquetado en el plugin en un directorio del sistema * de ficheros./*from w w w . j a va 2 s . co m*/ * * @param bundleDir ruta del directorio en el bundle * @param fileSystemDir ruta del directorio del sistema * @throws IOException si ocurre algun problema al acceder a las rutas */ public static void copyBundleDirToFileSystem(String bundleDir, String fileSystemDir) throws IOException { final Bundle bundle = Platform.getBundle(RefactoringPlugin.BUNDLE_NAME); final Enumeration<?> entries = bundle.findEntries(FilenameUtils.separatorsToUnix(bundleDir), "*", true); final List<?> lista = Collections.list(entries); for (Object entrada : lista) { URL entry = (URL) entrada; File fichero = new File(entry.getFile()); if (!entry.toString().endsWith("/")) { FileUtils.copyURLToFile(entry, new File(fileSystemDir + entry.getFile())); } } }
From source file:org.apache.axis2.classloader.MultiParentClassLoader.java
public Enumeration findResources(String name) throws IOException { if (isDestroyed()) { return Collections.enumeration(Collections.EMPTY_SET); }/*from w ww. j av a 2s. c om*/ List resources = new ArrayList(); // // if we are using inverse class loading, add the resources from local urls first // if (inverseClassLoading && !isDestroyed()) { List myResources = Collections.list(super.findResources(name)); resources.addAll(myResources); } // // Add parent resources // for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; List parentResources = Collections.list(parent.getResources(name)); resources.addAll(parentResources); } // // if we are not using inverse class loading, add the resources from local urls now // if (!inverseClassLoading && !isDestroyed()) { List myResources = Collections.list(super.findResources(name)); resources.addAll(myResources); } return Collections.enumeration(resources); }
From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java
private static void validateEclipseCsMetaPropFile(File file, String pkg, Set<Class<?>> pkgModules) throws Exception { Assert.assertTrue("'checkstyle-metadata.properties' must exist in eclipsecs in inside " + pkg, file.exists());// w w w.jav a 2 s . c o m final Properties prop = new Properties(); prop.load(new FileInputStream(file)); final Set<Object> properties = new HashSet<>(Collections.list(prop.keys())); for (Class<?> module : pkgModules) { final String moduleName = module.getSimpleName(); Assert.assertTrue(moduleName + " requires a name in eclipsecs properties " + pkg, properties.remove(moduleName + ".name")); Assert.assertTrue(moduleName + " requires a desc in eclipsecs properties " + pkg, properties.remove(moduleName + ".desc")); final Set<String> moduleProperties = getFinalProperties(module); for (String moduleProperty : moduleProperties) { Assert.assertTrue( moduleName + " requires the property " + moduleProperty + " in eclipsecs properties " + pkg, properties.remove(moduleName + "." + moduleProperty)); } } for (Object property : properties) { Assert.fail("Unknown property found in eclipsecs properties " + pkg + ": " + property); } }
From source file:org.red5.net.websocket.WebSocketPlugin.java
/** * Returns a new instance of WsServerContainer if one does not already exist. * /* w w w. ja va 2 s . co m*/ * @param servletContext * @return WsServerContainer */ public static ServerContainer getWsServerContainerInstance(ServletContext servletContext) { String path = servletContext.getContextPath(); // handle root if (path.length() == 0) { path = "/"; } log.info("getWsServerContainerInstance: {}", path); DefaultWsServerContainer container; if (containerMap.containsKey(path)) { container = containerMap.get(path); } else { // instance a server container for WS container = new DefaultWsServerContainer(servletContext); if (log.isDebugEnabled()) { log.debug("Attributes: {} params: {}", Collections.list(servletContext.getAttributeNames()), Collections.list(servletContext.getInitParameterNames())); } // get a configurator instance ServerEndpointConfig.Configurator configurator = (ServerEndpointConfig.Configurator) WebSocketPlugin .getWsConfiguratorInstance(); // check for sub protocols log.debug("Checking for subprotocols"); List<String> subProtocols = new ArrayList<>(); Optional<Object> subProtocolsAttr = Optional .ofNullable(servletContext.getInitParameter("subProtocols")); if (subProtocolsAttr.isPresent()) { String attr = (String) subProtocolsAttr.get(); log.debug("Subprotocols: {}", attr); if (StringUtils.isNotBlank(attr)) { if (attr.contains(",")) { // split them up Stream.of(attr.split(",")).forEach(entry -> { subProtocols.add(entry); }); } else { subProtocols.add(attr); } } } else { // default to allowing any subprotocol subProtocols.add("*"); } log.debug("Checking for CORS"); // check for allowed origins override in this servlet context Optional<Object> crossOpt = Optional.ofNullable(servletContext.getAttribute("crossOriginPolicy")); if (crossOpt.isPresent() && Boolean.valueOf((String) crossOpt.get())) { Optional<String> opt = Optional.ofNullable((String) servletContext.getAttribute("allowedOrigins")); if (opt.isPresent()) { ((DefaultServerEndpointConfigurator) configurator).setAllowedOrigins(opt.get().split(",")); } } log.debug("Checking for endpoint override"); // check for endpoint override and use default if not configured String wsEndpointClass = Optional.ofNullable((String) servletContext.getAttribute("wsEndpointClass")) .orElse("org.red5.net.websocket.server.DefaultWebSocketEndpoint"); try { // locate the endpoint class Class<?> endpointClass = Class.forName(wsEndpointClass); log.debug("startWebSocket - endpointPath: {} endpointClass: {}", path, endpointClass); // build an endpoint config ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(endpointClass, path) .configurator(configurator).subprotocols(subProtocols).build(); // set the endpoint on the server container container.addEndpoint(serverEndpointConfig); } catch (Throwable t) { log.warn("WebSocket endpoint setup exception", t); } // store container for lookup containerMap.put(path, container); // add session listener servletContext.addListener(new HttpSessionListener() { @Override public void sessionCreated(HttpSessionEvent se) { log.debug("sessionCreated: {}", se.getSession().getId()); ServletContext sc = se.getSession().getServletContext(); // Don't trigger WebSocket initialization if a WebSocket Server Container is already present if (sc.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE) == null) { // grab the container using the servlet context for lookup DefaultWsServerContainer serverContainer = (DefaultWsServerContainer) WebSocketPlugin .getWsServerContainerInstance(sc); // set the container to the context for lookup sc.setAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE, serverContainer); } } @Override public void sessionDestroyed(HttpSessionEvent se) { log.debug("sessionDestroyed: {}", se); container.closeAuthenticatedSession(se.getSession().getId()); } }); } // set the container to the context for lookup servletContext.setAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE, container); return container; }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
public final void doHandle(HttpServletRequest baseRequest, HttpServletRequest request, HttpServletResponse response, InputStream is) throws IOException, S3Exception { String method = request.getMethod(); String uri = request.getRequestURI(); if (!this.servicePath.isEmpty()) { if (uri.length() > this.servicePath.length()) { uri = uri.substring(this.servicePath.length()); }// w ww . j a v a 2s . c om } logger.debug("request: {}", request); String hostHeader = request.getHeader(HttpHeaders.HOST); if (hostHeader != null && virtualHost.isPresent()) { hostHeader = HostAndPort.fromString(hostHeader).getHostText(); String virtualHostSuffix = "." + virtualHost.get(); if (!hostHeader.equals(virtualHost.get())) { if (hostHeader.endsWith(virtualHostSuffix)) { String bucket = hostHeader.substring(0, hostHeader.length() - virtualHostSuffix.length()); uri = "/" + bucket + uri; } else { String bucket = hostHeader.toLowerCase(); uri = "/" + bucket + uri; } } } boolean hasDateHeader = false; boolean hasXAmzDateHeader = false; for (String headerName : Collections.list(request.getHeaderNames())) { for (String headerValue : Collections.list(request.getHeaders(headerName))) { logger.trace("header: {}: {}", headerName, Strings.nullToEmpty(headerValue)); } if (headerName.equalsIgnoreCase(HttpHeaders.DATE)) { hasDateHeader = true; } else if (headerName.equalsIgnoreCase("x-amz-date")) { hasXAmzDateHeader = true; } } // when access information is not provided in request header, // treat it as anonymous, return all public accessible information if (!anonymousIdentity && (method.equals("GET") || method.equals("HEAD") || method.equals("POST")) && request.getHeader(HttpHeaders.AUTHORIZATION) == null && request.getParameter("X-Amz-Algorithm") == null && request.getParameter("AWSAccessKeyId") == null && defaultBlobStore != null) { doHandleAnonymous(request, response, is, uri, defaultBlobStore); return; } if (!anonymousIdentity && !hasDateHeader && !hasXAmzDateHeader && request.getParameter("X-Amz-Date") == null && request.getParameter("Expires") == null) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED, "AWS authentication requires a valid Date or" + " x-amz-date header"); } // TODO: apply sanity checks to X-Amz-Date if (hasDateHeader) { long date; try { date = request.getDateHeader(HttpHeaders.DATE); } catch (IllegalArgumentException iae) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED, iae); } if (date < 0) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED); } long now = System.currentTimeMillis(); if (now + TimeUnit.DAYS.toMillis(1) < date || now - TimeUnit.DAYS.toMillis(1) > date) { throw new S3Exception(S3ErrorCode.REQUEST_TIME_TOO_SKEWED); } } BlobStore blobStore; String requestIdentity = null; String headerAuthorization = request.getHeader(HttpHeaders.AUTHORIZATION); S3AuthorizationHeader authHeader = null; boolean presignedUrl = false; if (!anonymousIdentity) { if (headerAuthorization == null) { String algorithm = request.getParameter("X-Amz-Algorithm"); if (algorithm == null) { String identity = request.getParameter("AWSAccessKeyId"); String signature = request.getParameter("Signature"); if (identity == null || signature == null) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED); } headerAuthorization = "AWS " + identity + ":" + signature; presignedUrl = true; } else if (algorithm.equals("AWS4-HMAC-SHA256")) { String credential = request.getParameter("X-Amz-Credential"); String signedHeaders = request.getParameter("X-Amz-SignedHeaders"); String signature = request.getParameter("X-Amz-Signature"); if (credential == null || signedHeaders == null || signature == null) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED); } headerAuthorization = "AWS4-HMAC-SHA256" + " Credential=" + credential + ", requestSignedHeaders=" + signedHeaders + ", Signature=" + signature; presignedUrl = true; } } try { authHeader = new S3AuthorizationHeader(headerAuthorization); } catch (IllegalArgumentException iae) { throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT, iae); } requestIdentity = authHeader.identity; } String[] path = uri.split("/", 3); for (int i = 0; i < path.length; i++) { path[i] = URLDecoder.decode(path[i], "UTF-8"); } Map.Entry<String, BlobStore> provider = blobStoreLocator.locateBlobStore(requestIdentity, path.length > 1 ? path[1] : null, path.length > 2 ? path[2] : null); if (anonymousIdentity) { blobStore = provider.getValue(); String contentSha256 = request.getHeader("x-amz-content-sha256"); if ("STREAMING-AWS4-HMAC-SHA256-PAYLOAD".equals(contentSha256)) { is = new ChunkedInputStream(is); } } else if (requestIdentity == null) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED); } else { if (provider == null) { throw new S3Exception(S3ErrorCode.INVALID_ACCESS_KEY_ID); } String credential = provider.getKey(); blobStore = provider.getValue(); String expiresString = request.getParameter("Expires"); if (expiresString != null) { long expires = Long.parseLong(expiresString); long nowSeconds = System.currentTimeMillis() / 1000; if (nowSeconds >= expires) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED); } } String dateString = request.getParameter("X-Amz-Date"); expiresString = request.getParameter("X-Amz-Expires"); if (dateString != null && expiresString != null) { long date = parseIso8601(dateString); long expires = Long.parseLong(expiresString); long nowSeconds = System.currentTimeMillis() / 1000; if (nowSeconds >= date + expires) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED, "Request has expired"); } } switch (authHeader.authenticationType) { case AWS_V2: switch (authenticationType) { case AWS_V2: case AWS_V2_OR_V4: case NONE: break; default: throw new S3Exception(S3ErrorCode.ACCESS_DENIED); } break; case AWS_V4: switch (authenticationType) { case AWS_V4: case AWS_V2_OR_V4: case NONE: break; default: throw new S3Exception(S3ErrorCode.ACCESS_DENIED); } break; case NONE: break; default: throw new IllegalArgumentException("Unhandled type: " + authHeader.authenticationType); } String expectedSignature = null; // When presigned url is generated, it doesn't consider service path String uriForSigning = presignedUrl ? uri : this.servicePath + uri; if (authHeader.hmacAlgorithm == null) { expectedSignature = createAuthorizationSignature(request, uriForSigning, credential); } else { String contentSha256 = request.getHeader("x-amz-content-sha256"); try { byte[] payload; if (request.getParameter("X-Amz-Algorithm") != null) { payload = new byte[0]; } else if ("STREAMING-AWS4-HMAC-SHA256-PAYLOAD".equals(contentSha256)) { payload = new byte[0]; is = new ChunkedInputStream(is); } else if ("UNSIGNED-PAYLOAD".equals(contentSha256)) { payload = new byte[0]; } else { // buffer the entire stream to calculate digest payload = ByteStreams.toByteArray(ByteStreams.limit(is, v4MaxNonChunkedRequestSize + 1)); if (payload.length == v4MaxNonChunkedRequestSize + 1) { throw new S3Exception(S3ErrorCode.MAX_MESSAGE_LENGTH_EXCEEDED); } is = new ByteArrayInputStream(payload); } expectedSignature = createAuthorizationSignatureV4(baseRequest, authHeader, payload, uriForSigning, credential); } catch (InvalidKeyException | NoSuchAlgorithmException e) { throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT, e); } } if (!expectedSignature.equals(authHeader.signature)) { logger.debug("fail to validate signature"); throw new S3Exception(S3ErrorCode.SIGNATURE_DOES_NOT_MATCH); } } for (String parameter : Collections.list(request.getParameterNames())) { if (UNSUPPORTED_PARAMETERS.contains(parameter)) { logger.error("Unknown parameters {} with URI {}", parameter, request.getRequestURI()); throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED); } } // emit NotImplemented for unknown x-amz- headers for (String headerName : Collections.list(request.getHeaderNames())) { if (ignoreUnknownHeaders) { continue; } if (!headerName.startsWith("x-amz-")) { continue; } if (headerName.startsWith("x-amz-meta-")) { continue; } if (!SUPPORTED_X_AMZ_HEADERS.contains(headerName.toLowerCase())) { logger.error("Unknown header {} with URI {}", headerName, request.getRequestURI()); throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED); } } String uploadId = request.getParameter("uploadId"); switch (method) { case "DELETE": if (path.length <= 2 || path[2].isEmpty()) { handleContainerDelete(response, blobStore, path[1]); return; } else if (uploadId != null) { handleAbortMultipartUpload(response, blobStore, path[1], path[2], uploadId); return; } else { handleBlobRemove(response, blobStore, path[1], path[2]); return; } case "GET": if (uri.equals("/")) { handleContainerList(response, blobStore); return; } else if (path.length <= 2 || path[2].isEmpty()) { if ("".equals(request.getParameter("acl"))) { handleGetContainerAcl(response, blobStore, path[1]); return; } else if ("".equals(request.getParameter("location"))) { handleContainerLocation(response, blobStore, path[1]); return; } else if ("".equals(request.getParameter("uploads"))) { handleListMultipartUploads(request, response, blobStore, path[1]); return; } handleBlobList(request, response, blobStore, path[1]); return; } else { if ("".equals(request.getParameter("acl"))) { handleGetBlobAcl(response, blobStore, path[1], path[2]); return; } else if (uploadId != null) { handleListParts(request, response, blobStore, path[1], path[2], uploadId); return; } handleGetBlob(request, response, blobStore, path[1], path[2]); return; } case "HEAD": if (path.length <= 2 || path[2].isEmpty()) { handleContainerExists(blobStore, path[1]); return; } else { handleBlobMetadata(request, response, blobStore, path[1], path[2]); return; } case "POST": if ("".equals(request.getParameter("delete"))) { handleMultiBlobRemove(response, is, blobStore, path[1]); return; } else if ("".equals(request.getParameter("uploads"))) { handleInitiateMultipartUpload(request, response, blobStore, path[1], path[2]); return; } else if (uploadId != null && request.getParameter("partNumber") == null) { handleCompleteMultipartUpload(response, is, blobStore, path[1], path[2], uploadId); return; } break; case "PUT": if (path.length <= 2 || path[2].isEmpty()) { if ("".equals(request.getParameter("acl"))) { handleSetContainerAcl(request, response, is, blobStore, path[1]); return; } handleContainerCreate(request, response, is, blobStore, path[1]); return; } else if (uploadId != null) { if (request.getHeader("x-amz-copy-source") != null) { handleCopyPart(request, response, blobStore, path[1], path[2], uploadId); } else { handleUploadPart(request, response, is, blobStore, path[1], path[2], uploadId); } return; } else if (request.getHeader("x-amz-copy-source") != null) { handleCopyBlob(request, response, is, blobStore, path[1], path[2]); return; } else { if ("".equals(request.getParameter("acl"))) { handleSetBlobAcl(request, response, is, blobStore, path[1], path[2]); return; } handlePutBlob(request, response, is, blobStore, path[1], path[2]); return; } default: break; } logger.error("Unknown method {} with URI {}", method, request.getRequestURI()); throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED); }
From source file:eu.europa.esig.dss.cades.signature.CadesLevelBaselineLTATimestampExtractor.java
/** * The field crlsHashIndex is a sequence of octet strings. Each one contains the hash value of one instance of * RevocationInfoChoice within crls field of the root SignedData. A hash value for every instance of * RevocationInfoChoice, as present at the time when the corresponding archive time-stamp is requested, shall be * included in crlsHashIndex. No other hash values shall be included in this field. * * @return//from w w w . ja v a2 s. c om * @throws eu.europa.esig.dss.DSSException */ @SuppressWarnings("unchecked") private ASN1Sequence getVerifiedCRLsHashIndex(TimestampToken timestampToken) throws DSSException { final ASN1Sequence crlHashes = getCRLHashIndex(timestampToken); final ArrayList<DEROctetString> crlHashesList = Collections.list(crlHashes.getObjects()); final SignedData signedData = SignedData .getInstance(cadesSignature.getCmsSignedData().toASN1Structure().getContent()); final ASN1Set signedDataCRLs = signedData.getCRLs(); if (signedDataCRLs != null) { final Enumeration<ASN1Encodable> crLs = signedDataCRLs.getObjects(); if (crLs != null) { while (crLs.hasMoreElements()) { final ASN1Encodable asn1Encodable = crLs.nextElement(); handleRevocationEncoded(crlHashesList, DSSASN1Utils.getDEREncoded(asn1Encodable)); } } } if (!crlHashesList.isEmpty()) { LOG.error("{} attribute hash in CRL Hashes have not been found in document attributes: {}", crlHashesList.size(), crlHashesList); // return a empty DERSequence to screw up the hash return new DERSequence(); } return crlHashes; }
From source file:com.facebook.buck.jvm.java.DefaultJavaLibraryIntegrationTest.java
@Test public void testBuildJavaLibraryExportsDirectoryEntries() throws IOException { setUpProjectWorkspaceForScenario("export_directory_entries"); // Run `buck build`. BuildTarget target = BuildTargetFactory.newInstance("//:empty_directory_entries"); ProcessResult buildResult = workspace.runBuckBuild(target.getFullyQualifiedName()); buildResult.assertSuccess();/*from w w w . j a v a 2 s. c om*/ Path outputFile = workspace.getPath(BuildTargetPaths.getGenPath(filesystem, target, "lib__%s__output/" + target.getShortName() + ".jar")); assertTrue(Files.exists(outputFile)); ImmutableSet.Builder<String> jarContents = ImmutableSet.builder(); try (ZipFile zipFile = new ZipFile(outputFile.toFile())) { for (ZipEntry zipEntry : Collections.list(zipFile.entries())) { jarContents.add(zipEntry.getName()); } } // TODO(mread): Change the output to the intended output. assertEquals(jarContents.build(), ImmutableSet.of("META-INF/", "META-INF/MANIFEST.MF", "swag.txt", "yolo.txt")); workspace.verify(); }
From source file:org.sltpaya.tool.Utils.java
/** * ?APN?/*from w w w . j a v a 2s .c o m*/ * @return ? */ private boolean getApnStatus() { Matcher matcher; String name; try { Enumeration<NetworkInterface> niList = NetworkInterface.getNetworkInterfaces(); if (niList != null) { for (NetworkInterface intf : Collections.list(niList)) { if (!intf.isUp() || intf.getInterfaceAddresses().size() == 0) { continue; } Log.d(TAG, "isVpnUsed() NetworkInterface Name: " + intf.getName()); name = intf.getName(); matcher = Pattern.compile("tun\\d").matcher(name); if (matcher.find()) { System.out.println("vpn??????" + matcher.group()); return true; } } } } catch (Throwable e) { e.printStackTrace(); } return false; }
From source file:com.springsource.insight.plugin.ldap.TestLdapContext.java
private void logAttributes(String location, Attributes attrs) throws NamingException { NamingEnumeration<? extends Attribute> values = attrs.getAll(); try {// w ww . j a va 2s. c o m while ((values != null) && values.hasMore()) { Attribute aValue = values.next(); String id = aValue.getID(); Collection<?> valsList = Collections.list(aValue.getAll()); logger.trace(location + "[" + id + "]: " + valsList); } } finally { values.close(); } }