List of usage examples for java.net URI getQuery
public String getQuery()
From source file:fr.gael.dhus.olingo.ODataClient.java
/** * Returns the kind of resource the given URI is addressing. * It can be the service root or an entity set or an entity or a simple * property or a complex property.//w ww .j av a 2 s . c om * * @param uri References an OData resource at this service. * * @return the kind of resource the given URI is addressing * * @throws UriSyntaxException violation of the OData URI construction rules. * @throws UriNotMatchingException URI parsing exception. * @throws EdmException if a problem occurs while reading the EDM. * @throws ODataException encapsulate the OData exceptions described above. */ public resourceKind whatIs(URI uri) throws ODataException { if (uri == null) throw new IllegalArgumentException("uri must not be null."); Map<String, String> query_parameters = null; if (uri.getQuery() != null) { query_parameters = new HashMap<>(); StringTokenizer st = new StringTokenizer(uri.getQuery(), "&"); while (st.hasMoreTokens()) { String[] key_val = st.nextToken().split("=", 2); if (key_val.length != 2) throw new UriSyntaxException(UriSyntaxException.URISYNTAX); query_parameters.put(key_val[0], key_val[1]); } } String resource_path = getResourcePath(uri); UriInfo uri_info = parseRequest(resource_path, query_parameters); EdmType et = uri_info.getTargetType(); if (et == null) return resourceKind.SERVICE_ROOT; EdmTypeKind etk = et.getKind(); if (etk == EdmTypeKind.ENTITY) { if (uri_info.getTargetKeyPredicates().isEmpty()) return resourceKind.ENTITY_SET; return resourceKind.ENTITY; } if (etk == EdmTypeKind.SIMPLE) return resourceKind.SIMPLE_PROPERTY; if (etk == EdmTypeKind.COMPLEX) return resourceKind.COMPLEX_PROPERTY; return resourceKind.UNKNOWN; }
From source file:org.eclipse.orion.server.git.servlets.GitCloneHandlerV1.java
private boolean handlePost(HttpServletRequest request, HttpServletResponse response, String pathString) throws IOException, JSONException, ServletException, URISyntaxException, CoreException, NoHeadException, NoMessageException, ConcurrentRefUpdateException, WrongRepositoryStateException { // make sure required fields are set JSONObject toAdd = OrionServlet.readJSONRequest(request); if (toAdd.optBoolean(GitConstants.KEY_PULL, false)) { GitUtils.createGitCredentialsProvider(toAdd); GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(toAdd); boolean force = toAdd.optBoolean(GitConstants.KEY_FORCE, false); return pull(request, response, cp, pathString, force); }//from w w w.j a va2 s . c om Clone clone = new Clone(); String url = toAdd.optString(GitConstants.KEY_URL, null); // method handles repository clone or just repository init // decision is based on existence of GitUrl argument boolean initOnly; if (url == null || url.isEmpty()) initOnly = true; else { initOnly = false; if (!validateCloneUrl(url, request, response)) return true; clone.setUrl(new URIish(url)); } String cloneName = toAdd.optString(ProtocolConstants.KEY_NAME, null); if (cloneName == null) cloneName = request.getHeader(ProtocolConstants.HEADER_SLUG); // expected path /workspace/{workspaceId} String workspacePath = ServletResourceHandler.toOrionLocation(request, toAdd.optString(ProtocolConstants.KEY_LOCATION, null)); // expected path /file/{workspaceId}/{projectName}[/{path}] String filePathString = ServletResourceHandler.toOrionLocation(request, toAdd.optString(ProtocolConstants.KEY_PATH, null)); IPath filePath = filePathString == null ? null : new Path(filePathString); if (filePath != null && filePath.segmentCount() < 3) filePath = null; if (filePath == null && workspacePath == null) { String msg = NLS.bind("Either {0} or {1} should be provided: {2}", new Object[] { ProtocolConstants.KEY_PATH, ProtocolConstants.KEY_LOCATION, toAdd }); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } // only during init operation filePath or cloneName must be provided // during clone operation, name can be obtained from URL if (initOnly && filePath == null && cloneName == null) { String msg = NLS.bind("Either {0} or {1} should be provided: {2}", new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_NAME, toAdd }); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } if (!validateCloneName(cloneName, request, response)) return true; // prepare the WebClone object, create a new project if necessary ProjectInfo project = null; boolean webProjectExists = false; if (filePath != null) { //path format is /file/{workspaceId}/{projectName}/[filePath] clone.setId(filePath.toString()); project = GitUtils.projectFromPath(filePath); //workspace path format needs to be used if project does not exist if (project == null) { String msg = NLS.bind("Specified project does not exist: {0}", filePath.segment(2)); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } webProjectExists = true; clone.setContentLocation( project.getProjectStore().getFileStore(filePath.removeFirstSegments(3)).toURI()); if (cloneName == null) cloneName = filePath.segmentCount() > 2 ? filePath.lastSegment() : project.getFullName(); } else if (workspacePath != null) { IPath path = new Path(workspacePath); // TODO: move this to CloneJob // if so, modify init part to create a new project if necessary final IMetaStore metaStore = OrionConfiguration.getMetaStore(); WorkspaceInfo workspace = metaStore.readWorkspace(path.segment(1)); if (cloneName == null) cloneName = new URIish(url).getHumanishName(); cloneName = getUniqueProjectName(workspace, cloneName); webProjectExists = false; project = new ProjectInfo(); project.setFullName(cloneName); project.setWorkspaceId(workspace.getUniqueId()); try { //creating project in the backing store will assign a project id metaStore.createProject(project); } catch (CoreException e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error persisting project state", e)); } try { WorkspaceResourceHandler.computeProjectLocation(request, project, null, false); metaStore.updateProject(project); } catch (CoreException e) { //delete the project so we don't end up with a project in a bad location try { metaStore.deleteProject(workspace.getUniqueId(), project.getFullName()); } catch (CoreException e1) { //swallow secondary error LogHelper.log(e1); } //we are unable to write in the platform location! String msg = NLS.bind("Failed to create project: {0}", project.getFullName()); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); } URI baseLocation = getURI(request); baseLocation = new URI(baseLocation.getScheme(), baseLocation.getUserInfo(), baseLocation.getHost(), baseLocation.getPort(), workspacePath, baseLocation.getQuery(), baseLocation.getFragment()); clone.setId(GitUtils.pathFromProject(workspace, project).toString()); clone.setContentLocation(project.getProjectStore().toURI()); } clone.setName(cloneName); clone.setBaseLocation(getURI(request)); JSONObject cloneObject = clone.toJSON(); String cloneLocation = cloneObject.getString(ProtocolConstants.KEY_LOCATION); String gitUserName = toAdd.optString(GitConstants.KEY_NAME, null); String gitUserMail = toAdd.optString(GitConstants.KEY_MAIL, null); Boolean initProject = toAdd.optBoolean(GitConstants.KEY_INIT_PROJECT, false); if (initOnly) { // git init InitJob job = new InitJob(clone, TaskJobHandler.getUserId(request), request.getRemoteUser(), cloneLocation, gitUserName, gitUserMail); return TaskJobHandler.handleTaskJob(request, response, job, statusHandler); } // git clone // prepare creds GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(toAdd); cp.setUri(new URIish(clone.getUrl())); // if all went well, clone CloneJob job = new CloneJob(clone, TaskJobHandler.getUserId(request), cp, request.getRemoteUser(), cloneLocation, webProjectExists ? null : project /* used for cleaning up, so null when not needed */, gitUserName, gitUserMail, initProject); return TaskJobHandler.handleTaskJob(request, response, job, statusHandler); }
From source file:edu.stanford.junction.director.JAVADirector.java
private void launchService(URI activityURI, ActivityScript script, String className) { Class c = null;//from ww w . j a va2 s . c om try { c = Class.forName(className); } catch (Exception e) { System.out.println("Could not find class for service " + className + "."); } JunctionService service = null; Method method = null; try { method = c.getMethod("newInstance"); service = (JunctionService) method.invoke(null); } catch (Exception e) { System.out.println("No newInstance method found for " + c + "."); } String queryPart = activityURI.getQuery(); System.out.println("query part is " + queryPart); String localRole = "Unknown"; int i; if ((i = queryPart.indexOf("role=")) >= 0) { localRole = queryPart.substring(i + 14); if ((i = localRole.indexOf("&")) > 0) { localRole = localRole.substring(0, i); } } System.out.println("Setting service role to " + localRole); service.setRole(localRole); System.out.println("service actorID is " + service.getActorID()); try { mMaker.newJunction(activityURI, script, service); } catch (JunctionException e) { e.printStackTrace(); } }
From source file:de.thingweb.thing.Thing.java
public String resolvePropertyUri(String name, int index) { URI uri = getUri(index); Property p = getProperty(name);/*from w w w . j ava 2 s .c o m*/ if (p != null) { try { // String scheme, String userInfo, String host, int port, String path, String query, String fragment String path = uri.getPath(); if (path.endsWith("/")) { path = path + p.getHrefs().get(index); } else { path = path + "/" + p.getHrefs().get(index); } uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path, uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new RuntimeException("TD with malformed hrefs"); } } else { throw new RuntimeException("No such Property"); } return uri.toString(); }
From source file:org.eclipse.orion.server.tests.servlets.files.FileSystemTest.java
protected URI addSchemeHostPort(URI uri) { String scheme = uri.getScheme(); String host = uri.getHost();/*from w w w .j ava 2 s .co m*/ int port = uri.getPort(); if (scheme == null) { scheme = "http"; } if (host == null) { host = "localhost"; } if (port == -1) { port = 8080; } try { return new URI(scheme, uri.getUserInfo(), host, port, uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
From source file:org.apache.synapse.transport.nhttp.ClientWorker.java
/** * Create the thread that would process the response message received for the outgoing message * context sent//w w w . ja va2 s. c o m * @param cfgCtx the Axis2 configuration context * @param in the InputStream to read the body of the response message received * @param response HTTP response received from the server * @param outMsgCtx the original outgoing message context (i.e. corresponding request) * @param endpointURLPrefix The endpoint URL prefix */ public ClientWorker(ConfigurationContext cfgCtx, InputStream in, HttpResponse response, MessageContext outMsgCtx, String endpointURLPrefix) { this.cfgCtx = cfgCtx; this.in = in; this.response = response; this.endpointURLPrefix = endpointURLPrefix; this.outMsgCtx = outMsgCtx; try { responseMsgCtx = outMsgCtx.getOperationContext().getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN); // fix for RM to work because of a soapAction and wsaAction conflict if (responseMsgCtx != null) { responseMsgCtx.setSoapAction(""); } } catch (AxisFault af) { log.error("Error getting IN message context from the operation context", af); return; } // this conditional block is to support Sandesha, as it uses an out-in mep, but without // creating the message context to write the response and adding it into the operation // context, as it may get a 202 accepted or 200. So if the operation is complete ignore // this message, else, create a new message context and handle this if (responseMsgCtx == null && outMsgCtx.getOperationContext().isComplete()) { if (log.isDebugEnabled()) { log.debug("Error getting IN message context from the operation context. " + "Possibly an RM terminate sequence message"); } } else { if (responseMsgCtx == null) { responseMsgCtx = new MessageContext(); responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext()); } responseMsgCtx.setProperty(MessageContext.IN_MESSAGE_CONTEXT, outMsgCtx); responseMsgCtx.setServerSide(true); responseMsgCtx.setDoingREST(outMsgCtx.isDoingREST()); responseMsgCtx.setProperty(MessageContext.TRANSPORT_IN, outMsgCtx.getProperty(MessageContext.TRANSPORT_IN)); responseMsgCtx.setTransportIn(outMsgCtx.getTransportIn()); responseMsgCtx.setTransportOut(outMsgCtx.getTransportOut()); // set any transport headers received Header[] headers = response.getAllHeaders(); if (headers != null && headers.length > 0) { Map<String, String> headerMap = new TreeMap<String, String>(new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); String servicePrefix = (String) outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; // if this header is already added if (headerMap.containsKey(header.getName())) { /* this is a multi-value header */ // generate the key String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS; // get the old value String oldValue = headerMap.get(header.getName()); // adds additional values to a list in a property of // message context Map map; if (responseMsgCtx.getProperty(key) != null) { map = (Map) responseMsgCtx.getProperty(key); map.put(header.getName(), oldValue); } else { map = new MultiValueMap(); map.put(header.getName(), oldValue); // set as a property in message context responseMsgCtx.setProperty(key, map); } } if ("Location".equals(header.getName()) && endpointURLPrefix != null && servicePrefix != null) { //Here, we are changing only the host name and the port of the new URI - value of the Location //header. //If the new URI is again referring to a resource in the server to which the original request //is sent, then replace the hostname and port of the URI with the hostname and port of synapse //We are not changing the request url here, only the host name and the port. try { URI serviceURI = new URI(servicePrefix); URI endpointURI = new URI(endpointURLPrefix); URI locationURI = new URI(header.getValue()); if ((locationURI.getHost().equalsIgnoreCase(endpointURI.getHost())) && (locationURI.getPort() == endpointURI.getPort())) { URI newURI = new URI(locationURI.getScheme(), locationURI.getUserInfo(), serviceURI.getHost(), serviceURI.getPort(), locationURI.getPath(), locationURI.getQuery(), locationURI.getFragment()); headerMap.put(header.getName(), newURI.toString()); responseMsgCtx.setProperty(NhttpConstants.SERVICE_PREFIX, outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX)); } else { headerMap.put(header.getName(), header.getValue()); } } catch (URISyntaxException e) { log.error(e.getMessage(), e); } } else { headerMap.put(header.getName(), header.getValue()); } } responseMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); } responseMsgCtx.setAxisMessage(outMsgCtx.getOperationContext().getAxisOperation() .getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE)); responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext()); responseMsgCtx.setConfigurationContext(outMsgCtx.getConfigurationContext()); responseMsgCtx.setTo(null); // Ensure MessageContext has a ClientConnectionDebug attached before we start streaming ClientConnectionDebug cd = (ClientConnectionDebug) outMsgCtx .getProperty(ClientHandler.CLIENT_CONNECTION_DEBUG); if (cd != null) { responseMsgCtx.setProperty(ClientHandler.CLIENT_CONNECTION_DEBUG, cd); } } setServerContextAttribute(NhttpConstants.CLIENT_WORKER_INIT_TIME, System.currentTimeMillis(), outMsgCtx); }
From source file:org.soyatec.windowsazure.blob.internal.BlockBlob.java
boolean uploadData(IBlobProperties blobProperties, BlobStream stream, long length, boolean overwrite, String eTag, NameValueCollection queryParameters, int action) throws Exception { // fix root container boolean isRoot = container.getName().equals(IBlobContainer.ROOT_CONTAINER); String containerName = isRoot ? "" : container.getName(); ResourceUriComponents uriComponents = new ResourceUriComponents(container.getAccountName(), containerName, blobProperties.getName());/*from ww w. j av a 2 s.c o m*/ URI blobUri = HttpUtilities.createRequestUri(container.getBaseUri(), container.isUsePathStyleUris(), container.getAccountName(), containerName, blobProperties.getName(), container.getTimeout(), queryParameters, uriComponents, container.getCredentials()); if (SSLProperties.isSSL()) { try { URI newBlobUri = new URI("https", null, blobUri.getHost(), 443, blobUri.getPath(), blobUri.getQuery(), blobUri.getFragment()); blobUri = newBlobUri; } catch (Exception e) { e.printStackTrace(); } } HttpRequest request = createHttpRequestForPutBlob(blobUri, HttpMethod.Put, blobProperties, length, overwrite, eTag); // if (isRoot) { // request.addHeader(HeaderNames.ApiVersion, // XmsVersion.VERSION_2009_07_17); // } request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2009_09_19); if (action == BLOB_ACTION || action == BLOCK_ACTION) { // small blob or // block request.addHeader(HeaderNames.BlobType, BlobType.BlockBlob.getLiteral()); } boolean retval = false; BlobStream requestStream = new BlobMemoryStream(); Utilities.copyStream(stream, requestStream, (int) length); byte[] body = requestStream.getBytes(); ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body)); processMD5(blobProperties, request, body, action); container.credentials.signRequest(request, uriComponents); HttpWebResponse response = null; if (SSLProperties.isSSL()) { SSLSocketFactory factory = SslUtil.createSSLSocketFactory(SSLProperties.getKeyStore(), SSLProperties.getKeyStorePasswd(), SSLProperties.getTrustStore(), SSLProperties.getTrustStorePasswd(), SSLProperties.getKeyAlias()); response = HttpUtilities.getSSLReponse((HttpUriRequest) request, factory); } else { response = HttpUtilities.getResponse(request); } if (response.getStatusCode() == HttpStatus.SC_CREATED) { retval = true; } else if (!overwrite && (response.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED || response.getStatusCode() == HttpStatus.SC_NOT_MODIFIED)) { retval = false; } else { retval = false; HttpUtilities.processUnexpectedStatusCode(response); } blobProperties.setLastModifiedTime(response.getLastModified()); blobProperties.setETag(response.getHeader(HeaderNames.ETag)); requestStream.close(); response.close(); return retval; }
From source file:com.openshift.internal.restclient.authorization.OpenShiftAuthorizationRedirectStrategy.java
@Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { // 401 response if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { IAuthorizationDetails details = new AuthorizationDetails(response.getAllHeaders()); throw new UnauthorizedException(details); }/* ww w. ja va2 s .co m*/ // 302 response if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { Header locationHeader = response.getFirstHeader("Location"); if (locationHeader == null) { return false; } URI locationURI = createLocationURI(locationHeader.getValue()); // check access_token fragment param Map<String, String> pairs = URIUtils.splitFragment(locationURI); if (pairs.containsKey(ACCESS_TOKEN)) { final String token = pairs.get(ACCESS_TOKEN); IAuthorizationStrategy strategy = client.getAuthorizationStrategy(); client.setAuthorizationStrategy(new TokenAuthorizationStrategy(token)); this.authcontext = new AuthorizationContext(token, pairs.get(EXPIRES), client.getCurrentUser(), IAuthorizationContext.AUTHSCHEME_BASIC); client.setAuthorizationStrategy(strategy); return false; } // check error query param Map<String, String> queryParams = URIUtils.splitQuery(locationURI.getQuery()); if (queryParams.containsKey(ERROR)) { IAuthorizationDetails details = new AuthorizationDetails(queryParams.get(ERROR), queryParams.get(ERROR_DETAILS)); throw new UnauthorizedException(details); } } return super.isRedirected(request, response, context); }
From source file:org.eclipse.orion.server.git.servlets.GitDiffHandlerV1.java
private boolean identifyNewDiffResource(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {//from w w w . j a va2 s. co m StringWriter writer = new StringWriter(); IOUtilities.pipe(request.getReader(), writer, false, false); JSONObject requestObject = new JSONObject(writer.toString()); URI u = getURI(request); IPath p = new Path(u.getPath()); IPath np = new Path("/"); //$NON-NLS-1$ for (int i = 0; i < p.segmentCount(); i++) { String s = p.segment(i); if (i == 2) { s += ".."; //$NON-NLS-1$ s += GitUtils.encode(requestObject.getString(GitConstants.KEY_COMMIT_NEW)); } np = np.append(s); } if (p.hasTrailingSeparator()) np = np.addTrailingSeparator(); URI nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), np.toString(), u.getQuery(), u.getFragment()); JSONObject result = new JSONObject(); result.put(ProtocolConstants.KEY_LOCATION, nu.toString()); OrionServlet.writeJSONResponse(request, response, result); response.setHeader(ProtocolConstants.HEADER_LOCATION, resovleOrionURI(request, nu).toString()); return true; } catch (Exception e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when identifying a new Diff resource.", e)); } }