org.apache.http.client.utils.URIBuilder Java Examples

The following examples show how to use org.apache.http.client.utils.URIBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: apimanager-swagger-promote   Author: Axway-API-Management-Plus   File: APIManagerAdapter.java    License: Apache License 2.0 8 votes vote down vote up
public String getMethodNameForId(String apiId, String methodId) throws AppException {
	ObjectMapper mapper = new ObjectMapper();
	String response = null;
	URI uri;
	try {
		uri = new URIBuilder(CommandParameters.getInstance().getAPIManagerURL()).setPath(RestAPICall.API_VERSION + "/proxies/"+apiId+"/operations/"+methodId).build();
		RestAPICall getRequest = new GETRequest(uri, null);
		HttpResponse httpResponse = getRequest.execute();
		response = EntityUtils.toString(httpResponse.getEntity());
		EntityUtils.consume(httpResponse.getEntity());
		LOG.trace("Response: " + response);
		JsonNode operationDetails = mapper.readTree(response);
		if(operationDetails.size()==0) {
			LOG.warn("No operation with ID: "+methodId+" found for API with id: " + apiId);
			return null;
		}
		return operationDetails.get("name").asText();
	} catch (Exception e) {
		LOG.error("Can't load name for operation with id: "+methodId+" for API: "+apiId+". Can't parse response: " + response);
		throw new AppException("Can't load name for operation with id: "+methodId+" for API: "+apiId, ErrorCode.API_MANAGER_COMMUNICATION, e);
	}
}
 
Example #2
Source Project: Bhadoo-Cloud-Drive   Author: ParveenBhadooOfficial   File: GoogleOauthController.java    License: MIT License 7 votes vote down vote up
private User getUser(@NotNull Token token) throws IOException, URISyntaxException {

		URIBuilder builder = new URIBuilder(PROFILE_URL);
		builder.addParameter("access_token", token.getAccessToken());

		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpGet httpGet = new HttpGet(builder.build());
		org.apache.http.HttpResponse response = httpClient.execute(httpGet);
		int statusCode = response.getStatusLine().getStatusCode();
		InputStream inputStream = response.getEntity().getContent();

		if (HttpUtilities.success(statusCode)) {
			User user = gson.fromJson(new InputStreamReader(inputStream), User.class);
			user.setToken(token);
			return user;
		}

		throw new ApiException(HttpStatus.valueOf(statusCode));
	}
 
Example #3
Source Project: packagedrone   Author: eclipse   File: UploadApiV2Test.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void upload1 () throws URISyntaxException, IOException
{
    final ChannelTester tester = getTester ();

    final File file = getAbsolutePath ( CommonResources.BUNDLE_1_RESOURCE );

    final URIBuilder b = new URIBuilder ( resolve ( "/api/v2/upload/channel/%s/%s", tester.getId (), file.getName () ) );
    b.setUserInfo ( "deploy", this.deployKey );
    b.addParameter ( "foo:bar", "baz" );

    try ( final CloseableHttpResponse response = upload ( b, file ) )
    {
        Assert.assertEquals ( 200, response.getStatusLine ().getStatusCode () );
    }

    final Set<String> arts = tester.getAllArtifactIds ();

    Assert.assertEquals ( 1, arts.size () );
}
 
Example #4
Source Project: nextcloud-java-api   Author: a-schild   File: ConnectorCommon.java    License: GNU General Public License v3.0 6 votes vote down vote up
private URI buildUrl(String subPath, List<NameValuePair> queryParams)
{
	if(serverConfig.getSubpathPrefix()!=null) {
		subPath = serverConfig.getSubpathPrefix()+"/"+subPath;
	}
	
    URIBuilder uB= new URIBuilder()
    .setScheme(serverConfig.isUseHTTPS() ? "https" : "http")
    .setHost(serverConfig.getServerName())
    .setPort(serverConfig.getPort())
    .setUserInfo(serverConfig.getUserName(), serverConfig.getPassword())
    .setPath(subPath);
    if (queryParams != null)
    {
        uB.addParameters(queryParams);
    }
    try {
        return uB.build();
    } catch (URISyntaxException e) {
        throw new NextcloudApiException(e);
    }
}
 
