Example usage for org.springframework.http MediaType MediaType

List of usage examples for org.springframework.http MediaType MediaType

Introduction

In this page you can find the example usage for org.springframework.http MediaType MediaType.

Prototype

public MediaType(MediaType other, @Nullable Map<String, String> parameters) 

Source Link

Document

Copy-constructor that copies the type and subtype of the given MediaType , and allows for different parameters.

Usage

From source file:com.playhaven.android.req.PlayHavenRequest.java

protected HttpHeaders getHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(new MediaType("application", "json")));
    headers.setUserAgent(UserAgent.USER_AGENT);
    return headers;
}

From source file:demo.SourceHttpMessageConverter.java

/**
 * Sets the {@link #setSupportedMediaTypes(java.util.List) supportedMediaTypes}
 * to {@code text/xml} and {@code application/xml}, and {@code application/*-xml}.
 *//*from  www.  j  ava  2  s  .  co m*/
public SourceHttpMessageConverter() {
    super(MediaType.APPLICATION_XML, MediaType.TEXT_XML, new MediaType("application", "*+xml"));
}

From source file:org.darwinathome.server.controller.WebstartController.java

@RequestMapping("/{user}/{pass}/tetragotchi.jnlp")
public ResponseEntity<String> jnlpFile(HttpServletRequest request, @PathVariable String user,
        @PathVariable String pass) throws IOException {
    String from = String.format("%s/%s/tetragotchi.jnlp", user, pass);
    String base = request.getRequestURL().toString().replace(from, "");
    String realFileName = servletContext.getRealPath("tetragotchi.jnlp");
    BufferedReader in = new BufferedReader(new FileReader(realFileName));
    StringBuilder out = new StringBuilder();
    String line;// w  w  w.j a v a2  s .  c  o  m
    while ((line = in.readLine()) != null) {
        if (line.contains("@@")) {
            line = line.replace("@@BASE@@", base);
            line = line.replace("@@USER@@", user);
            line = line.replace("@@PASS@@", pass);
        }
        out.append(line).append('\n');
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(new MediaType("application", "java-jnlp-file"));
    return new ResponseEntity<String>(out.toString(), headers, HttpStatus.OK);
}

From source file:cz.cvut.via.androidrestskeleton.SkeletonActivity.java

/** Called with the activity is first created. */
@Override/*from  w w  w .  j a  v a  2 s  . c o  m*/
public void onCreate(Bundle savedInstanceState) {

    // DISABLE policy not allowing network connections from main application thread
    // these calls normally HAVE to be done from worker threads/asynchronous threads/services ..
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    super.onCreate(savedInstanceState);

    // Inflate our UI from its XML layout description.
    setContentView(R.layout.skeleton_activity);

    requestView = (CheckedTextView) findViewById(R.id.checkedTextRequest);
    responseView = (CheckedTextView) findViewById(R.id.checkedTextResponse);

    // Hook up button presses to the appropriate event handler.
    ((Button) findViewById(R.id.create)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            PostalAddress address = new PostalAddress();
            address.setCity("new city");
            address.setCountry("new country");
            address.setStreet("new street");
            address.setZipCode("zipcode");

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<PostalAddress> requestEntity = new HttpEntity<PostalAddress>(address, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/";

            new AsyncPOST<PostalAddress>(requestEntity) {
                protected void onPostExecute(Response<String> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders().toString() + "\n\n"
                            + request.getBody().toJSONString());
                    responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                            + result.getResponseEntity().getHeaders().toString());
                    lastCreatedLocation = result.getResponseEntity().getHeaders().getLocation().getPath();
                };
            }.execute(url);
        }
    });

    // Hook up button presses to the appropriate event handler.
    ((Button) findViewById(R.id.list)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            RestTemplate restTemplate = new RestTemplate();

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/";

            new AsyncGET<PostalAddress[]>(requestEntity, PostalAddress[].class) {
                protected void onPostExecute(Response<PostalAddress[]> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        StringBuilder text = new StringBuilder();
                        for (PostalAddress address : result.getResponseEntity().getBody()) {
                            text.append(address.toJSONString() + "\n\n");
                        }
                        //+ requestEntity.getBody().toJSONString());
                        responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                                + result.getResponseEntity().getHeaders().toString() + "\n\n" + text);
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.update)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            PostalAddress address = new PostalAddress();
            address.setCity("updated city");
            address.setCountry("new country");
            address.setStreet("new street");
            address.setZipCode("zipcode");

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<PostalAddress> requestEntity = new HttpEntity<PostalAddress>(address, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + lastCreatedLocation;

            new AsyncPUT<PostalAddress>(requestEntity) {
                protected void onPostExecute(Response<Object> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders().toString() + "\n\n"
                            + request.getBody().toJSONString());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        responseView.setText("PUT method in Spring does not support return values..");
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.delete)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + lastCreatedLocation;

            // get reponse
            new AsyncDELETE() {
                protected void onPostExecute(Response<Object> result) {
                    requestView.setText(url);

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        responseView.setText("PUT method in Spring does not support return values..");
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.query)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            HashMap<String, String> query = new HashMap<String, String>();
            query.put("setFilter", "street == streetParam");
            query.put("declareParameters", "String streetParam");
            query.put("setOrdering", "street desc");

            HashMap<String, String> parameters = new HashMap<String, String>();
            parameters.put("streetParam", "new street");

            RESTQuery q = new RESTQuery();
            q.setQuery(query);
            q.setParameters(parameters);

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<RESTQuery> requestEntity = new HttpEntity<RESTQuery>(q, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/q";

            // get reponse
            new AsyncPOST_QUERY<RESTQuery, PostalAddress[]>(requestEntity, PostalAddress[].class) {
                @Override
                protected void onPostExecute(Response<PostalAddress[]> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {

                        StringBuilder text = new StringBuilder();
                        for (PostalAddress address : result.getResponseEntity().getBody()) {
                            text.append(address.toJSONString() + "\n\n");
                        }

                        responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                                + result.getResponseEntity().getHeaders().toString() + "\n\n" + text);
                    }
                }
            }.execute(url);
        }
    });

}

