Example usage for org.springframework.web.client RestTemplate RestTemplate

List of usage examples for org.springframework.web.client RestTemplate RestTemplate

Introduction

In this page you can find the example usage for org.springframework.web.client RestTemplate RestTemplate.

Prototype

public RestTemplate() 

Source Link

Document

Create a new instance of the RestTemplate using default settings.

Usage

From source file:com.wavemaker.tools.deployment.tomcat.TomcatManager.java

/**
 * Create a new {@link TomcatManager}.//w  w  w.j  a v a 2s. co m
 * 
 * @param host the remote host
 * @param port the remote port
 * @param managerPath the path of the manager application
 * @param username the username used to connect
 * @param password the password used to connect
 */
public TomcatManager(String host, int port, String managerPath, String username, String password) {
    Assert.notNull(host, "Host must not be null");
    Assert.notNull(managerPath, "ManagerPath must not be null");
    this.host = host;
    this.port = port;
    this.managerPath = managerPath;
    this.restTemplate = new RestTemplate();
    SimpleClientHttpRequestFactory requestFactory = new PerformantSimpleClientHttpRequestFactory();
    requestFactory.setBufferRequestBody(false);
    this.restTemplate
            .setRequestFactory(new AuthorizedClientHttpRequestFactory(requestFactory, username, password));
    this.restTemplate.getMessageConverters().add(0, new InputStreamMessageConverter());
}

From source file:com.platzerworld.e4.biergarten.model.mock.MockBiergarten.java

private List<?> doSearch(String url, Map<String, String> urlVariables, String xpath, NodeMapper mapper) {
    ProxyAuthenticator.authenticate();//www .j  a  va  2 s  .  c om
    Source payload;
    if (urlVariables == null) {
        payload = new RestTemplate().getForObject(url, Source.class);
    } else {
        payload = new RestTemplate().getForObject(url, Source.class, urlVariables);
    }
    return new Jaxp13XPathTemplate().evaluate(xpath, payload, mapper);
}

From source file:org.springframework.hateoas.client.Traverson.java

private static final RestOperations createDefaultTemplate(List<MediaType> mediaTypes) {

    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));

    if (mediaTypes.contains(MediaTypes.HAL_JSON)) {
        converters.add(getHalConverter());
    }//from  w w  w . ja v  a2  s .c o  m

    RestTemplate template = new RestTemplate();
    template.setMessageConverters(converters);

    return template;
}

From source file:com.ecsteam.cloudlaunch.services.jenkins.JenkinsService.java

public QueuedBuildResponse getJobNumberFromQueue(String queueId) {
    RestTemplate template = new RestTemplate();
    QueuedBuildResponse response = null;

    // let's just be 100% sure that we don't enter an infinite loop (almost certainly never would)
    // we have to continuously check this URL because the queued item goes away quickly, so we need
    // to get the job number ASAP
    for (int count = 0; count < 1000; ++count) {
        ResponseEntity<QueueItemResponseFragment> fragmentEntity = template.exchange(
                "{baseUrl}/queue/item/{queueId}/api/json", HttpMethod.GET, getAuthorizationEntity(),
                QueueItemResponseFragment.class, baseUrl, queueId);

        if (!HttpStatus.OK.equals(fragmentEntity.getStatusCode())) {
            return null;
        }// w  w w .j a  v  a2 s  . c  o m

        QueueItemResponseFragment fragment = fragmentEntity.getBody();
        if (fragment.getExecutable() != null && fragment.getExecutable().getUrl() != null) {
            String monitorUrl = fragment.getExecutable().getUrl();
            String last = null;
            String current = null;
            String next = null;

            String[] parts = monitorUrl.split("/");

            response = new QueuedBuildResponse();
            for (int i = parts.length - 1; i >= 0; --i) {
                last = parts[i];
                current = parts[i - 1];
                next = parts[i - 2];

                if ("job".equals(next) && jobName.equals(current)) {
                    response = new QueuedBuildResponse();
                    response.setMonitorUri(String.format("/services/builds/job/%s", last));

                    return response;
                }
            }
        }
    }

    return null;
}