Example #5
Source Project: apimanager-swagger-promote   Author: Axway-API-Management-Plus   File: UpdateAPIStatus.java    License: Apache License 2.0 6 votes vote down vote up
public void updateRetirementDate(APIChangeState changeState) throws AppException {
	if(changeState!=null && changeState.getNonBreakingChanges().contains("retirementDate")) {
		// Ignore the retirementDate if desiredState is not deprecated as it's used nowhere
		if(!desiredState.getState().equals(IAPI.STATE_DEPRECATED)) {
			LOG.info("Ignoring given retirementDate as API-Status is not set to deprecated");
			return;
		}
		try {
			URI uri = new URIBuilder(cmd.getAPIManagerURL())
					.setPath(RestAPICall.API_VERSION+"/proxies/"+actualState.getId()+"/deprecate").build();
			RestAPICall apiCall = new POSTRequest(new StringEntity("retirementDate="+formatRetirementDate(desiredState.getRetirementDate())), uri, this, true);
			apiCall.setContentType("application/x-www-form-urlencoded");
			apiCall.execute();
		} catch (Exception e) {
			ErrorState.getInstance().setError("Error while updating the retirementDate.", ErrorCode.CANT_UPDATE_API_PROXY);
			throw new AppException("Error while updating the retirementDate", ErrorCode.CANT_UPDATE_API_PROXY);
		}
	} 
	return;
}
 
Example #6
Source Project: org.hl7.fhir.core   Author: hapifhir   File: ResourceAddress.java    License: Apache License 2.0 6 votes vote down vote up
public static URI buildEndpointUriFromString(String endpointPath) {
	URI uri = null; 
	try {
		URIBuilder uriBuilder = new URIBuilder(endpointPath);
		uri = uriBuilder.build();
		String scheme = uri.getScheme();
		String host = uri.getHost();
		if(!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) {
			throw new EFhirClientException("Scheme must be 'http' or 'https': " + uri);
		}
		if(StringUtils.isBlank(host)) {
			throw new EFhirClientException("host cannot be blank: " + uri);
		}
	} catch(URISyntaxException e) {
		throw new EFhirClientException("Invalid URI", e);
	}
	return uri;
}
 
Example #7
Source Project: halyard   Author: spinnaker   File: PublicServiceValidator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void validate(ConfigProblemSetBuilder p, PublicService n) {
  String overrideBaseUrl = n.getOverrideBaseUrl();
  if (!StringUtils.isEmpty(overrideBaseUrl)) {
    try {
      URI uri = new URIBuilder(overrideBaseUrl).build();

      if (StringUtils.isEmpty(uri.getScheme())) {
        p.addProblem(ERROR, "You must supply a URI scheme, e.g. 'http://' or 'https://'");
      }

      if (StringUtils.isEmpty(uri.getHost())) {
        p.addProblem(ERROR, "You must supply a URI host");
      }
    } catch (URISyntaxException e) {
      p.addProblem(ERROR, "Invalid base URL: " + e.getMessage());
    }
  }
}
 
Example #8
Source Project: data-prep   Author: Talend   File: PrepMetadataGetContentUrlGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public AsyncExecutionResult generateResultUrl(Object... args) {

    // check pre-condition
    Validate.notNull(args);
    Validate.isTrue(args.length == 2);
    Validate.isInstanceOf(String.class, args[0]);
    Validate.isInstanceOf(String.class, args[1]);

    String preparationId = (String) args[0];
    String headId = (String) args[1];

    URIBuilder builder = new URIBuilder();
    builder.setPath("/api/preparations/" + preparationId + "/metadata");

    if (StringUtils.isNotEmpty(headId)) {
        builder.setParameter("version", headId);
    }

    return new AsyncExecutionResult(builder.toString());
}
 
Example #9
Source Project: gravitee-gateway   Author: gravitee-io   File: QueryParametersTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void call_get_query_with_special_separator() throws Exception {
    wireMockRule.stubFor(
            get(urlPathEqualTo("/team/my_team"))
                    .willReturn(
                            ok()
                                    .withBody("{{request.query.q}}")
                                    .withTransformers("response-template")));

    String query = "from:2016-01-01;to:2016-01-31";

    URI target = new URIBuilder("http://localhost:8082/test/my_team")
            .addParameter("id", "20000047")
            .addParameter("idType", "1")
            .addParameter("q", query)
            .build();

    HttpResponse response = Request.Get(target).execute().returnResponse();

    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    String responseContent = StringUtils.copy(response.getEntity().getContent());
    assertEquals(query, responseContent);

    wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/team/my_team")));
}
 
