/** * Looks up a href within our universe. If the href refers to a document that is not loaded, it * will be loaded. The URL #target will then be checked against the SVG diagram's index and the * coresponding element returned. If there is no coresponding index, null is returned. */ public SVGElement getElement(URI path, boolean loadIfAbsent) { try { // Strip fragment from URI URI xmlBase = new URI(path.getScheme(), path.getSchemeSpecificPart(), null); SVGDiagram dia = (SVGDiagram) loadedDocs.get(xmlBase); if (dia == null && loadIfAbsent) { // System.err.println("SVGUnivserse: " + xmlBase.toString()); // javax.swing.JOptionPane.showMessageDialog(null, xmlBase.toString()); URL url = xmlBase.toURL(); loadSVG(url, false); dia = (SVGDiagram) loadedDocs.get(xmlBase); if (dia == null) { return null; } } String fragment = path.getFragment(); return fragment == null ? dia.getRoot() : dia.getElement(fragment); } catch (Exception e) { Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, "Could not parse path " + path, e); return null; } }
private void mountFiles(String path, Class<?> clazz) { try { List<Resource> list = new ArrayList<>(); String packagePath = clazz.getPackage().getName().replace('.', '/'); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] res = resolver.getResources("classpath:" + packagePath + "/*.png"); if (res != null) { list.addAll(Arrays.asList(res)); } res = resolver.getResources("classpath:" + packagePath + "/*.gif"); if (res != null) { list.addAll(Arrays.asList(res)); } for (Resource resource : list) { URI uri = resource.getURI(); File file = new File(uri.toString()); mountResource( path + "/" + file.getName(), new SharedResourceReference(clazz, file.getName())); } } catch (Exception ex) { LoggingUtils.logUnexpectedException(LOGGER, "Couldn't mount files", ex); } }
private HttpStatus commit(HttpUriRequest method) throws IOException { HttpStatus status; HttpClient httpclient = createHttpClient(); // reduce the TIME_WAIT // method.addHeader("Connection", "close"); if (method.getFirstHeader("Referer") == null) { URI uri = method.getURI(); method.setHeader("Referer", uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort()); } ; try { HttpResponse resp = execute(method, httpclient); status = new HttpStatus(resp.getStatusLine()); if (resp.getEntity() != null) { status.setMessage(EntityUtils.toString(resp.getEntity(), "UTF-8")); } } catch (IOException e) { // cancel the connection when the error happen method.abort(); throw e; } finally { HttpClientUtils.abortConnection(method, httpclient); } return status; }
/** * Returns the diagram that has been loaded from this root. If diagram is not already loaded, * returns null. */ public SVGDiagram getDiagram(URI xmlBase, boolean loadIfAbsent) { if (xmlBase == null) { return null; } SVGDiagram dia = (SVGDiagram) loadedDocs.get(xmlBase); if (dia != null || !loadIfAbsent) { return dia; } // Load missing diagram try { URL url; if ("jar".equals(xmlBase.getScheme()) && xmlBase.getPath() != null && !xmlBase.getPath().contains("!/")) { // Workaround for resources stored in jars loaded by Webstart. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6753651 url = SVGUniverse.class.getResource("xmlBase.getPath()"); } else { url = xmlBase.toURL(); } loadSVG(url, false); dia = (SVGDiagram) loadedDocs.get(xmlBase); return dia; } catch (Exception e) { Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, "Could not parse", e); } return null; }
ValidationResult validateUri(URL url, ValidationRequest request) throws IOException { String parser = request.getValue("parser", null); HttpRequestBase method; List<NameValuePair> qParams = new ArrayList<NameValuePair>(); qParams.add(new BasicNameValuePair("out", "json")); if (parser != null) { qParams.add(new BasicNameValuePair("parser", parser)); } qParams.add(new BasicNameValuePair("doc", url.toString())); try { URI uri = new URI(baseUrl); URI uri2 = URIUtils.createURI( uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), URLEncodedUtils.format(qParams, "UTF-8"), null); method = new HttpGet(uri2); return validate(method); } catch (URISyntaxException e) { throw new IllegalArgumentException("invalid uri. Check your baseUrl " + baseUrl, e); } }
private String lastURL() throws URISyntaxException { try { Address adr = getAddress(); String scheme = decode(getScheme()).toString(); int port = adr.getPort(); if ((scheme.equals("http") && port == 80) || (scheme.equals("https") && port == 443)) { port = -1; } URI uri = new URI(scheme, null, adr.getHost(), port, null, null, null); uri = uri.resolve(getRequestURI()); return uri.toString(); } // URI can also throw IllegalArgumentException wrapping // a URISyntaxException. Unwrap it. catch (IllegalArgumentException x) { Throwable cause = x.getCause(); if ((cause != null) && (cause instanceof URISyntaxException)) { throw (URISyntaxException) cause; } else { throw x; } } }
public void testAddVAppTemplateOrMediaImageToCatalogAndNameItem() throws SecurityException, NoSuchMethodException, IOException { Method method = CatalogAsyncClient.class.getMethod( "addVAppTemplateOrMediaImageToCatalogAndNameItem", URI.class, URI.class, String.class, CatalogItemOptions[].class); HttpRequest request = processor.createRequest( method, URI.create("http://fooentity"), URI.create("https://vcenterprise.bluelock.com/api/v1.0/catalog/1"), "myname", CatalogItemOptions.Builder.description("mydescription")); assertRequestLineEquals( request, "POST https://vcenterprise.bluelock.com/api/v1.0/catalog/1/catalogItems HTTP/1.1"); assertNonPayloadHeadersEqual( request, "Accept: application/vnd.vmware.vcloud.catalogItem+xml\n"); assertPayloadEquals( request, "<CatalogItem xmlns=\"http://www.vmware.com/vcloud/v1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" name=\"myname\" xsi:schemaLocation=\"http://www.vmware.com/vcloud/v1 http://vcloud.safesecureweb.com/ns/vcloud.xsd\"><Description>mydescription</Description><Entity href=\"http://fooentity\"/></CatalogItem>", "application/vnd.vmware.vcloud.catalogItem+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, CatalogItemHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(request); }
@Test public void shouldRemoveRandomNumberQueryParam() throws Exception { context.setThreadingPolicy(new Synchroniser()); final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(GET); expectedRequest.setRequestURI(URI.create("/path?param=value")); context.checking( new Expectations() { { oneOfUnconditionalWrappedResponseRequiredCheck(this); oneOfIsEmulatedWebSocketRequest(this, expectedRequest); oneOf(nextFilter).messageReceived(with(serverSession), with(equal(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_1); httpRequest.setMethod(GET); httpRequest.setRequestURI(URI.create("/path?param=value&.krn=12345")); HttpProtocolCompatibilityFilter filter = new HttpProtocolCompatibilityFilter(); filter.messageReceived(nextFilter, serverSession, httpRequest); context.assertIsSatisfied(); }
@Override public ILayer createLayer(URI source) throws LayerException { if (!source.isAbsolute()) { // If URI is not absolute ex URI.create("../folder/myfile.shp"), then create a canonical URI try { source = new File(location != null ? new File(location) : new File("./"), source.toString()) .getCanonicalFile() .toURI(); } catch (IOException ex) { throw new LayerException(ex); } } String layerName; try { layerName = FileUtils.getNameFromURI(source); } catch (UnsupportedOperationException ex) { try { layerName = dataManager.findUniqueTableName(I18N.tr("Layer")); } catch (SQLException ex2) { throw new LayerException(ex2); } } return createLayer(layerName, source); }
/** * Resolve COLLADA references relative to the COLLADA document. If the reference is relative then * it will resolved relative to the .dae file, not the kml file. If the COLLADA document may be * contained in a KMZ archive the resources will be resolved relative to the .dae file within the * archive. Normally references in a KMZ are resolved relative to the root of the archive, but * Model references are an exception. See * https://developers.google.com/kml/documentation/kmzarchives and * https://developers.google.com/kml/documentation/kmlreference#model * * <p>{@inheritDoc}. */ public String resolveFilePath(String path) throws IOException { KMLLink link = this.model.getLink(); // Check the resource map to see if an alias is defined for this resource. String alias = this.resourceMap.get(path); if (alias != null) path = alias; // If the path is relative then resolve it relative to the COLLADA file. File f = new File(path); if (!f.isAbsolute() && link != null && link.getHref() != null) { try { URI base = new URI(null, link.getHref(), null); URI ref = new URI(null, path, null); path = base.resolve(ref).getPath(); } catch (URISyntaxException ignored) { // Ignored } } Object o = this.parent.getRoot().resolveReference(path); if (o instanceof URL || o instanceof String) return o.toString(); return null; }
public boolean isDirectory(URI uri) { try { if (uri.getPath() != null && uri.getPath().endsWith(".jar!")) { // if the uri is the root of a jar, and it ends with a !, it should be considered a // directory return true; } String jar = getJar(uri); String path = getPath(uri); if (!path.endsWith("/")) { path = path + "/"; } JarFile jarFile = new JarFile(jar); try { JarEntry jarEntry = jarFile.getJarEntry(path); if (jarEntry != null && jarEntry.isDirectory()) { return true; } // maybe the path is not in the jar as a seperate entry, but there are files in the path Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { if (entries.nextElement().getName().startsWith(path)) { return true; } } return false; } finally { jarFile.close(); } } catch (IOException e) { return false; } }
/** * Ctor. * * @param txt Text of the link * @todo #558:30min Href ctor. According to new qulice version, constructor must contain only * variables initialization and other constructor calls. Refactor code according to that rule * and remove `ConstructorOnlyInitializesOrCallOtherConstructors` warning suppression. */ @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", "PMD.ConstructorOnlyInitializesOrCallOtherConstructors" }) public Href(final CharSequence txt) { this.params = new ConcurrentHashMap<String, List<String>>(0); final URI link = Href.createURI(txt.toString()); final String query = link.getRawQuery(); if (query == null) { this.uri = link; } else { final String href = link.toString(); this.uri = URI.create(href.substring(0, href.length() - query.length() - 1)); final String[] pairs = query.split("&"); for (final String pair : pairs) { final String[] parts = pair.split("=", 2); final String key = Href.decode(parts[0]); final String value; if (parts.length > 1) { value = Href.decode(parts[1]); } else { value = ""; } this.params.putIfAbsent(key, new LinkedList<String>()); this.params.get(key).add(value); } } }
@SuppressWarnings("deprecation") @Test public void testReferenceCatalogEntity() throws Exception { getManagementContext().getCatalog().addItem(BasicEntity.class); String yaml = "{ name: simple-app-yaml, location: localhost, services: [ { serviceType: " + BasicEntity.class.getName() + " } ] }"; ClientResponse response = client() .resource("/v1/applications") .entity(yaml, "application/x-yaml") .post(ClientResponse.class); assertTrue(response.getStatus() / 100 == 2, "response is " + response); // Expect app to be running URI appUri = response.getLocation(); waitForApplicationToBeRunning(response.getLocation()); assertEquals( client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-yaml"); ClientResponse response2 = client().resource(appUri.getPath()).delete(ClientResponse.class); assertEquals(response2.getStatus(), Response.Status.ACCEPTED.getStatusCode()); }
@Test(dependsOnMethods = {"testDeployApplication", "testLocatedLocation"}) public void testDeployApplicationFromBuilder() throws Exception { ApplicationSpec spec = ApplicationSpec.builder() .type(RestMockAppBuilder.class.getCanonicalName()) .name("simple-app-builder") .locations(ImmutableSet.of("localhost")) .build(); ClientResponse response = clientDeploy(spec); assertTrue(response.getStatus() / 100 == 2, "response is " + response); // Expect app to be running URI appUri = response.getLocation(); waitForApplicationToBeRunning(response.getLocation(), Duration.TEN_SECONDS); assertEquals( client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-builder"); // Expect app to have the child-entity Set<EntitySummary> entities = client() .resource(appUri.toString() + "/entities") .get(new GenericType<Set<EntitySummary>>() {}); assertEquals(entities.size(), 1); assertEquals(Iterables.getOnlyElement(entities).getName(), "child1"); assertEquals( Iterables.getOnlyElement(entities).getType(), RestMockSimpleEntity.class.getCanonicalName()); }
private void loadURL(URL url) { boolean verbose = cmCheck_verbose.isSelected(); universe = new SVGUniverse(); universe.setVerbose(verbose); SVGDiagram diagram = null; if (!CheckBoxMenuItem_anonInputStream.isSelected()) { // Load from a disk with a valid URL URI uri = universe.loadSVG(url); if (verbose) System.err.println(uri.toString()); diagram = universe.getDiagram(uri); } else { // Load from a stream with no particular valid URL try { InputStream is = url.openStream(); URI uri = universe.loadSVG(is, "defaultName"); if (verbose) System.err.println(uri.toString()); diagram = universe.getDiagram(uri); } catch (Exception e) { e.printStackTrace(); } } svgDisplayPanel.setDiagram(diagram); repaint(); }
private ServerStatus getSpaces(List<Space> spaces, JSONObject orgJSON) throws Exception { URI targetURI = URIUtil.toURI(target.getUrl()); URI spaceURI = targetURI.resolve(orgJSON.getJSONObject("entity").getString("spaces_url")); GetMethod getDomainsMethod = new GetMethod(spaceURI.toString()); HttpUtil.configureHttpMethod(getDomainsMethod, target); getDomainsMethod.setQueryString("inline-relations-depth=1"); // $NON-NLS-1$ ServerStatus status = HttpUtil.executeMethod(getDomainsMethod); if (!status.isOK()) return status; /* extract available spaces */ JSONObject orgs = status.getJsonData(); if (orgs.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) { return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK); } /* look if the domain is available */ int resources = orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).length(); for (int k = 0; k < resources; ++k) { JSONObject spaceJSON = orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).getJSONObject(k); spaces.add(new Space().setCFJSON(spaceJSON)); } return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK); }
@Test public void shouldNotOverrideNextProtocolBasedOnOriginQueryParam() throws Exception { context.setThreadingPolicy(new Synchroniser()); final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(POST); expectedRequest.setRequestURI(URI.create("/path?.ko=http://localhost:8000")); expectedRequest.setHeader("X-Next-Protocol", "other"); expectedRequest.setContent(EMPTY); context.checking( new Expectations() { { oneOfUnconditionalWrappedResponseRequiredCheck(this); oneOfIsEmulatedWebSocketRequest(this, expectedRequest); oneOf(nextFilter).messageReceived(with(serverSession), with(equal(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_1); httpRequest.setMethod(POST); httpRequest.setRequestURI(URI.create("/path?.ko=http://localhost:8000")); httpRequest.setHeader("X-Next-Protocol", "other"); httpRequest.setContent(EMPTY); HttpProtocolCompatibilityFilter filter = new HttpProtocolCompatibilityFilter(); filter.messageReceived(nextFilter, serverSession, httpRequest); context.assertIsSatisfied(); }
public String toString() { // we can't use uri.toString(), which escapes everything, because we want // illegal characters unescaped in the string, for glob processing, etc. StringBuilder buffer = new StringBuilder(); if (uri.getScheme() != null) { buffer.append(uri.getScheme()); buffer.append(":"); } if (uri.getAuthority() != null) { buffer.append("//"); buffer.append(uri.getAuthority()); } if (uri.getPath() != null) { String path = uri.getPath(); if (path.indexOf('/') == 0 && hasWindowsDrive(path, true) && // has windows drive uri.getScheme() == null && // but no scheme uri.getAuthority() == null) // or authority path = path.substring(1); // remove slash before drive buffer.append(path); } if (uri.getFragment() != null) { buffer.append("#"); buffer.append(uri.getFragment()); } return buffer.toString(); }
@Test public void shouldRemoveValidHttpVersionHeader() throws Exception { context.setThreadingPolicy(new Synchroniser()); final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(POST); expectedRequest.setRequestURI(URI.create("/path")); expectedRequest.setContent(EMPTY); context.checking( new Expectations() { { oneOfUnconditionalWrappedResponseRequiredCheck(this); oneOfIsEmulatedWebSocketRequest(this, expectedRequest); oneOf(nextFilter).messageReceived(with(serverSession), with(equal(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_1); httpRequest.setMethod(POST); httpRequest.setRequestURI(URI.create("/path")); httpRequest.setHeader("X-Http-Version", "httpe-1.0"); httpRequest.setContent(EMPTY); HttpProtocolCompatibilityFilter filter = new HttpProtocolCompatibilityFilter(); filter.messageReceived(nextFilter, serverSession, httpRequest); context.assertIsSatisfied(); }
private String getDataStatus(String mTitle) { String title = mTitle; HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); System.out.println( Constant.WEBSERVICE_URL + Constant.WEBSERVICE_Category + "categorytitle=" + title); String url = "categorytitle=" + title; String text = null; try { URI uri = new URI("https", "www.sellyourtime.in", "/api/categories_count.php", url, null); String ll = uri.toASCIIString(); HttpGet httpGet = new HttpGet(ll); try { HttpResponse response = httpClient.execute(httpGet, localContext); HttpEntity entity = response.getEntity(); text = getASCIIContentFromEntity(entity); } catch (Exception e) { return e.getLocalizedMessage(); } } catch (Exception e) { } return text; }
private Uri resolveUri(URI uri) { if (uri.isAbsolute() || absoluteUri == null) { return convertToAndroidUriAndFixScheme(uri, uri); } else { return convertToAndroidUriAndFixScheme(absoluteUri.resolve(uri), absoluteUri); } }
@Override public DDF loadSpecialFormat(DataFormat format, URI fileURI, Boolean flatten) throws DDFException { SparkDDFManager sparkDDFManager = (SparkDDFManager) mDDFManager; HiveContext sqlContext = sparkDDFManager.getHiveContext(); DataFrame jdf = null; switch (format) { case JSON: jdf = sqlContext.jsonFile(fileURI.toString()); break; case PQT: jdf = sqlContext.parquetFile(fileURI.toString()); break; default: throw new DDFException(String.format("Unsupported data format: %s", format.toString())); } DataFrame df = SparkUtils.getDataFrameWithValidColnames(jdf); DDF ddf = sparkDDFManager.newDDF( sparkDDFManager, df, new Class<?>[] {DataFrame.class}, null, SparkUtils.schemaFromDataFrame(df)); if (flatten == true) return ddf.getFlattenedDDF(); else return ddf; }
protected boolean writeClassFileCheck(IFile file, String fileName, byte[] newBytes) throws CoreException { try { byte[] oldBytes = Util.getResourceContentsAsByteArray(file); notEqual: if (newBytes.length == oldBytes.length) { for (int i = newBytes.length; --i >= 0; ) if (newBytes[i] != oldBytes[i]) break notEqual; return false; // bytes are identical so skip them } URI location = file.getLocationURI(); if (location == null) return false; // unable to determine location of this class file String filePath = location.getSchemeSpecificPart(); ClassFileReader reader = new ClassFileReader(oldBytes, filePath.toCharArray()); // ignore local types since they're only visible inside a single method if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) { if (JavaBuilder.DEBUG) System.out.println("Type has structural changes " + fileName); // $NON-NLS-1$ addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); } } catch (ClassFormatException e) { addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); } return true; }
private boolean addRequest(HttpRequest request) { URI uri = null; try { uri = new URI(request.getUri()); } catch (URISyntaxException ex) { logger.error( "Can't create URI from request uri (" + request.getUri() + ")" + ex.getStackTrace()); // FIXME error handling return false; } if (configuration.getFilterStrategy() != FilterStrategy.NONE) { String p = EMPTY; boolean add = true; if (configuration.getFilterStrategy() == FilterStrategy.ONLY) add = true; else if (configuration.getFilterStrategy() == FilterStrategy.EXCEPT) add = false; for (Pattern pattern : configuration.getPatterns()) { switch (pattern.getPatternType()) { case ANT: p = SelectorUtils.ANT_HANDLER_PREFIX; break; case JAVA: p = SelectorUtils.REGEX_HANDLER_PREFIX; break; } p += pattern.getPattern() + SelectorUtils.PATTERN_HANDLER_SUFFIX; if (SelectorUtils.matchPath(p, uri.getPath())) return add; } return !add; } return true; }
/** {@inheritDoc} */ public void saveKeyStore(KeyStore store, char[] password) throws KeyStoreException, IOException { if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug("Writing " + store + " to " + keystore_location); } try { OutputStream os = null; if ("file".equalsIgnoreCase(keystore_location.getScheme())) { os = new FileOutputStream(new File(keystore_location)); } else { os = keystore_location.toURL().openConnection().getOutputStream(); } store.store(os, password); } catch (NoSuchAlgorithmException failed) { KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); failure.initCause(failed); throw failure; } catch (CertificateException failed) { KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); failure.initCause(failed); throw failure; } }
public static URI getAuthorizationUrl( URI loginServer, String clientId, String callbackUrl, String[] scopes, String clientSecret, String displayType) { if (displayType == null) displayType = "touch"; final StringBuilder sb = new StringBuilder(loginServer.toString()); sb.append(OAUTH_AUTH_PATH); sb.append(displayType); if (clientSecret != null) { sb.append("&").append(RESPONSE_TYPE).append("=").append(ACTIVATED_CLIENT_CODE); } else { sb.append("&").append(RESPONSE_TYPE).append("=").append(TOKEN); } sb.append("&").append(CLIENT_ID).append("=").append(Uri.encode(clientId)); if ((null != scopes) && (scopes.length > 0)) { // need to always have the refresh_token scope to reuse our refresh token sb.append("&").append(SCOPE).append("=").append(REFRESH_TOKEN); StringBuilder scopeStr = new StringBuilder(); for (String scope : scopes) { if (!scope.equalsIgnoreCase(REFRESH_TOKEN)) { scopeStr.append(" ").append(scope); } } String safeScopeStr = Uri.encode(scopeStr.toString()); sb.append(safeScopeStr); } sb.append("&redirect_uri="); sb.append(callbackUrl); return URI.create(sb.toString()); }
/** * Return an array containing hostnames, offset and size of portions of the given file. For a * nonexistent file or regions, null will be returned. * * <p>This call is most helpful with DFS, where it returns hostnames of machines that contain the * given file. * * <p>The FileSystem will simply return an elt containing 'localhost'. */ @Override public BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len) throws IOException { // Check if requested file in Swift is more than 5Gb. In this case // each block has its own location -which may be determinable // from the Swift client API, depending on the remote server final FileStatus[] listOfFileBlocks = store.listSubPaths(file.getPath()); List<URI> locations = new ArrayList<URI>(); if (listOfFileBlocks.length > 1) { for (FileStatus fileStatus : listOfFileBlocks) { if (SwiftObjectPath.fromPath(uri, fileStatus.getPath()) .equals(SwiftObjectPath.fromPath(uri, file.getPath()))) { continue; } locations.addAll(store.getObjectLocation(fileStatus.getPath())); } } else { locations = store.getObjectLocation(file.getPath()); } final String[] names = new String[locations.size()]; final String[] hosts = new String[locations.size()]; int i = 0; for (URI location : locations) { hosts[i] = location.getHost(); names[i] = location.getAuthority(); i++; } return new BlockLocation[] {new BlockLocation(names, hosts, 0, file.getLen())}; }
/** * This method logs into a service by doing an standard http using the configuration in this * class. * * @param username the username to log into the application with * @param password the password to log into the application with * @return the url that the login redirects to */ public String login(String username, String password) { MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add(usernameInputFieldName, username); form.add(passwordInputFieldName, password); URI location = this.template.postForLocation(loginUrl(), form); return location.toString(); }
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) { String baseUrl = "http://localhost:" + this.context.getEmbeddedServletContainer().getPort(); RestTemplate rest = new TestRestTemplate(); // First, verify the web endpoint can't be reached assertEndpointUnauthorized(baseUrl, rest); // Since we can't reach it, need to collect an authorization token HttpHeaders headers = getHeaders(config); String url = baseUrl + "/oauth/token"; JsonNode tokenResponse = rest.postForObject( url, new HttpEntity<MultiValueMap<String, Object>>(getBody(), headers), JsonNode.class); String authorizationToken = tokenResponse.findValue("access_token").asText(); String tokenType = tokenResponse.findValue("token_type").asText(); String scope = tokenResponse.findValues("scope").get(0).toString(); assertThat(tokenType, equalTo("bearer")); assertThat(scope, equalTo("\"read\"")); // Now we should be able to see that endpoint. headers.set("Authorization", "BEARER " + authorizationToken); ResponseEntity<String> securedResponse = rest.exchange( new RequestEntity<Void>(headers, HttpMethod.GET, URI.create(baseUrl + "/securedFind")), String.class); assertThat(securedResponse.getStatusCode(), equalTo(HttpStatus.OK)); assertThat( securedResponse.getBody(), equalTo("You reached an endpoint " + "secured by Spring Security OAuth2")); ResponseEntity<String> entity = rest.exchange( new RequestEntity<Void>(headers, HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class); assertThat(entity.getStatusCode(), equalTo(finalStatus)); }
@Test public void shouldNotRequireExplicitPort() throws Exception { ResourceAddress address = addressFactorySpi.newResourceAddress(URI.create("httpx+ssl://localhost/")); URI location = address.getResource(); assertEquals(location.getPort(), 443); }