From source file:org.trustedanalytics.user.invite.config.SecurityConfig.java

@Bean
public JwtAccessTokenConverter myjwtTokenEnhancer() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
    DefaultUserAuthenticationConverter userTokenConverter = new ScopeAuthoritiesTokenConverter();
    accessTokenConverter.setUserTokenConverter(userTokenConverter);
    converter.setAccessTokenConverter(accessTokenConverter);

    String keyValue = resource.getJwt().getKeyValue();
    if (!StringUtils.hasText(keyValue)) {
        try {/*from ww w  . ja va  2 s  .  c o m*/
            keyValue = (String) new RestTemplate().getForObject(resource.getJwt().getKeyUri(), Map.class)
                    .get("value");
        } catch (ResourceAccessException e) {
            throw new TokenFetchException("Failed to fetch token key from " + resource.getJwt().getKeyUri(), e);
        }
    } else {
        if (StringUtils.hasText(keyValue) && !keyValue.startsWith("-----BEGIN")) {
            converter.setSigningKey(keyValue);
        }
    }
    converter.setVerifierKey(keyValue);

    return converter;
}

From source file:org.n52.tamis.rest.forward.processes.jobs.StatusRequestForwarder.java

/**
 * {@inheritDoc} <br/>//ww  w . j  av  a  2  s .  c  o m
 * <br/>
 * Delegates an incoming status description request to the WPS proxyand
 * creates an instance of {@link StatusDescription}
 * 
 * @param parameterValueStore
 *            must contain the URL variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} to
 *            identify the WPS instance and
 *            {@link URL_Constants_TAMIS#PROCESS_ID_VARIABLE_NAME} to
 *            identify the process and
 *            {@link URL_Constants_TAMIS#JOB_ID_VARIABLE_NAME} to identify
 *            the job
 * @return an instance of {@link StatusDescription}
 */
@Override
public StatusDescription forwardRequestToWpsProxy(HttpServletRequest request, Object requestBody,
        ParameterValueStore parameterValueStore) {
    initializeRequestSpecificParameters(parameterValueStore);

    String statusDescription_url_wpsProxy = createTargetURL_WpsProxy(request);

    RestTemplate statusDescriptionTemplate = new RestTemplate();

    // fetch the status description from WPS proxy and
    // deserialize it into TAMIS status decsription
    StatusDescription statusDescriptionDoc = statusDescriptionTemplate
            .getForObject(statusDescription_url_wpsProxy, StatusDescription.class);

    String outputs = statusDescriptionDoc.getStatusInfo().getOutput();

    if (outputs != null) {
        /*
         * we want to replace the baseURL of the outputUrl field of the
         * statusDescription. From the WPS proxy, the returned outputUrl
         * field will point to a URL specific for the proxy. We need to
         * replace it with the right URL of this application (the base URL
         * will change).
         * 
         * outputURL_wpsProxy =
         * <baseURL_WpsProxy>/processes/<process_id>/jobs/<job_id>
         * outputURL_tamis =
         * <baseURL_Tamis>tamis_prefix/<service_id>/processes/<process_id>/
         * jobs/< job_id>
         */
        String tamis_baseUrl = constructTamisBaseUrl(request);

        String outputURL_tamis = tamis_baseUrl + "/" + URL_Constants_TAMIS.API_V1_BASE_PREFIX + "/"
                + URL_Constants_TAMIS.TAMIS_PREFIX + "/" + this.getServiceId()
                + URL_Constants_TAMIS.SLASH_PROCESSES + "/" + this.getProcessId()
                + URL_Constants_TAMIS.SLASH_JOBS + "/" + this.getJobId() + URL_Constants_TAMIS.SLASH_OUTPUTS;
        statusDescriptionDoc.getStatusInfo().setOutput(outputURL_tamis);
    }

    return statusDescriptionDoc;
}

