Search in sources :

Example 1 with RestTemplate

use of org.springframework.web.client.RestTemplate in project spring-boot-admin by codecentric.

the class ApplicationRegistratorTest method setup.

@Before
public void setup() {
    restTemplate = mock(RestTemplate.class);
    adminProps = new AdminProperties();
    adminProps.setUrl(new String[] { "http://sba:8080", "http://sba2:8080" });
    ApplicationFactory factory = mock(ApplicationFactory.class);
    when(factory.createApplication()).thenReturn(Application.create("AppName").withManagementUrl("http://localhost:8080/mgmt").withHealthUrl("http://localhost:8080/health").withServiceUrl("http://localhost:8080").build());
    registrator = new ApplicationRegistrator(restTemplate, adminProps, factory);
    headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
}
Also used : AdminProperties(de.codecentric.boot.admin.client.config.AdminProperties) HttpHeaders(org.springframework.http.HttpHeaders) ApplicationRegistrator(de.codecentric.boot.admin.client.registration.ApplicationRegistrator) RestTemplate(org.springframework.web.client.RestTemplate) ApplicationFactory(de.codecentric.boot.admin.client.registration.ApplicationFactory) Before(org.junit.Before)

Example 2 with RestTemplate

use of org.springframework.web.client.RestTemplate in project ETSMobile-Android2 by ApplETS.

the class MonETSNotificationsRequest method loadDataFromNetwork.

@Override
public MonETSNotificationList loadDataFromNetwork() throws Exception {
    accountManager = AccountManager.get(context);
    Account[] accounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
    if (accounts.length > 0) {
        authToken = accountManager.peekAuthToken(accounts[0], Constants.AUTH_TOKEN_TYPE);
    }
    String url = context.getString(R.string.portail_api_base_url);
    if (onlyNewNotifs) {
        url += "/api/notification/dossier/1";
    } else {
        url += "/api/notification";
    }
    ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {

        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
            requestWrapper.getHeaders().set("Cookie", authToken);
            return execution.execute(requestWrapper, body);
        }
    };
    RestTemplate restTemplate = getRestTemplate();
    List<ClientHttpRequestInterceptor> list = new ArrayList<ClientHttpRequestInterceptor>();
    list.add(interceptor);
    restTemplate.setInterceptors(list);
    try {
        return restTemplate.getForObject(url, MonETSNotificationList.class);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().value() == 401) {
            if (accounts.length > 0) {
                accountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
                authToken = accountManager.blockingGetAuthToken(accounts[0], Constants.AUTH_TOKEN_TYPE, true);
                interceptor = new ClientHttpRequestInterceptor() {

                    @Override
                    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
                        HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
                        requestWrapper.getHeaders().set("Cookie", authToken);
                        return execution.execute(requestWrapper, body);
                    }
                };
                list.clear();
                list.add(interceptor);
                restTemplate.setInterceptors(list);
            }
        }
    } finally {
        return restTemplate.getForObject(url, MonETSNotificationList.class);
    }
}
Also used : HttpRequest(org.springframework.http.HttpRequest) Account(android.accounts.Account) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpRequestWrapper(org.springframework.http.client.support.HttpRequestWrapper) RestTemplate(org.springframework.web.client.RestTemplate) ArrayList(java.util.ArrayList) ClientHttpRequestExecution(org.springframework.http.client.ClientHttpRequestExecution) ClientHttpRequestInterceptor(org.springframework.http.client.ClientHttpRequestInterceptor)

Example 3 with RestTemplate

use of org.springframework.web.client.RestTemplate in project OpenClinica by OpenClinica.

the class XformMetaDataService method getMediaFileItemFromFormManager.