Example #10
Source Project: wechatpay-apache-httpclient   Author: wechatpay-apiv3   File: AutoUpdateVerifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getCertificateTest() throws Exception {
  URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
  HttpGet httpGet = new HttpGet(uriBuilder.build());
  httpGet.addHeader("Accept", "application/json");
  CloseableHttpResponse response1 = httpClient.execute(httpGet);
  assertEquals(200, response1.getStatusLine().getStatusCode());
  try {
    HttpEntity entity1 = response1.getEntity();
    // do something useful with the response body
    // and ensure it is fully consumed
    EntityUtils.consume(entity1);
  } finally {
    response1.close();
  }
}
 
Example #11
Source Project: davmail   Author: mguessan   File: HC4ExchangeFormAuthenticator.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected URI getAbsoluteUri(URI uri, String path) throws URISyntaxException {
    URIBuilder uriBuilder = new URIBuilder(uri);
    if (path != null) {
        // reset query string
        uriBuilder.clearParameters();
        if (path.startsWith("/")) {
            // path is absolute, replace method path
            uriBuilder.setPath(path);
        } else if (path.startsWith("http://") || path.startsWith("https://")) {
            return URI.create(path);
        } else {
            // relative path, build new path
            String currentPath = uri.getPath();
            int end = currentPath.lastIndexOf('/');
            if (end >= 0) {
                uriBuilder.setPath(currentPath.substring(0, end + 1) + path);
            } else {
                throw new URISyntaxException(uriBuilder.build().toString(), "Invalid path");
            }
        }
    }
    return uriBuilder.build();
}
 
Example #12
Source Project: pentaho-kettle   Author: pentaho   File: WebService.java    License: Apache License 2.0 6 votes vote down vote up
HttpPost getHttpMethod( String vURLService ) throws URISyntaxException {
  URIBuilder uriBuilder = new URIBuilder( vURLService );
  HttpPost vHttpMethod = new HttpPost( uriBuilder.build() );

  vHttpMethod.setHeader( "Content-Type", "text/xml;charset=UTF-8" );

  String soapAction = "\"" + meta.getOperationNamespace();
  if ( !meta.getOperationNamespace().endsWith( "/" ) ) {
    soapAction += "/";
  }
  soapAction += meta.getOperationName() + "\"";
  logDetailed( BaseMessages.getString( PKG, "WebServices.Log.UsingRequestHeaderSOAPAction", soapAction ) );
  vHttpMethod.setHeader( "SOAPAction", soapAction );

  return vHttpMethod;
}
 
Example #13
Source Project: attic-stratos   Author: apache   File: IntegrationMockClient.java    License: Apache License 2.0 6 votes vote down vote up
public boolean terminateInstance(String instanceId) {
    try {
        if (log.isDebugEnabled()) {
            log.debug(String.format("Terminate instance: [instance-id] %s", instanceId));
        }
        URI uri = new URIBuilder(endpoint + INSTANCES_CONTEXT + instanceId).build();
        org.apache.stratos.mock.iaas.client.rest.HttpResponse response = doDelete(uri);
        if (response != null) {
            if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) {
                return true;
            } else {
                GsonBuilder gsonBuilder = new GsonBuilder();
                Gson gson = gsonBuilder.create();
                org.apache.stratos.mock.iaas.domain.ErrorResponse errorResponse = gson
                        .fromJson(response.getContent(), org.apache.stratos.mock.iaas.domain.ErrorResponse.class);
                if (errorResponse != null) {
                    throw new RuntimeException(errorResponse.getErrorMessage());
                }
            }
        }
        throw new RuntimeException("An unknown error occurred");
    } catch (Exception e) {
        String message = "Could not start mock instance";
        throw new RuntimeException(message, e);
    }
}
 