From source file:org.avidj.zuul.client.ZuulRestClient.java

@Override
public boolean lock(String sessionId, List<String> path, LockType type, LockScope scope) {
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    Map<String, String> parameters = new HashMap<>();
    parameters.put("id", sessionId); // set the session id
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(serviceUrl + lockPath(path))
            .queryParam("t", type(type)).queryParam("s", scope(scope));

    ResponseEntity<String> result = restTemplate.exchange(uriBuilder.build().encode().toUri(), HttpMethod.PUT,
            entity, String.class);

    LOG.info(result.toString());/*from  w w  w. jav a2s .c  o  m*/
    HttpStatus code = result.getStatusCode();
    return code.equals(HttpStatus.CREATED);
}

From source file:org.cloudfoundry.identity.uaa.login.EmailResetPasswordServiceTests.java

@Before
public void setUp() throws Exception {
    RestTemplate uaaTemplate = new RestTemplate();
    mockUaaServer = MockRestServiceServer.createServer(uaaTemplate);
    messageService = Mockito.mock(EmailService.class);
    emailResetPasswordService = new EmailResetPasswordService(templateEngine, messageService, uaaTemplate,
            "http://uaa.example.com/uaa", "pivotal");
}

From source file:org.n52.tamis.rest.forward.processes.SingleProcessDescriptionRequestForwarder.java

/**
 * {@inheritDoc} <br/>//from w  w  w. j ava2 s .c  o m
 * <br/>
 * Delegates an incoming single process description request to the WPS
 * proxy, receives the extended single process description document and
 * creates an instance of {@link ProcessDescription_singleProcess}
 * 
 * @param parameterValueStore
 *            must contain the URL variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} to
 *            identify the WPS instance and
 *            {@link URL_Constants_TAMIS#PROCESS_ID_VARIABLE_NAME} to
 *            identify the process
 * @return an instance of {@link ProcessDescription_singleProcess}
 */
@Override
public ProcessDescription_singleProcess forwardRequestToWpsProxy(HttpServletRequest request, Object requestBody,
        ParameterValueStore parameterValueStore) {
    initializeRequestSpecificParameters(parameterValueStore);

    String singleProcessDescription_url_wpsProxy = createTargetURL_WpsProxy(request);

    RestTemplate singleProcessDescriptionTemplate = new RestTemplate();

    // fetch extended singlePocessDescriptionDoc from WPS proxy and
    // deserialize it into
    // shortened singlePocessDescriptionDoc
    ProcessDescription_singleProcess singeleProcessDescriptionDoc = singleProcessDescriptionTemplate
            .getForObject(singleProcessDescription_url_wpsProxy, ProcessDescription_singleProcess.class);

    return singeleProcessDescriptionDoc;
}

From source file:com.atwelm.aezwidget.data.ConfigurationServer.java

/**
 * Loads the layouts from the server and provides them in the callback if provided
 * @param callback Contains the layouts or error information
 *///ww  w  .jav a 2s  .  c o m
public void loadLayouts(final LoadLayoutCallback callback) {
    final ConfigurationServer self = this;
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());

                ResponseEntity<AEZFetchLayoutResponseInterface> responseEntity = restTemplate
                        .getForEntity(mServerAddress, mServerType.getResponseClass());

                int returnStatus = responseEntity.getStatusCode().value();

                if (returnStatus <= 200 && returnStatus < 300) {
                    AEZFetchLayoutResponseInterface response = responseEntity.getBody();

                    List<AEZLayout> receivedLayouts = response.getLayouts();

                    callback.success(receivedLayouts);

                } else {
                    callback.failure(returnStatus, null);
                }

            } catch (HttpStatusCodeException rsce) {
                Log.e(LOG_IDENTIFIER, rsce.toString());
                callback.failure(rsce.getStatusCode().value(), rsce.toString());

            } catch (RestClientException rce) {
                Log.e(LOG_IDENTIFIER, rce.toString());
                callback.failure(-1, rce.toString());
            }
        }
    });
    t.start();
}