From source file:com.btmatthews.leabharlann.view.FileContentMessageConverter.java

/**
 * Set the HTTP headers on the servlet response and stream the file contents to the servlet response's output stream.
 *
 * @param fileContent   Describes the file content.
 * @param outputMessage Used to access the servlet response headers and output stream.
 * @throws IOException                     If there was an error streaming the file content.
 * @throws HttpMessageNotWritableException If there was problem retrieving the file content from the Java Content Repository.
 *//*from   w  ww . j  ava  2s.  c o  m*/
@Override
protected void writeInternal(final FileContent fileContent, final HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    try {
        jcrAccessor.withNodeId(fileContent.getWorkspace(), fileContent.getId(), new NodeCallback() {
            @Override
            public Object doInSessionWithNode(Session session, Node node) throws Exception {
                final Node resourceNode = node.getNode(Node.JCR_CONTENT);
                final String mimeType = jcrAccessor.getStringProperty(resourceNode, Property.JCR_MIMETYPE);
                final Calendar lastModified = jcrAccessor.getCalendarProperty(resourceNode,
                        Property.JCR_LAST_MODIFIED);
                final Binary data = jcrAccessor.getBinaryProperty(resourceNode, Property.JCR_DATA);
                if (jcrAccessor.hasProperty(resourceNode, Property.JCR_ENCODING)) {
                    final String encoding = jcrAccessor.getStringProperty(resourceNode, Property.JCR_ENCODING);
                    outputMessage.getHeaders().setContentType(new MediaType(MediaType.valueOf(mimeType),
                            Collections.singletonMap("charset", encoding)));
                } else {
                    outputMessage.getHeaders().setContentType(MediaType.valueOf(mimeType));
                }
                outputMessage.getHeaders().setContentLength(data.getSize());
                if (lastModified != null) {
                    outputMessage.getHeaders().setLastModified(lastModified.getTimeInMillis());
                }
                outputMessage.getHeaders().set("Content-Disposition", "attachment;filename=" + node.getName());
                IOUtils.copy(data.getStream(), outputMessage.getBody());
                return null;
            }
        });
    } catch (final RepositoryAccessException e) {
        throw new HttpMessageNotWritableException(e.getLocalizedMessage());
    }
}

From source file:org.openmrs.module.spike1.web.controller.Spike1ManageController.java