Example #14
Source Project: cloud-transfer-backend   Author: cloud-transfer   File: GoogleOauthController.java    License: MIT License 6 votes vote down vote up
private User getUser(@NotNull Token token) throws IOException, URISyntaxException {

		URIBuilder builder = new URIBuilder(PROFILE_URL);
		builder.addParameter("access_token", token.getAccessToken());

		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpGet httpGet = new HttpGet(builder.build());
		org.apache.http.HttpResponse response = httpClient.execute(httpGet);
		int statusCode = response.getStatusLine().getStatusCode();
		InputStream inputStream = response.getEntity().getContent();

		if (HttpUtilities.success(statusCode)) {
			User user = gson.fromJson(new InputStreamReader(inputStream), User.class);
			user.setToken(token);
			return user;
		}

		throw new ApiException(HttpStatus.valueOf(statusCode));
	}
 
Example #15
Source Project: flowable-engine   Author: flowable   File: CmmnTaskService.java    License: Apache License 2.0 6 votes vote down vote up
public JsonNode listTasks(ServerConfig serverConfig, ObjectNode bodyNode) {

        JsonNode resultNode = null;
        try {
            URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_TASK_QUERY_URL);

            String uri = clientUtil.getUriWithPagingAndOrderParameters(builder, bodyNode);
            HttpPost post = clientUtil.createPost(uri, serverConfig);

            post.setEntity(clientUtil.createStringEntity(bodyNode.toString()));
            resultNode = clientUtil.executeRequest(post, serverConfig);
        } catch (Exception e) {
            throw new FlowableServiceException(e.getMessage(), e);
        }
        return resultNode;
    }
 
Example #16
Source Project: gocd   Author: gocd   File: HttpRequestBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public HttpRequestBuilder withPath(String path) {
    try {
        URIBuilder uri = new URIBuilder(path);
        request.setServerName("test.host");
        request.setContextPath(CONTEXT_PATH);
        request.setParameters(splitQuery(uri));
        request.setRequestURI(CONTEXT_PATH + uri.getPath());
        request.setServletPath(uri.getPath());
        if (!uri.getQueryParams().isEmpty()) {
            request.setQueryString(URLEncodedUtils.format(uri.getQueryParams(), UTF_8));
        }
        return this;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source Project: sputnik   Author: TouK   File: HttpConnector.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
public URI buildUri(String path, NameValuePair... parameters) throws URISyntaxException {
    HttpHost targetHost = httpClientContext.getTargetHost();

    return new URIBuilder()
            .setHost(targetHost.getHostName())
            .setPort(targetHost.getPort())
            .setScheme(targetHost.getSchemeName())
            .setPath(contextPath + path)
            .setParameters(parameters)
            .build();
}
 
Example #18
Source Project: data-prep   Author: Talend   File: LocatePreparation.java    License: Apache License 2.0 5 votes vote down vote up
private HttpRequestBase onExecute(String id) {
    try {
        URIBuilder uriBuilder = new URIBuilder(preparationServiceUrl + "/preparations/" + id + "/folder");
        return new HttpGet(uriBuilder.build());
    } catch (URISyntaxException e) {
        throw new TDPException(UNEXPECTED_EXCEPTION, e);
    }
}
 
Example #19
Source Project: flowable-engine   Author: flowable   File: CaseInstanceService.java    License: Apache License 2.0 5 votes vote down vote up
public JsonNode getVariables(ServerConfig serverConfig, String caseInstanceId) {
    URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_VARIABLE_INSTANCE_LIST_URL);
    builder.addParameter("caseInstanceId", caseInstanceId);
    builder.addParameter("size", DEFAULT_VARIABLE_RESULT_SIZE);
    builder.addParameter("sort", "variableName");
    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder));
    return clientUtil.executeRequest(get, serverConfig);
}
 
Example #20
Source Project: cs-actions   Author: CloudSlang   File: RunImpl.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
public static String planDetailsUrl(@NotNull final String planId) throws Exception {

    final URIBuilder uriBuilder = getUriBuilder();
    StringBuilder pathString = new StringBuilder()
            .append(API)
            .append(API_VERSION)
            .append(PLAN_DETAILS_PATH)
            .append(PATH_SEPARATOR)
            .append(planId);
    uriBuilder.setPath(pathString.toString());
    return uriBuilder.build().toURL().toString();
}
 
