List of usage examples for java.net URI toString
public String toString()
From source file:at.ac.ait.ubicity.fileloader.FileLoader.java
/** * /*from w w w . ja v a 2 s . c o m*/ * @param _uri the uri we must "patrol" * @param keySpace the Cassandra keyspace to use * @param host the Cassandra host / node * @param batchSize MutationBatch size for ingests * @param millisToWait the number of milliseconds we are supposed to wait before visiting the uri again * @throws FileNotFoundException if there is a problem with the given uri * @throws Exception if actually loading ( ingesting ) from some file under the uri leads to a problem * */ public final static void invigilate(URI _uri, String keySpace, String host, int batchSize, long millisToWait) throws FileNotFoundException, Exception { logger.info("[FILELOADER] invigilating URI: " + _uri); if (_uri.getScheme().equals("file")) { //we don't know yet if the URI is a directory or a file File _startingPoint = new File(_uri); File[] _files = getLogFilesFor(_startingPoint); FileCache cache = useCache ? LogFileCache.get().loadCache() : null; for (File file : _files) { logger.info("[FILELOADER] found file under " + _uri.toString() + " : " + file.getName()); doLoad(file, cache, keySpace, host, batchSize); } return; } logger.info("[FILELOADER] URI " + _uri.toString() + " is not something FileLoader can currently handle"); }
From source file:com.vmware.admiral.test.integration.BaseIntegrationSupportIT.java
protected static void waitForStatusCode(URI uri, Map<String, String> headers, int expectedStatusCode, int count) throws Exception { for (int i = 0; i < count; i++) { Thread.sleep(STATE_CHANGE_WAIT_POLLING_PERIOD_MILLIS); try {/* www. j a v a 2 s.co m*/ HttpResponse httpResponse = SimpleHttpsClient.execute(HttpMethod.GET, uri.toString(), null, headers, getUnsecuredSSLSocketFactory()); if (expectedStatusCode == httpResponse.statusCode) { return; } } catch (Exception x) { // failed - keep waiting } } throw new RuntimeException( String.format("Failed waiting for status code %s at %s", expectedStatusCode, uri)); }
From source file:com.microsoft.tfs.core.clients.registration.RegistrationData.java
public static RegistrationData newFromServer(final _RegistrationSoap webService, final URI serverURI) { Check.notNull(webService, "webService"); //$NON-NLS-1$ Check.notNull(serverURI, "serverURI"); //$NON-NLS-1$ RegistrationEntry[] entries;/*ww w . ja v a2s . c o m*/ try { entries = (RegistrationEntry[]) WrapperUtils.wrap(RegistrationEntry.class, webService.getRegistrationEntries("")); //$NON-NLS-1$ } catch (final ProxyException e) { throw RegistrationExceptionMapper.map(e); } return new RegistrationData(entries, System.currentTimeMillis(), serverURI.toString()); }
From source file:com.example.app.ui.DemoUserProfileViewer.java
/** * Get the about me./*from w ww . ja v a2 s. co m*/ * * @param videoLink the video link. * @param videoLinkURI the video link uRI. * @param videoLinkComponent the video link component. * @return the about me component or null. */ @Nullable static Component getAboutMe(URL videoLink, URI videoLinkURI, URILink videoLinkComponent) { Component aboutMeVideo = null; IMediaUtility util = MediaUtilityFactory.getUtility(); try { // Check if we can parse the media and it has a stream we like. /// In our made up example, we're only accepting H.264 video. We don't care about the audio in this example. IMediaMetaData mmd; if (util.isEnabled() && videoLinkURI != null && (mmd = util.getMetaData(videoLinkURI.toString())).getStreams().length > 0) { int width = 853, height = 480; // 480p default boolean hasVideo = false; for (IMediaStream stream : mmd.getStreams()) { if (stream.getCodec().getType() == ICodec.Type.video && "H264".equals(stream.getCodec().name())) { hasVideo = true; if (stream.getWidth() > 0) { width = stream.getWidth(); height = stream.getHeight(); } break; } } if (hasVideo) { Media component = new Media(); component.setMediaType(Media.MediaType.video); component.addSource(new MediaSource(videoLinkURI)); component.setFallbackContent(videoLinkComponent); component.setSize(new PixelMetric(width), new PixelMetric(height)); aboutMeVideo = component; } } } catch (IllegalArgumentException | RemoteException e) { _logger.error("Unable to get media information for " + videoLink, e); } return aboutMeVideo; }
From source file:brooklyn.util.ResourceUtils.java
public static URL tidy(URL url) { // File class has helpful methods for URIs but not URLs. So we convert. URI in; try {//from w w w . j a va2s . c om in = url.toURI(); } catch (URISyntaxException e) { throw Exceptions.propagate(e); } URI out; Matcher matcher = pattern.matcher(in.toString()); if (matcher.matches()) { // home-relative File home = new File(Os.home()); File file = new File(home, matcher.group(1)); out = file.toURI(); } else if (in.getScheme().equals("file:")) { // some other file, so canonicalize File file = new File(in); out = file.toURI(); } else { // some other scheme, so no-op out = in; } URL urlOut; try { urlOut = out.toURL(); } catch (MalformedURLException e) { throw Exceptions.propagate(e); } if (!urlOut.equals(url) && log.isDebugEnabled()) { log.debug("quietly changing " + url + " to " + urlOut); } return urlOut; }
From source file:fr.eurecom.nerd.core.proxy.ExtractivClient.java
private static PostMethod getExtractivProcessString(final URI extractivURI, final String content, final String serviceKey) throws FileNotFoundException { final PartBase filePart = new StringPart("content", content, null); // bytes to upload final ArrayList<Part> message = new ArrayList<Part>(); message.add(filePart);/*from w w w . ja v a 2 s . com*/ message.add(new StringPart("formids", "content")); message.add(new StringPart("output_format", "JSON")); message.add(new StringPart("api_key", serviceKey)); final Part[] messageArray = message.toArray(new Part[0]); // Use a Post for the file upload final PostMethod postMethod = new PostMethod(extractivURI.toString()); postMethod.setRequestEntity(new MultipartRequestEntity(messageArray, postMethod.getParams())); postMethod.addRequestHeader("Accept-Encoding", "gzip"); // Request the response be compressed (this is highly recommended) return postMethod; }
From source file:de.fuberlin.agcsw.heraclitus.graph.GraphAnalyse.java
public static void initSailRepository(URI physicalURI, URI namespace) { try {// ww w. j a v a 2 s . c o m rep = new SailRepository(new MemoryStore()); rep.initialize(); RepositoryConnection con = rep.getConnection(); ValueFactory f = rep.getValueFactory(); con.add(physicalURI.toURL(), namespace.toString(), RDFFormat.RDFXML, f.createURI("http://graph.com")); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RDFParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.sworddance.util.UriFactoryImpl.java
/** * * @param baseUri/* ww w . ja v a 2 s .c o m*/ * @param relativeUriString may be an absolute uri when converted to a URI * @return absolute Uri */ public static String absolutize(URI baseUri, String relativeUriString) { URI relativeUri = UriFactoryImpl.createUri(relativeUriString); if (relativeUri != null && relativeUri.isAbsolute()) { return relativeUri.toString(); } notNull(baseUri, "uri should not be null"); if (relativeUriString == null) { ApplicationIllegalArgumentException.valid(baseUri.isAbsolute(), baseUri, ": uri must be absolute because there is no relativeUriString."); return baseUri.resolve(".").toString(); } return baseUri.resolve(relativeUri).toString(); }
From source file:io.mesosphere.mesos.frameworks.cassandra.framework.Main.java
private static int _main() throws UnknownHostException { final Optional<String> portOption = Env.option("PORT0"); if (!portOption.isPresent()) { throw new SystemExitException("Environment variable PORT0 must be defined", 5); }/*ww w . j a v a 2 s. c o m*/ final int port0 = Integer.parseInt(portOption.get()); final String host = Env.option("HOST").or("localhost"); final Optional<String> clusterNameOpt = Env.option("CASSANDRA_CLUSTER_NAME"); final int executorCount = Integer.parseInt(Env.option("CASSANDRA_NODE_COUNT").or("3")); final int seedCount = Integer.parseInt(Env.option("CASSANDRA_SEED_COUNT").or("2")); final double resourceCpuCores = Double.parseDouble(Env.option("CASSANDRA_RESOURCE_CPU_CORES").or("2.0")); final long resourceMemoryMegabytes = Long.parseLong(Env.option("CASSANDRA_RESOURCE_MEM_MB").or("2048")); final long resourceDiskMegabytes = Long.parseLong(Env.option("CASSANDRA_RESOURCE_DISK_MB").or("2048")); final long javaHeapMb = Long.parseLong(Env.option("CASSANDRA_RESOURCE_HEAP_MB").or("0")); final long healthCheckIntervalSec = Long .parseLong(Env.option("CASSANDRA_HEALTH_CHECK_INTERVAL_SECONDS").or("60")); final long bootstrapGraceTimeSec = Long .parseLong(Env.option("CASSANDRA_BOOTSTRAP_GRACE_TIME_SECONDS").or("120")); final String cassandraVersion = "2.1.4"; final String clusterName = clusterNameOpt.or("cassandra"); final String frameworkName = frameworkName(clusterNameOpt); final String zkUrl = Env.option("CASSANDRA_ZK").or("zk://localhost:2181/cassandra-mesos"); final long zkTimeoutMs = Long.parseLong(Env.option("CASSANDRA_ZK_TIMEOUT_MS").or("10000")); final String mesosMasterZkUrl = Env.option("MESOS_ZK").or("zk://localhost:2181/mesos"); final String mesosUser = Env.option("MESOS_USER").or(""); final long failoverTimeout = Long.parseLong(Env.option("CASSANDRA_FAILOVER_TIMEOUT_SECONDS") .or(String.valueOf(Period.days(7).toStandardSeconds().getSeconds()))); final String mesosRole = Env.option("CASSANDRA_FRAMEWORK_MESOS_ROLE").or("*"); final String dataDirectory = Env.option("CASSANDRA_DATA_DIRECTORY").or(DEFAULT_DATA_DIRECTORY); // TODO: Temporary. Will be removed when MESOS-1554 is released final String backupDirectory = Env.option("CASSANDRA_BACKUP_DIRECTORY").or(DEFAULT_BACKUP_DIRECTORY); final boolean jmxLocal = Boolean.parseBoolean(Env.option("CASSANDRA_JMX_LOCAL").or("true")); final boolean jmxNoAuthentication = Boolean .parseBoolean(Env.option("CASSANDRA_JMX_NO_AUTHENTICATION").or("false")); final String defaultRack = Env.option("CASSANDRA_DEFAULT_RACK").or("RAC1"); final String defaultDc = Env.option("CASSANDRA_DEFAULT_DC").or("DC1"); final List<ExternalDc> externalDcs = getExternalDcs(Env.filterStartsWith("CASSANDRA_EXTERNAL_DC_", true)); final Matcher matcher = validateZkUrl(zkUrl); final State state = new ZooKeeperState(matcher.group(1), zkTimeoutMs, TimeUnit.MILLISECONDS, matcher.group(2)); if (seedCount > executorCount || seedCount <= 0 || executorCount <= 0) { throw new IllegalArgumentException( "number of nodes (" + executorCount + ") and/or number of seeds (" + seedCount + ") invalid"); } final PersistedCassandraFrameworkConfiguration configuration = new PersistedCassandraFrameworkConfiguration( state, frameworkName, healthCheckIntervalSec, bootstrapGraceTimeSec, cassandraVersion, resourceCpuCores, resourceDiskMegabytes, resourceMemoryMegabytes, javaHeapMb, executorCount, seedCount, mesosRole, backupDirectory, dataDirectory, jmxLocal, jmxNoAuthentication, defaultRack, defaultDc, externalDcs, clusterName); final FrameworkInfo.Builder frameworkBuilder = FrameworkInfo.newBuilder() .setFailoverTimeout(failoverTimeout).setUser(mesosUser).setName(frameworkName).setRole(mesosRole) .setCheckpoint(true); final Optional<String> frameworkId = configuration.frameworkId(); if (frameworkId.isPresent()) { frameworkBuilder.setId(frameworkId(frameworkId.get())); } final URI httpServerBaseUri = URI.create("http://" + host + ":" + port0 + "/"); final Clock clock = new SystemClock(); final PersistedCassandraClusterHealthCheckHistory healthCheckHistory = new PersistedCassandraClusterHealthCheckHistory( state); final PersistedCassandraClusterState clusterState = new PersistedCassandraClusterState(state); final SeedManager seedManager = new SeedManager(configuration, new ObjectMapper(), new SystemClock()); final CassandraCluster cassandraCluster = new CassandraCluster(clock, httpServerBaseUri.toString(), new ExecutorCounter(state, 0L), clusterState, healthCheckHistory, new PersistedCassandraClusterJobs(state), configuration, seedManager); final HealthReportService healthReportService = new HealthReportService(clusterState, configuration, healthCheckHistory, clock); final Scheduler scheduler = new CassandraScheduler(configuration, cassandraCluster, clock); final JsonFactory factory = new JsonFactory(); final ObjectMapper objectMapper = new ObjectMapper(factory); objectMapper.registerModule(new GuavaModule()); // create JsonProvider to provide custom ObjectMapper JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(); provider.setMapper(objectMapper); final ResourceConfig rc = new ResourceConfig().registerInstances( new FileResourceController(cassandraVersion), new ApiController(factory), new ClusterCleanupController(cassandraCluster, factory), new ClusterRepairController(cassandraCluster, factory), new ClusterRollingRestartController(cassandraCluster, factory), new ClusterBackupController(cassandraCluster, factory), new ClusterRestoreController(cassandraCluster, factory), new ConfigController(cassandraCluster, factory), new LiveEndpointsController(cassandraCluster, factory), new NodeController(cassandraCluster, factory), new HealthCheckController(healthReportService), new QaReportController(cassandraCluster, factory), new ScaleOutController(cassandraCluster, factory), provider); final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(httpServerBaseUri, rc); final MesosSchedulerDriver driver; final Optional<Credential> credentials = getCredential(); if (credentials.isPresent()) { frameworkBuilder.setPrincipal(credentials.get().getPrincipal()); driver = new MesosSchedulerDriver(scheduler, frameworkBuilder.build(), mesosMasterZkUrl, credentials.get()); } else { frameworkBuilder.setPrincipal("cassandra-framework"); driver = new MesosSchedulerDriver(scheduler, frameworkBuilder.build(), mesosMasterZkUrl); } seedManager.startSyncingSeeds(60); final int status; switch (driver.run()) { case DRIVER_STOPPED: status = 0; break; case DRIVER_ABORTED: status = 1; break; case DRIVER_NOT_STARTED: status = 2; break; default: status = 3; break; } httpServer.shutdownNow(); // Ensure that the driver process terminates. driver.stop(true); return status; }
From source file:com.google.cloud.runtime.jetty.util.HttpUrlUtil.java
/** * Wait for a server to be "up" by requesting a specific GET resource * that should be returned in status code 200. * <p>//from www. jav a 2s.c o m * This will attempt a check for server up. * If any result other then response code 200 occurs, then * a 2s delay is performed until the next test. * Up to the duration/timeunit specified. * </p> * * @param uri the URI to request * @param duration the time duration to wait for server up * @param unit the time unit to wait for server up */ public static void waitForServerUp(URI uri, int duration, TimeUnit unit) { System.err.println("Waiting for server up: " + uri); boolean waiting = true; long expiration = System.currentTimeMillis() + unit.toMillis(duration); while (waiting && System.currentTimeMillis() < expiration) { try { System.out.print("."); HttpURLConnection http = openTo(uri); int statusCode = http.getResponseCode(); if (statusCode != HttpURLConnection.HTTP_OK) { log.log(Level.FINER, "Waiting 2s for next attempt"); TimeUnit.SECONDS.sleep(2); } else { waiting = false; } } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid URI: " + uri.toString()); } catch (IOException e) { log.log(Level.FINEST, "Ignoring IOException", e); } catch (InterruptedException ignore) { // ignore } } System.err.println(); System.err.println("Server seems to be up."); }