Example usage for java.net URISyntaxException printStackTrace

List of usage examples for java.net URISyntaxException printStackTrace

Introduction

In this page you can find the example usage for java.net URISyntaxException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:elaborate.editor.publish.PublishTask.java

private void prepareDirectories() {
    rootDir = Files.createTempDir();
    Log.info("directory={}", rootDir);
    distDir = new File(rootDir, "dist");
    URL resource = Thread.currentThread().getContextClassLoader().getResource("publication");
    try {/*  ww w  . j  a  va2s .  c  o  m*/
        File publicationResourceDir = new File(resource.toURI());
        FileUtils.copyDirectory(publicationResourceDir, distDir);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    jsonDir = new File(distDir, "data");
    jsonDir.mkdir();
}

From source file:vitro.vgw.wsiadapter.TCSWSIAdapter.java

void doRequest(String method, String strUri) {
    URI uri;//from w  ww  . j av a2s  .co  m
    try {
        uri = new URI(strUri);
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return;
    }
    doRequest(method, uri);
}

From source file:me.trashout.fragment.TrashDetailFragment.java

/**
 * Setup trash data//from   ww  w.j  a v a 2  s .c  o  m
 *
 * @param trash
 */
private void setupTrashData(Trash trash) {
    mImages = getFullScreenImagesFromTrash(trash);

    trashDetailStateName.setText(trash.getStatus().getStringResId());
    if (trash.isUpdateNeeded()) {
        trashDetailStateIcon.setImageResource(R.drawable.ic_trash_status_unknown);
        trashDetailStateName.setText(R.string.trash_updateNeeded);
    } else if (Constants.TrashStatus.CLEANED.equals(trash.getStatus())) {
        trashDetailStateIcon.setImageResource(R.drawable.ic_trash_activity_cleaned);
    } else if (Constants.TrashStatus.STILL_HERE.equals(trash.getStatus())
            && (trash.getUpdateHistory() == null || trash.getUpdateHistory().isEmpty())) {
        trashDetailStateIcon.setImageResource(R.drawable.ic_trash_activity_reported);
    } else {
        trashDetailStateIcon.setImageResource(R.drawable.ic_trash_activity_updated);
    }

    trashDetailStateTime.setText(DateTimeUtils.getRoundedTimeAgo(getContext(), trash.getLastChangeDate()));

    trashDetailSizeIcon.setImageResource(trash.getSize().getIconResId());
    trashDetailSizeText.setText(trash.getSize().getStringResId());

    trashDetailTypeContainerFlexbox.removeAllViews();
    for (Constants.TrashType trashType : trash.getTypes()) {
        if (trashType != null) {
            FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.flexBasisPercent = 0.5f;
            trashDetailTypeContainerFlexbox.addView(getTrashTypeView(trashType), layoutParams);
        }
    }

    trashDetailHistoryContainer.removeAllViews();
    trashDetailHistoryContainer
            .addView(getTrashUpdateHistoryView(UpdateHistory.createLastUpdateHistoryFromTrash(trash),
                    (trash.getUpdateHistory() == null || trash.getUpdateHistory().isEmpty())));
    int updateHistoryOrder = 0;

    if (trash.getUpdateHistory() != null && !trash.getUpdateHistory().isEmpty()) {
        ArrayList<UpdateHistory> preparedUpdateHistory = prepareUpdateHistory(trash.getUpdateHistory());

        for (UpdateHistory updateHistory : preparedUpdateHistory) {

            if (trashDetailHistoryContainer.getChildCount() > 0)
                trashDetailHistoryContainer.addView(ViewUtils.getDividerView(getContext()));

            trashDetailHistoryContainer.addView(getTrashUpdateHistoryView(updateHistory,
                    updateHistoryOrder == preparedUpdateHistory.size() - 1));
            updateHistoryOrder++;
        }
    }

    trashDetailPhotoCount.setText(String.valueOf(mImages != null ? mImages.size() : 0));

    String accessibilityText;
    if (trash.getAccessibility() != null && !TextUtils
            .isEmpty(accessibilityText = trash.getAccessibility().getAccessibilityString(getContext()))) {
        trashDetailAccessibilityText.setText(accessibilityText);
    } else {
        trashDetailAccessibility.setVisibility(View.GONE);
        trashDetailAccessibilityText.setVisibility(View.GONE);
    }

    if (!TextUtils.isEmpty(trash.getNote())) {
        trashDetailAdditionalInformation.setVisibility(View.VISIBLE);
        trashDetailAdditionalInformationText.setVisibility(View.VISIBLE);

        trashDetailAdditionalInformationText.setText(trash.getNote());
    } else {
        trashDetailAdditionalInformation.setVisibility(View.GONE);
        trashDetailAdditionalInformationText.setVisibility(View.GONE);
    }

    if (trash.getGps() != null && trash.getGps().getArea() != null
            && !TextUtils.isEmpty(trash.getGps().getArea().getFormatedLocation())) {
        trashDetailPlace.setText(trash.getGps().getArea().getFormatedLocation());
    } else {
        Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
        new GeocoderTask(geocoder, trash.getGps().getLat(), trash.getGps().getLng(),
                new GeocoderTask.Callback() {
                    @Override
                    public void onAddressComplete(GeocoderTask.GeocoderResult geocoderResult) {
                        if (!TextUtils.isEmpty(geocoderResult.getFormattedAddress())) {
                            trashDetailPlace.setText(geocoderResult.getFormattedAddress());
                        } else {
                            trashDetailPlace.setVisibility(View.GONE);
                        }
                    }
                }).execute();
    }

    trashDetailPosition.setText(
            PositionUtils.getFormattedLocation(getContext(), trash.getGps().getLat(), trash.getGps().getLng()));

    trashDetailAccuracyLocationText
            .setText(String.format(getString(R.string.accuracy_formatter), trash.getGps().getAccuracy()));
    if (lastPosition != null)
        trashDetailLocationApproximately
                .setText(
                        String.format(getString(R.string.specific_distance_away_formatter),
                                lastPosition != null ? PositionUtils.getFormattedComputeDistance(getContext(),
                                        lastPosition, trash.getPosition()) : "?",
                                getString(R.string.global_distanceAttribute_away)));

    String mapUrl = PositionUtils.getStaticMapUrl(getActivity(), trash.getGps().getLat(),
            trash.getGps().getLng());
    try {
        URI mapUri = new URI(mapUrl.replace("|", "%7c"));
        Log.d(TAG, "setupTrashData: mapUrl = " + String.valueOf(mapUri.toURL()));
        GlideApp.with(this).load(String.valueOf(mapUri.toURL())).centerCrop().into(trashDetailMap);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    if (trash.getImages() != null && !trash.getImages().isEmpty()
            && ViewUtils.checkImageStorage(trash.getImages().get(0))) {
        StorageReference mImageRef = FirebaseStorage.getInstance()
                .getReferenceFromUrl(trash.getImages().get(0).getFullStorageLocation());
        GlideApp.with(this).load(mImageRef).centerCrop().transition(DrawableTransitionOptions.withCrossFade())
                .placeholder(R.drawable.ic_image_placeholder_rectangle).into(trashDetailImage);
    }

    trashDetailEventContainer.removeAllViews();
    if (trash.getEvents() != null && !trash.getEvents().isEmpty()) {
        trashDetailEventCardView.setVisibility(View.VISIBLE);
        trashDetailNoEvent.setVisibility(View.GONE);

        for (Event event : trash.getEvents()) {
            if (trashDetailEventContainer.getChildCount() > 0)
                trashDetailEventContainer.addView(ViewUtils.getDividerView(getContext()));

            trashDetailEventContainer.addView(getTrashEventView(event));
        }
    } else {
        trashDetailEventCardView.setVisibility(View.GONE);
        trashDetailNoEvent.setVisibility(View.VISIBLE);
    }
}

From source file:org.fusesource.cloudmix.agent.InstallerAgent.java

public AgentDetails updateAgentDetails() {

    // TODO why would we flush the agent details each time???
    // agentDetails = null;
    agentDetails = getAgentDetails();// w  w w  .j av  a  2  s .  c o m
    loadPersistedAgentDetails();
    populateInitialAgentDetails(agentDetails);

    try {
        getClient().updateAgentDetails(getAgentId(), getAgentDetails());
    } catch (URISyntaxException e) {
        LOG.info("Problem updating agent information ", e);
        e.printStackTrace();
    }
    return agentDetails;
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public String getOauth2UserEmail() throws IllegalArgumentException {

    // get the auth code...
    Context ctxt = getStateContext(ctxtKey);
    String code = (String) ctxt.getContext("code");
    {//from   w  w  w .ja  va2s .c  o m
        // convert the auth code into an auth token
        URI nakedUri;
        try {
            nakedUri = new URI(tokenUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpPost httppost = new HttpPost(nakedUri);
        logger.info(httppost.getURI().toString());

        // THESE ARE POST BODY ARGS...    
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        qparams.add(new BasicNameValuePair("client_id", CLIENT_ID));
        qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
        qparams.add(new BasicNameValuePair("code", code));
        qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl()));
        UrlEncodedFormEntity postentity;
        try {
            postentity = new UrlEncodedFormEntity(qparams, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            throw new IllegalArgumentException("Unexpected");
        }

        httppost.setEntity(postentity);

        HttpResponse response = null;
        try {
            response = client.execute(httppost, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase()
                        + " status code: " + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    // stuff the map in the Context...
                    for (Map.Entry<String, Object> e : userData.entrySet()) {
                        ctxt.putContext(e.getKey(), e.getValue());
                    }
                } else {
                    logger.error("unexpected body");
                    return "Error with Oauth2 token request - missing body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    // OK if we got here, we have a valid token.  
    // Issue the request...
    String email = null;
    {
        URI nakedUri;
        try {
            nakedUri = new URI(userInfoUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token")));
        URI uri;
        try {
            uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(),
                    nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpGet httpget = new HttpGet(uri);
        logger.info(httpget.getURI().toString());

        HttpResponse response = null;
        try {
            response = client.execute(httpget, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error - reason: " + response.getStatusLine().getReasonPhrase() + " status code: "
                        + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);

                    email = (String) userData.get("email");
                } else {
                    logger.error("unexpected body");
                    return "Error - missing body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    return email;
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public String obtainOauth2Data(String destinationUrl) throws IllegalArgumentException {

    // get the auth code...
    Context ctxt = getStateContext(ctxtKey);
    String code = (String) ctxt.getContext("code");
    {/*  w  ww.ja  v  a  2s.  c o m*/
        // convert the auth code into an auth token
        URI nakedUri;
        try {
            nakedUri = new URI(tokenUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpPost httppost = new HttpPost(nakedUri);
        logger.info(httppost.getURI().toString());

        // THESE ARE POST BODY ARGS...    
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        qparams.add(new BasicNameValuePair("client_id", CLIENT_ID));
        qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
        qparams.add(new BasicNameValuePair("code", code));
        qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl()));
        UrlEncodedFormEntity postentity;
        try {
            postentity = new UrlEncodedFormEntity(qparams, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            throw new IllegalArgumentException("Unexpected");
        }

        httppost.setEntity(postentity);

        HttpResponse response = null;
        try {
            response = client.execute(httppost, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase()
                        + " status code: " + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    // stuff the map in the Context...
                    for (Map.Entry<String, Object> e : userData.entrySet()) {
                        ctxt.putContext(e.getKey(), e.getValue());
                    }
                } else {
                    logger.error("unexpected body");
                    return "Error with Oauth2 token request - unexpected body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    // OK if we got here, we have a valid token.  
    // Issue the request...
    {
        URI nakedUri;
        try {
            nakedUri = new URI(destinationUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token")));
        URI uri;
        try {
            uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(),
                    nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpGet httpget = new HttpGet(uri);
        logger.info(httpget.getURI().toString());

        HttpResponse response = null;
        try {
            response = client.execute(httpget, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error";
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    String contentType = entity.getContentType().getValue();
                    if (contentType.toLowerCase().contains("xml")) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                        StringBuilder b = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            b.append(line);
                        }
                        String value = b.toString();
                        return value;
                    } else {
                        logger.error("unexpected body");
                        return "Error";
                    }
                } else {
                    logger.error("unexpected missing body");
                    return "Error";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }
}

From source file:com.cloud.network.resource.NccHttpCode.java

private String queryAsyncJob(String jobId) throws ExecutionException {
    String result = null;//from ww w .j av a2 s .  c om
    try {
        URI agentUri = null;
        agentUri = new URI("https", null, _ip, DEFAULT_PORT, "/admin/v1/journalcontexts/" + jobId, null, null);

        org.json.JSONObject jsonBody = new JSONObject();

        long startTick = System.currentTimeMillis();
        while (System.currentTimeMillis() - startTick < _nccCmdTimeout) {
            result = getHttpRequest(jsonBody.toString(), agentUri, _sessionid);
            JSONObject response = new JSONObject(result);
            if (response != null) {
                s_logger.debug("Job Status result for [" + jobId + "]:: " + result + " Tick and currentTime :"
                        + System.currentTimeMillis() + " -" + startTick + "job cmd timeout :" + _nccCmdTimeout);
                String status = response.getJSONObject("journalcontext").getString("status").toUpperCase();
                String message = response.getJSONObject("journalcontext").getString("message");
                s_logger.debug("Job Status Progress Status [" + jobId + "]:: " + status);
                switch (status) {
                case "FINISHED":
                    return status;
                case "IN PROGRESS":
                    break;
                case "ERROR, ROLLBACK IN PROGRESS":
                    break;
                case "ERROR, ROLLBACK COMPLETED":
                    throw new ExecutionException("ERROR, ROLLBACK COMPLETED " + message);
                case "ERROR, ROLLBACK FAILED":
                    throw new ExecutionException("ERROR, ROLLBACK FAILED " + message);
                }
            }
        }

    } catch (URISyntaxException e) {
        String errMsg = "Could not generate URI for NetScaler ControlCenter";
        s_logger.error(errMsg, e);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

protected HttpUriRequest getHttpUriRequest(String requestMethod, String url) throws IOException {

    HttpUriRequest request = null;/*  w w w .j a v a  2  s.c  o m*/

    try {
        URI uri = new URI(url);
        // GET or POST
        if (requestMethod.equalsIgnoreCase("get")) {
            request = new HttpGet(uri);
        } else {
            request = new HttpPost(uri);
        }

        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setHeader("Content-Language", "en-US");
        request.setHeader("Authorization", "Bearer " + sessionToken);

        request.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        request.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        request.setHeader("Expires", "0"); // Proxies.

    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    return request;
}

From source file:br.gov.jfrj.siga.gc.gsa.GcInformacaoAdaptor.java

/** Gives the bytes of a document referenced with id. */
public void getDocContent(Request req, Response resp) throws IOException {
    DocId id = req.getDocId();//w w  w  . j  a v a 2  s. c om
    log.fine("obtendo id = " + id);
    long primaryKey;
    try {
        primaryKey = Long.parseLong(id.getUniqueId());
    } catch (NumberFormatException nfe) {
        resp.respondNotFound();
        return;
    }

    Connection conn = null;
    PreparedStatement stmt = null;
    String query = "select ACRONIMO_ORGAO_USU, ANO, NUMERO, NOME_TIPO_INFORMACAO, TITULO, NOME_ACESSO, HIS_DT_INI, CONTEUDO_TIPO, CONTEUDO, "
            + "(select nome_pessoa from corporativo.dp_pessoa pes where pes.id_pessoa = inf.id_pessoa_titular) SUBSCRITOR, "
            + "(select sigla_lotacao from corporativo.dp_lotacao lot where lot.id_lotacao = inf.id_lotacao_titular) SUBSCRITOR_LOTACAO, "
            + "(select nome_pessoa from corporativo.dp_pessoa pes, corporativo.cp_identidade idn where idn.id_pessoa = pes.id_pessoa and idn.id_identidade = inf.his_idc_ini) CADASTRANTE, "
            + "(select sigla_lotacao from corporativo.dp_lotacao lot, corporativo.dp_pessoa pes, corporativo.cp_identidade idn where lot.id_lotacao = pes.id_lotacao and idn.id_pessoa = pes.id_pessoa and idn.id_identidade = inf.his_idc_ini) CADASTRANTE_LOTACAO "
            + "from sigagc.gc_informacao inf, sigagc.gc_arquivo arq, corporativo.cp_orgao_usuario ou, sigagc.gc_tipo_informacao tp, sigagc.gc_acesso ac  "
            + "where inf.id_arquivo = arq.id_conteudo and inf.id_orgao_usuario = ou.id_orgao_usu and inf.id_tipo_informacao = tp.id_tipo_informacao and inf.id_acesso = ac.id_acesso and numero is not null and ac.id_acesso = 1 "
            + "and inf.id_informacao = ?";
    try {
        conn = getConnection();
        stmt = conn.prepareStatement(query);
        stmt.setLong(1, primaryKey);
        ResultSet rs = stmt.executeQuery();
        if (!rs.next()) {
            resp.respondNotFound();
            return;
        }

        // Add Metadata
        //
        addMetadata(resp, "orgao", rs.getString("ACRONIMO_ORGAO_USU"));
        String codigo = rs.getString("ACRONIMO_ORGAO_USU") + "-GC-" + rs.getInt("ANO") + "/"
                + Long.toString(rs.getLong("NUMERO") + 100000).substring(1);
        addMetadata(resp, "codigo", codigo);
        addMetadata(resp, "origem", "Conhecimento");
        addMetadata(resp, "especie", rs.getString("NOME_TIPO_INFORMACAO"));
        addMetadata(resp, "descricao", rs.getString("TITULO"));
        addMetadata(resp, "acesso", rs.getString("NOME_ACESSO"));
        addMetadata(resp, "data", getDtYYYYMMDD(rs.getDate("HIS_DT_INI")));
        addMetadata(resp, "subscritor_lotacao", rs.getString("SUBSCRITOR_LOTACAO"));
        addMetadata(resp, "subscritor", rs.getString("SUBSCRITOR"));
        addMetadata(resp, "cadastrante_lotacao", rs.getString("CADASTRANTE_LOTACAO"));
        addMetadata(resp, "cadastrante", rs.getString("CADASTRANTE"));

        // Add Acl
        //
        // List<GroupPrincipal> groups = new ArrayList<>();
        // groups.add(new GroupPrincipal(s));
        // Acl acl = new Acl.Builder().setPermitGroups(groups)
        // .setEverythingCaseInsensitive().build();
        // resp.setAcl(acl);

        // Add Atributos essenciais
        //
        resp.setCrawlOnce(false);
        resp.setLastModified(rs.getDate("HIS_DT_INI"));
        try {
            String numero = Long.toString(rs.getLong("NUMERO") + 100000).substring(1);
            resp.setDisplayUrl(
                    new URI(permalink + rs.getString("ACRONIMO_ORGAO_USU") + "GC" + rs.getInt("ANO") + numero));
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }

        // Add Conteudo
        //
        if ("text/html".equals(rs.getString("CONTEUDO_TIPO"))) {
            String html = new String(rs.getBytes("CONTEUDO"), "UTF-8");
            if (html != null) {
                resp.setContentType("text/html");
                resp.getOutputStream().write(html.getBytes());
                return;
            }
        } else {
            resp.respondNotFound();
            return;
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}