public FileItem getMediaFileItemFromFormManager(String fileLink, String crfOid, String formLayoutOid) {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    ResponseEntity<byte[]> response = restTemplate.exchange(fileLink, HttpMethod.GET, entity, byte[].class, "1");
    FileItem fileItem = null;
    if (response.getStatusCode() == HttpStatus.OK) {
        String fileName = "";
        FileOutputStream output = null;
        try {
            String disposition = response.getHeaders().get("Content-Disposition").get(0);
            fileName = disposition.replaceFirst("(?i)^.*filename=\"([^\"]+)\".*$", "$1");
            String dir = Utils.getCrfMediaFilePath(crfOid, formLayoutOid);
            if (!new File(dir).exists()) {
                new File(dir).mkdirs();
                logger.debug("Made the directory " + dir);
            }
            File file = new File(dir + fileName);
            output = new FileOutputStream(file);
            IOUtils.write(response.getBody(), output);
            fileItem = new DiskFileItem("media_file", response.getHeaders().get("Content-Type").get(0), false, fileName, 100000000, file);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return fileItem;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) HttpEntity(org.springframework.http.HttpEntity) FileOutputStream(java.io.FileOutputStream) RestTemplate(org.springframework.web.client.RestTemplate) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) IOException(java.io.IOException) File(java.io.File) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 4 with RestTemplate

use of org.springframework.web.client.RestTemplate in project OpenClinica by OpenClinica.

the class XformMetaDataService method executeIndividualCrf.

public void executeIndividualCrf(ExecuteIndividualCrfObject eicObject) {
    for (OCodmComplexTypeDefinitionFormLayoutDef formLayoutDef : eicObject.formLayoutDefs) {
        List<String> fileLinks = null;
        String vForm = "";
        RestTemplate rest = new RestTemplate();
        if (eicObject.form != null) {
            List<FormVersion> versions = eicObject.form.getVersions();
            for (FormVersion version : versions) {
                if (version.getName().equals(formLayoutDef.getOID())) {
                    fileLinks = version.getFileLinks();
                    for (String fileLink : fileLinks) {
                        if (fileLink.endsWith(VERSION)) {
                            vForm = rest.getForObject(fileLink, String.class);
                            break;
                        }
                    }
                    if (!eicObject.errors.hasErrors()) {
                        ObjectMapper mapper = new ObjectMapper();
                        TypeReference<List<XformGroup>> mapType = new TypeReference<List<XformGroup>>() {
                        };
                        List<XformGroup> jsonList = null;
                        try {
                            jsonList = mapper.readValue(vForm, mapType);
                        } catch (JsonParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (JsonMappingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        XformContainer xformContainer = new XformContainer();
                        xformContainer.setGroups(jsonList);
                        eicObject.setContainer(xformContainer);
                        if (eicObject.errors.hasErrors()) {
                            return;
                        }
                        // Save meta-data in database
                        saveFormMetadata(eicObject, version, eicObject.container, formLayoutDef, fileLinks);
                    }
                }
            }
        }
    }
}
Also used : OCodmComplexTypeDefinitionFormLayoutDef(org.openclinica.ns.odm_ext_v130.v31.OCodmComplexTypeDefinitionFormLayoutDef) XformGroup(org.akaza.openclinica.domain.xform.XformGroup) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) XformContainer(org.akaza.openclinica.domain.xform.XformContainer) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) RestTemplate(org.springframework.web.client.RestTemplate) List(java.util.List) ArrayList(java.util.ArrayList) TypeReference(com.fasterxml.jackson.core.type.TypeReference) FormVersion(org.akaza.openclinica.service.dto.FormVersion) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with RestTemplate

use of org.springframework.web.client.RestTemplate in project OpenClinica by OpenClinica.

the class EnketoAPI method getURL.

private EnketoURLResponse getURL(URL url, String crfOID) {
    try {
        String userPasswdCombo = new String(Base64.encodeBase64((token + ":").getBytes()));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Basic " + userPasswdCombo);
        headers.add("Accept-Charset", "UTF-8");
        EnketoURLRequest body = new EnketoURLRequest(ocURL, crfOID);
        HttpEntity<EnketoURLRequest> request = new HttpEntity<EnketoURLRequest>(body, headers);
        RestTemplate rest = new RestTemplate();
        ResponseEntity<EnketoURLResponse> response = rest.postForEntity(url.toString(), request, EnketoURLResponse.class);
        if (response != null)
            return response.getBody();
        else
            return null;
    } catch (Exception e) {
        logger.error(e.getMessage());
        logger.error(ExceptionUtils.getStackTrace(e));
    }
    return null;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) RestTemplate(org.springframework.web.client.RestTemplate)

Aggregations

RestTemplate (org.springframework.web.client.RestTemplate)519 Test (org.junit.Test)135 Test (org.junit.jupiter.api.Test)78 HttpHeaders (org.springframework.http.HttpHeaders)77 HttpEntity (org.springframework.http.HttpEntity)76 URI (java.net.URI)73 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)45 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)44 HashMap (java.util.HashMap)42 ArrayList (java.util.ArrayList)40 IOException (java.io.IOException)36 Bean (org.springframework.context.annotation.Bean)35 MappingJackson2HttpMessageConverter (org.springframework.http.converter.json.MappingJackson2HttpMessageConverter)32 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)29 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)27 StringHttpMessageConverter (org.springframework.http.converter.StringHttpMessageConverter)27 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)24 RestTemplateBuilder (org.springframework.boot.web.client.RestTemplateBuilder)22 ClientHttpRequestFactory (org.springframework.http.client.ClientHttpRequestFactory)22 SimpleClientHttpRequestFactory (org.springframework.http.client.SimpleClientHttpRequestFactory)22