Example #21
Source Project: streams   Author: apache   File: RiakHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
public void start() throws Exception {
  Objects.nonNull(config);
  assert(config.getScheme().startsWith("http"));
  URIBuilder uriBuilder = new URIBuilder();
  uriBuilder.setScheme(config.getScheme());
  uriBuilder.setHost(config.getHosts().get(0));
  uriBuilder.setPort(config.getPort().intValue());
  baseURI = uriBuilder.build();
  client = HttpClients.createDefault();
}
 
Example #22
Source Project: data-prep   Author: Talend   File: PreparationCopyStepsFrom.java    License: Apache License 2.0 5 votes vote down vote up
private HttpRequestBase onExecute(final String to, final String from) {
    try {
        URIBuilder builder = new URIBuilder(preparationServiceUrl + "/preparations/" + to + "/steps/copy");
        builder.addParameter("from", from);
        return new HttpPut(builder.build());
    } catch (URISyntaxException e) {
        throw new TDPException(UNEXPECTED_EXCEPTION, e);
    }
}
 
Example #23
Source Project: cs-actions   Author: CloudSlang   File: VariableImpl.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
public static String listVariablesUrl() throws Exception {

    final URIBuilder uriBuilder = getUriBuilder();
    StringBuilder pathString = new StringBuilder()
            .append(API)
            .append(API_VERSION)
            .append(VARIABLE_PATH);
    uriBuilder.setPath(pathString.toString());
    return uriBuilder.build().toURL().toString();
}
 
Example #24
Source Project: render   Author: saalfeldlab   File: RenderDataClient.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param  stack  name of stack.
 * @param  minZ   (optional) minimum value to include in list.
 * @param  maxZ   (optional) maximum value to include in list.
 *
 * @return z values for the specified stack.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public List<Double> getStackZValues(final String stack,
                                    final Double minZ,
                                    final Double maxZ)
        throws IOException {

    final URIBuilder builder = new URIBuilder(getUri(urls.getStackUrlString(stack) + "/zValues"));

    if (minZ != null) {
        builder.addParameter("minZ", minZ.toString());
    }
    if (maxZ != null) {
        builder.addParameter("maxZ", maxZ.toString());
    }

    final URI uri;
    try {
        uri = builder.build();
    } catch (final URISyntaxException e) {
        throw new IOException(e.getMessage(), e);
    }

    final HttpGet httpGet = new HttpGet(uri);
    final String requestContext = "GET " + uri;
    final TypeReference<List<Double>> typeReference = new TypeReference<List<Double>>() {};
    final JsonUtils.GenericHelper<List<Double>> helper = new JsonUtils.GenericHelper<>(typeReference);
    final JsonResponseHandler<List<Double>> responseHandler = new JsonResponseHandler<>(requestContext, helper);

    LOG.info("getStackZValues: submitting {}", requestContext);

    return httpClient.execute(httpGet, responseHandler);
}
 
Example #25
Source Project: owltools   Author: owlcollab   File: OWLServerSimSearchTest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected HttpUriRequest createGoodCoAnnotationRequest(int n) throws URISyntaxException {
		URIBuilder uriBuilder = new URIBuilder()
			.setScheme("http")
			.setHost("localhost").setPort(9031)
//			.setPath("/owlsim/getCoAnnotationListForAttribute/");
			.setPath("/owlsim/getCoAnnotatedClasses/");
		List<OWLClass> allClasses = new ArrayList<OWLClass>();
		allClasses.addAll(g.getAllOWLClasses());
		Collections.shuffle(allClasses);
		int i=0;
/*
		for (OWLClass c : allClasses) {
			String id = g.getIdentifier(c);
			uriBuilder.addParameter("a", id);

			i++;
			if (i >= n)
				break;
		} */
//		uriBuilder.addParameter("a","HP:0001252");
//		uriBuilder.addParameter("a","HP:0001250");
//		uriBuilder.addParameter("a","HP:0000252");
		uriBuilder.addParameter("a","MP:0002082");
		uriBuilder.addParameter("limit","5");
		URI uri = uriBuilder.build();
		LOG.info("Getting URL="+uri);
		HttpUriRequest httpUriRequest = new HttpGet(uri);
		LOG.info("Got URL="+uri);
		return httpUriRequest;
	}
 
