Example usage for java.io Closeable close

List of usage examples for java.io Closeable close

Introduction

In this page you can find the example usage for java.io Closeable close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:org.eclipse.che.vfs.impl.fs.FSMountPoint.java

private void closeQuietly(Closeable closeable) {
    if (closeable != null) {
        try {// w  w  w. j a v a 2 s  . c o m
            closeable.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:edu.stanford.muse.util.Util.java

public static void close(Closeable resource) {
    if (resource != null) {
        try {/*from w w w .  j a va  2 s  .c  o  m*/
            resource.close();
        } catch (IOException e) {
            // Do your thing with the exception. Print it, log it or mail
            // it.
            e.printStackTrace();
        }
    }
}

From source file:com.android.bluetooth.map.BluetoothMapContent.java

private static void close(Closeable c) {
    try {//from ww  w  . j  a  v a2s. co  m
        if (c != null)
            c.close();
    } catch (IOException e) {
    }
}

From source file:ca.uhn.fhir.rest.server.RestfulServer.java

protected void handleRequest(RequestTypeEnum theRequestType, HttpServletRequest theRequest,
        HttpServletResponse theResponse) throws ServletException, IOException {
    String fhirServerBase = null;
    ServletRequestDetails requestDetails = new ServletRequestDetails();
    requestDetails.setServer(this);
    requestDetails.setRequestType(theRequestType);
    requestDetails.setServletRequest(theRequest);
    requestDetails.setServletResponse(theResponse);

    theRequest.setAttribute(SERVLET_CONTEXT_ATTRIBUTE, getServletContext());

    try {//from w ww  . j  a  va 2s.  co m

        /* ***********************************
         * Parse out the request parameters
         * ***********************************/

        String requestFullPath = StringUtils.defaultString(theRequest.getRequestURI());
        String servletPath = StringUtils.defaultString(theRequest.getServletPath());
        StringBuffer requestUrl = theRequest.getRequestURL();
        String servletContextPath = IncomingRequestAddressStrategy.determineServletContextPath(theRequest,
                this);

        /*
         * Just for debugging..
         */
        if (ourLog.isTraceEnabled()) {
            ourLog.trace("Request FullPath: {}", requestFullPath);
            ourLog.trace("Servlet Path: {}", servletPath);
            ourLog.trace("Request Url: {}", requestUrl);
            ourLog.trace("Context Path: {}", servletContextPath);
        }

        String completeUrl;
        Map<String, String[]> params = null;
        if (StringUtils.isNotBlank(theRequest.getQueryString())) {
            completeUrl = requestUrl + "?" + theRequest.getQueryString();
            /*
             * By default, we manually parse the request params (the URL params, or the body for
             * POST form queries) since Java containers can't be trusted to use UTF-8 encoding
             * when parsing. Specifically Tomcat 7 and Glassfish 4.0 use 8859-1 for some dumb
             * reason.... grr.....
             */
            if (isIgnoreServerParsedRequestParameters()) {
                String contentType = theRequest.getHeader(Constants.HEADER_CONTENT_TYPE);
                if (theRequestType == RequestTypeEnum.POST && isNotBlank(contentType)
                        && contentType.startsWith(Constants.CT_X_FORM_URLENCODED)) {
                    String requestBody = new String(requestDetails.loadRequestContents(),
                            Constants.CHARSET_UTF8);
                    params = UrlUtil.parseQueryStrings(theRequest.getQueryString(), requestBody);
                } else if (theRequestType == RequestTypeEnum.GET) {
                    params = UrlUtil.parseQueryString(theRequest.getQueryString());
                }
            }
        } else {
            completeUrl = requestUrl.toString();
        }

        if (params == null) {
            params = new HashMap<String, String[]>(theRequest.getParameterMap());
        }

        requestDetails.setParameters(params);

        /* *************************
         * Notify interceptors about the incoming request
         * *************************/

        for (IServerInterceptor next : myInterceptors) {
            boolean continueProcessing = next.incomingRequestPreProcessed(theRequest, theResponse);
            if (!continueProcessing) {
                ourLog.debug("Interceptor {} returned false, not continuing processing");
                return;
            }
        }

        String requestPath = getRequestPath(requestFullPath, servletContextPath, servletPath);

        if (requestPath.length() > 0 && requestPath.charAt(0) == '/') {
            requestPath = requestPath.substring(1);
        }

        fhirServerBase = getServerBaseForRequest(theRequest);

        IIdType id;
        populateRequestDetailsFromRequestPath(requestDetails, requestPath);

        if (theRequestType == RequestTypeEnum.PUT) {
            String contentLocation = theRequest.getHeader(Constants.HEADER_CONTENT_LOCATION);
            if (contentLocation != null) {
                id = myFhirContext.getVersion().newIdType();
                id.setValue(contentLocation);
                requestDetails.setId(id);
            }
        }

        String acceptEncoding = theRequest.getHeader(Constants.HEADER_ACCEPT_ENCODING);
        boolean respondGzip = false;
        if (acceptEncoding != null) {
            String[] parts = acceptEncoding.trim().split("\\s*,\\s*");
            for (String string : parts) {
                if (string.equals("gzip")) {
                    respondGzip = true;
                }
            }
        }
        requestDetails.setRespondGzip(respondGzip);
        requestDetails.setRequestPath(requestPath);
        requestDetails.setFhirServerBase(fhirServerBase);
        requestDetails.setCompleteUrl(completeUrl);

        // String pagingAction = theRequest.getParameter(Constants.PARAM_PAGINGACTION);
        // if (getPagingProvider() != null && isNotBlank(pagingAction)) {
        // requestDetails.setRestOperationType(RestOperationTypeEnum.GET_PAGE);
        // if (theRequestType != RequestTypeEnum.GET) {
        // /*
        // * We reconstruct the link-self URL using the request parameters, and this would break if the parameters came
        // in using a POST. We could probably work around that but why bother unless
        // * someone comes up with a reason for needing it.
        // */
        // throw new InvalidRequestException(getFhirContext().getLocalizer().getMessage(RestfulServer.class,
        // "getPagesNonHttpGet"));
        // }
        // handlePagingRequest(requestDetails, theResponse, pagingAction);
        // return;
        // }

        BaseMethodBinding<?> resourceMethod = determineResourceMethod(requestDetails, requestPath);

        requestDetails.setRestOperationType(resourceMethod.getRestOperationType());

        // Handle server interceptors
        for (IServerInterceptor next : myInterceptors) {
            boolean continueProcessing = next.incomingRequestPostProcessed(requestDetails, theRequest,
                    theResponse);
            if (!continueProcessing) {
                ourLog.debug("Interceptor {} returned false, not continuing processing");
                return;
            }
        }

        /*
         * Actualy invoke the server method. This call is to a HAPI method binding, which
         * is an object that wraps a specific implementing (user-supplied) method, but
         * handles its input and provides its output back to the client.
         * 
         * This is basically the end of processing for a successful request, since the
         * method binding replies to the client and closes the response.
         */
        Closeable outputStreamOrWriter = (Closeable) resourceMethod.invokeServer(this, requestDetails);

        for (int i = getInterceptors().size() - 1; i >= 0; i--) {
            IServerInterceptor next = getInterceptors().get(i);
            next.processingCompletedNormally(requestDetails);
        }

        if (outputStreamOrWriter != null) {
            outputStreamOrWriter.close();
        }

    } catch (NotModifiedException e) {

        for (int i = getInterceptors().size() - 1; i >= 0; i--) {
            IServerInterceptor next = getInterceptors().get(i);
            if (!next.handleException(requestDetails, e, theRequest, theResponse)) {
                ourLog.debug("Interceptor {} returned false, not continuing processing");
                return;
            }
        }
        writeExceptionToResponse(theResponse, e);

    } catch (AuthenticationException e) {

        for (int i = getInterceptors().size() - 1; i >= 0; i--) {
            IServerInterceptor next = getInterceptors().get(i);
            if (!next.handleException(requestDetails, e, theRequest, theResponse)) {
                ourLog.debug("Interceptor {} returned false, not continuing processing");
                return;
            }
        }

        writeExceptionToResponse(theResponse, e);

    } catch (Throwable e) {

        /*
         * We have caught an exception during request processing. This might be because a handling method threw
         * something they wanted to throw (e.g. UnprocessableEntityException because the request
         * had business requirement problems) or it could be due to bugs (e.g. NullPointerException).
         * 
         * First we let the interceptors have a crack at converting the exception into something HAPI can use
         * (BaseServerResponseException)
         */
        BaseServerResponseException exception = null;
        for (int i = getInterceptors().size() - 1; i >= 0; i--) {
            IServerInterceptor next = getInterceptors().get(i);
            exception = next.preProcessOutgoingException(requestDetails, e, theRequest);
            if (exception != null) {
                ourLog.debug("Interceptor {} returned false, not continuing processing");
                break;
            }
        }

        /*
         * If none of the interceptors converted the exception, default behaviour is to keep the exception as-is if it
         * extends BaseServerResponseException, otherwise wrap it in an
         * InternalErrorException.
         */
        if (exception == null) {
            exception = DEFAULT_EXCEPTION_HANDLER.preProcessOutgoingException(requestDetails, e, theRequest);
        }

        /*
         * Next, interceptors get a shot at handling the exception
         */
        for (int i = getInterceptors().size() - 1; i >= 0; i--) {
            IServerInterceptor next = getInterceptors().get(i);
            if (!next.handleException(requestDetails, exception, theRequest, theResponse)) {
                ourLog.debug("Interceptor {} returned false, not continuing processing");
                return;
            }
        }

        /*
         * If we're handling an exception, no summary mode should be applied
         */
        requestDetails.getParameters().remove(Constants.PARAM_SUMMARY);
        requestDetails.getParameters().remove(Constants.PARAM_ELEMENTS);

        /*
         * If nobody handles it, default behaviour is to stream back the OperationOutcome to the client.
         */
        DEFAULT_EXCEPTION_HANDLER.handleException(requestDetails, exception, theRequest, theResponse);

    }
}

From source file:org.apache.click.util.ClickUtils.java

/**
 * Close the given closeable (Reader, Writer, Stream) and ignore any
 * exceptions thrown./*w  ww  .  jav  a  2 s.  c o m*/
 *
 * @param closeable the closeable (Reader, Writer, Stream) to close.
 */
public static void close(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException ioe) {
            // Ignore
        }
    }
}

From source file:io.fabric8.core.jmx.FabricManager.java

@Override
public Map<String, Object> getProfileFeatures(String versionId, String profileId) {
    Profile profile = getFabricService().getVersion(versionId).getProfile(profileId);
    Profile overlay = profile.getOverlay(true);

    Map<String, Boolean> isParentFeature = new HashMap<String, Boolean>();

    for (String feature : profile.getFeatures()) {
        isParentFeature.put(feature, Boolean.FALSE);
    }/*  w  ww  . j av a  2s . com*/

    for (String feature : overlay.getFeatures()) {
        if (isParentFeature.get(feature) == null) {
            isParentFeature.put(feature, Boolean.TRUE);
        }
    }

    Map<String, Object> rc = new HashMap<String, Object>();

    List<Map<String, Object>> featureDefs = new ArrayList<Map<String, Object>>();

    for (Map.Entry<String, Boolean> featureEntry : isParentFeature.entrySet()) {
        Map<String, Object> featureDef = new HashMap<String, Object>();
        featureDef.put("id", featureEntry.getKey());
        featureDef.put("isParentFeature", featureEntry.getValue());
        featureDefs.add(featureDef);
    }

    rc.put("featureDefinitions", featureDefs);

    List<Map<String, Object>> repositoryDefs = new ArrayList<Map<String, Object>>();
    for (String repo : overlay.getRepositories()) {
        Map<String, Object> repoDef = new HashMap<String, Object>();

        repoDef.put("id", repo);
        Closeable closeable = null;
        try {
            URL url = new URL(repo);
            InputStream os = url.openStream();
            closeable = os;
            InputStream is = new BufferedInputStream(url.openStream());
            closeable = is;
            char[] buffer = new char[8192];
            StringBuilder data = new StringBuilder();

            Reader in = new InputStreamReader(is, "UTF-8");
            closeable = in;
            for (;;) {
                int stat = in.read(buffer, 0, buffer.length);
                if (stat < 0) {
                    break;
                }
                data.append(buffer, 0, stat);
            }
            repoDef.put("data", data.toString());
        } catch (Throwable t) {
            repoDef.put("error", t.getMessage());
        } finally {
            try {
                if (closeable != null) {
                    closeable.close();
                }
            } catch (Throwable t) {
                // whatevs, I tried
            }
        }

        repositoryDefs.add(repoDef);
    }

    rc.put("repositoryDefinitions", repositoryDefs);

    return rc;

}

From source file:de.vanita5.twittnuker.util.Utils.java

public static boolean closeSilently(final Closeable c) {
    if (c == null)
        return false;
    try {//  w  ww.  j a v  a2s . c o m
        c.close();
    } catch (final IOException e) {
        return false;
    }
    return true;
}

From source file:org.pentaho.di.trans.step.BaseStep.java

/**
 * Close quietly./*from w ww.  ja v a 2  s .co m*/
 *
 * @param cl the object that can be closed.
 */
public static void closeQuietly(Closeable cl) {
    if (cl != null) {
        try {
            cl.close();
        } catch (IOException ignored) {
            // Ignore IOException on close
        }
    }
}

From source file:org.getlantern.firetweet.util.Utils.java

public static boolean closeSilently(final Closeable c) {
    if (c == null)
        return false;
    try {/*from   ww  w .  j av a  2 s.c om*/
        c.close();
    } catch (final IOException e) {
        Crashlytics.logException(e);
        return false;
    }
    return true;
}