@RequestMapping(value = "/module/spike1/appcache.json", method = RequestMethod.GET)
public ResponseEntity<String> getAppCache() throws IOException {
    log.fatal("Creating application cache");

    AppFrameworkService appFrameworkService = Context.getService(AppFrameworkService.class);
    List<AppDescriptor> allApps = appFrameworkService.getAllApps();

    String homepageUrl;/*from   ww w . j  av a  2s  .co m*/
    String manifestString = "CACHE MANIFEST\n";
    for (AppDescriptor appDescriptor : allApps) {
        homepageUrl = appDescriptor.getHomepageUrl();
        String homePageDirectory = homepageUrl.substring(0, homepageUrl.lastIndexOf('/') + 1);
        homepageUrl = homePageDirectory + "manifest.appcache";
        GetMethod getMethod = new GetMethod("http://localhost:8080/" + homepageUrl);
        new HttpClient().executeMethod(getMethod);
        byte[] responseBodyByteArray = getMethod.getResponseBody();
        String res = new String(responseBodyByteArray);
        String[] cacheLines = res.split("\n");
        for (String cache : cacheLines) {
            if (cache.startsWith("CACHE"))
                continue;
            if (StringUtils.isBlank(cache))
                continue;
            if (cache.startsWith("#")) {
                manifestString += cache + "\n";
                continue;
            }
            manifestString += "http://localhost:8080/" + homePageDirectory + cache + "\n";
        }
        manifestString += "\n";
    }

    // This line is only for dev mode to ensure that the files
    // are fetched again
    manifestString += "#" + getTimestampString(new Date());

    log.fatal("Manifest String : ");
    log.fatal("==========================================");
    log.fatal(manifestString);
    log.fatal("==========================================");

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(new MediaType("text", "cache-manifest"));
    //        responseHeaders.set("Content-Type", "text/cache-manifest");
    return new ResponseEntity<String>(manifestString, responseHeaders, HttpStatus.OK);

    //        response.setContentType("text/cache-manifest");
    //        return manifestString;
}

From source file:com.cemeterylistingswebtest.test.rest.CemeteryControllerTest.java

private HttpHeaders getContentType() {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(new MediaType("application", "json"));
    return requestHeaders;
}

From source file:com.onedrive.api.internal.MultipartRelatedHttpMessageConverter.java

private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage)
        throws IOException {
    final byte[] boundary = generateMultipartBoundary();
    Map<String, String> parameters = Collections.singletonMap("boundary", new String(boundary, "US-ASCII"));

    MediaType contentType = new MediaType(MULTIPART_RELATED_MEDIA_TYPE, parameters);
    HttpHeaders headers = outputMessage.getHeaders();
    headers.setContentType(contentType);

    if (outputMessage instanceof StreamingHttpOutputMessage) {
        StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
        streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
            public void writeTo(OutputStream outputStream) throws IOException {
                writeParts(outputStream, parts, boundary);
                writeEnd(outputStream, boundary);
            }//  w  w w . j  av a 2 s . co m
        });
    } else {
        writeParts(outputMessage.getBody(), parts, boundary);
        writeEnd(outputMessage.getBody(), boundary);
    }
}

From source file:us.polygon4.izzymongo.controller.AppController.java

/**
 * Exports database schema as FreeMind map
 * /* www .  j  a v a 2 s. co m*/
* @param fileName database name
* @return fileName + ".mm"
* @throws Exception
*/
@RequestMapping(value = "/export/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createExport(@PathVariable("fileName") String fileName) throws Exception {
    byte[] documentBody = null;
    documentBody = service.getDbSchema(fileName);
    fileName = fileName + ".mm";
    HttpHeaders header = new HttpHeaders();
    header.setContentType(new MediaType("application", "xml"));
    header.set("Content-Disposition", "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(documentBody.length);

    return new HttpEntity<byte[]>(documentBody, header);
}

From source file:de.qucosa.webapi.v1.DocumentResourceTest.java

@Test
public void postWithoutURNParametersPossibleWhenContentHasUrnNode() throws Exception {
    mockMvc.perform(post(DOCUMENT_POST_URL_WITHOUT_PARAMS)
            .accept(new MediaType("application", "vnd.slub.qucosa-v1+xml"))
            .contentType(new MediaType("application", "vnd.slub.qucosa-v1+xml"))
            .content("<Opus version=\"2.0\">" + "<Opus_Document>" + "<DocumentId>4711</DocumentId>"
                    + "<PersonAuthor>" + "<LastName>Shakespear</LastName>" + "<FirstName>William</FirstName>"
                    + "</PersonAuthor>" + "<TitleMain><Value>Macbeth</Value></TitleMain>"
                    + "<IdentifierUrn><Value>urn:nbn:foo-4711</Value></IdentifierUrn>" + "</Opus_Document>"
                    + "</Opus>"))
            .andExpect(status().isCreated());
}