Example #26
Source Project: flowable-engine   Author: flowable   File: CmmnTaskService.java    License: Apache License 2.0 5 votes vote down vote up
public JsonNode getSubTasks(ServerConfig serverConfig, String taskId) {
    URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_TASK_LIST_URL);
    builder.addParameter("parentTaskId", taskId);
    builder.addParameter("size", DEFAULT_SUBTASK_RESULT_SIZE);

    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder));
    return clientUtil.executeRequest(get, serverConfig);
}
 
Example #27
Source Project: torrssen2   Author: tarpha   File: FileStationService.java    License: MIT License 5 votes vote down vote up
public boolean delete(String path) {
    log.debug("File Station Delete");
    boolean ret = false;

    try {
        baseUrl = "http://" + settingService.getSettingValue("DS_HOST") + ":"
                + settingService.getSettingValue("DS_PORT") + "/webapi";

        URIBuilder builder = new URIBuilder(baseUrl + "/entry.cgi");
        builder.setParameter("api", "SYNO.FileStation.Delete").setParameter("version", "2")
                .setParameter("method", "start").setParameter("path", path).setParameter("recursive", "true")
                .setParameter("_sid", sid);

        JSONObject resJson = executeGet(builder);

        log.debug(builder.toString());

        if (resJson != null) {
            log.debug(resJson.toString());
            if (resJson.has("success")) {
                if (Boolean.parseBoolean(resJson.get("success").toString())) {
                    ret = true;
                }
            }
        }

    } catch (URISyntaxException | ParseException | JSONException e) {
        log.error(e.getMessage());
    }

    return ret;
}
 
Example #28
Source Project: vertx-deploy-tools   Author: msoute   File: RequestExecutor.java    License: Apache License 2.0 5 votes vote down vote up
private URI createDeployUri(String host, String endpoint) {
    try {
        return new URIBuilder().setScheme("http").setHost(host).setPort(port).setPath(endpoint).build();
    } catch (URISyntaxException e) {
        throw new IllegalStateException(e);
    }

}
 
Example #29
Source Project: torrssen2   Author: tarpha   File: DownloadStationService.java    License: MIT License 5 votes vote down vote up
public DownloadList getInfo(String id) {
    log.debug("Download Station getInfo");
    DownloadList ret = null;

    try {
        URIBuilder builder = new URIBuilder(baseUrl + "/DownloadStation/task.cgi");
        builder.setParameter("api", "SYNO.DownloadStation.Task").setParameter("version", "3")
                .setParameter("method", "getinfo").setParameter("additional", "detail,transfer")
                .setParameter("id", id).setParameter("_sid", this.sid);

        JSONObject resJson = executeGet(builder);

        if(resJson != null) {
            if(resJson.has("success")) {
                if(Boolean.parseBoolean(resJson.get("success").toString())) {
                    JSONArray jsonArray = resJson.getJSONObject("data").getJSONArray("tasks");

                    ret = setInfo(jsonArray.getJSONObject(0));
                }
            }
        }

    } catch (URISyntaxException | ParseException | JSONException e) {
        log.error(e.getMessage());
    } 

    return ret;
}
 
Example #30
Source Project: rdf4j   Author: eclipse   File: RDF4JProtocolSession.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public synchronized void commitTransaction() throws RDF4JException, IOException, UnauthorizedException {
	checkRepositoryURL();

	if (transactionURL == null) {
		throw new IllegalStateException("Transaction URL has not been set");
	}

	HttpPut method = null;
	try {
		URIBuilder url = new URIBuilder(transactionURL);
		url.addParameter(Protocol.ACTION_PARAM_NAME, Action.COMMIT.toString());
		method = applyAdditionalHeaders(new HttpPut(url.build()));

		final HttpResponse response = execute(method);
		try {
			int code = response.getStatusLine().getStatusCode();
			if (code == HttpURLConnection.HTTP_OK) {
				// we're done.
				transactionURL = null;
				if (ping != null) {
					ping.cancel(false);
				}
			} else {
				throw new RepositoryException("unable to commit transaction. HTTP error code " + code);
			}
		} finally {
			EntityUtils.consumeQuietly(response.getEntity());
		}
	} catch (URISyntaxException e) {
		logger.error("could not create URL for transaction commit", e);
		throw new RuntimeException(e);
	} finally {
		if (method != null) {
			method.reset();
		}
	}
}