Example usage for java.lang Throwable getLocalizedMessage

List of usage examples for java.lang Throwable getLocalizedMessage

Introduction

In this page you can find the example usage for java.lang Throwable getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:com.adobe.phonegap.contentsync.Sync.java

private boolean download(final String source, final File file, final JSONObject headers,
        final ProgressEvent progress, final CallbackContext callbackContext, final boolean trustEveryone) {
    Log.d(LOG_TAG, "download " + source);

    if (!Patterns.WEB_URL.matcher(source).matches()) {
        sendErrorMessage("Invalid URL", INVALID_URL_ERROR, callbackContext);
        return false;
    }// w  w w .  j  a v a 2s. co m

    final CordovaResourceApi resourceApi = webView.getResourceApi();
    final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));

    int uriType = CordovaResourceApi.getUriType(sourceUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;

    synchronized (progress) {
        if (progress.isAborted()) {
            return false;
        }
    }
    HttpURLConnection connection = null;
    HostnameVerifier oldHostnameVerifier = null;
    SSLSocketFactory oldSocketFactory = null;
    PluginResult result = null;
    TrackingInputStream inputStream = null;
    boolean cached = false;

    OutputStream outputStream = null;
    try {
        OpenForReadResult readResult = null;
        final Uri targetUri = resourceApi.remapUri(Uri.fromFile(file));

        progress.setTargetFile(file);
        progress.setStatus(STATUS_DOWNLOADING);

        Log.d(LOG_TAG, "Download file: " + sourceUri);
        Log.d(LOG_TAG, "Target file: " + file);
        Log.d(LOG_TAG, "size = " + file.length());

        if (isLocalTransfer) {
            readResult = resourceApi.openForRead(sourceUri);
            if (readResult.length != -1) {
                progress.setTotal(readResult.length);
            }
            inputStream = new SimpleTrackingInputStream(readResult.inputStream);
        } else {
            // connect to server
            // Open a HTTP connection to the URL based on protocol
            connection = resourceApi.createHttpConnection(sourceUri);
            if (useHttps && trustEveryone) {
                // Setup the HTTPS connection class to trust everyone
                HttpsURLConnection https = (HttpsURLConnection) connection;
                oldSocketFactory = trustAllHosts(https);
                // Save the current hostnameVerifier
                oldHostnameVerifier = https.getHostnameVerifier();
                // Setup the connection not to verify hostnames
                https.setHostnameVerifier(DO_NOT_VERIFY);
            }

            connection.setRequestMethod("GET");

            // TODO: Make OkHttp use this CookieManager by default.
            String cookie = getCookies(sourceUri.toString());

            if (cookie != null) {
                connection.setRequestProperty("cookie", cookie);
            }

            // This must be explicitly set for gzip progress tracking to work.
            connection.setRequestProperty("Accept-Encoding", "gzip");

            // Handle the other headers
            if (headers != null) {
                addHeadersToRequest(connection, headers);
            }

            connection.connect();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
                cached = true;
                connection.disconnect();
                sendErrorMessage("Resource not modified: " + source, CONNECTION_ERROR, callbackContext);
                return false;
            } else {
                if (connection.getContentEncoding() == null
                        || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
                    // Only trust content-length header if we understand
                    // the encoding -- identity or gzip
                    int connectionLength = connection.getContentLength();
                    if (connectionLength != -1) {
                        if (connectionLength > getFreeSpace()) {
                            cached = true;
                            connection.disconnect();
                            sendErrorMessage("Not enough free space to download", CONNECTION_ERROR,
                                    callbackContext);
                            return false;
                        } else {
                            progress.setTotal(connectionLength);
                        }
                    }
                }
                inputStream = getInputStream(connection);
            }
        }

        if (!cached) {
            try {
                synchronized (progress) {
                    if (progress.isAborted()) {
                        return false;
                    }
                    //progress.connection = connection;
                }

                // write bytes to file
                byte[] buffer = new byte[MAX_BUFFER_SIZE];
                int bytesRead = 0;
                outputStream = resourceApi.openOutputStream(targetUri);
                while ((bytesRead = inputStream.read(buffer)) > 0) {
                    synchronized (progress) {
                        if (progress.isAborted()) {
                            return false;
                        }
                    }
                    Log.d(LOG_TAG, "bytes read = " + bytesRead);
                    outputStream.write(buffer, 0, bytesRead);
                    // Send a progress event.
                    progress.setLoaded(inputStream.getTotalRawBytesRead());

                    updateProgress(callbackContext, progress);
                }
            } finally {
                synchronized (progress) {
                    //progress.connection = null;
                }
                safeClose(inputStream);
                safeClose(outputStream);
            }
        }

    } catch (Throwable e) {
        sendErrorMessage(e.getLocalizedMessage(), CONNECTION_ERROR, callbackContext);
    } finally {
        if (connection != null) {
            // Revert back to the proper verifier and socket factories
            if (trustEveryone && useHttps) {
                HttpsURLConnection https = (HttpsURLConnection) connection;
                https.setHostnameVerifier(oldHostnameVerifier);
                https.setSSLSocketFactory(oldSocketFactory);
            }
        }
    }

    return true;
}

From source file:im.ene.lab.attiq.ui.activities.ItemDetailActivity.java

private void deleteComment(final String id) {
    new AlertDialog.Builder(this).setMessage(getString(R.string.message_delete_comment))
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override/*from   ww w.  ja  v  a2s  .  co m*/
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, final int which) {
                    ApiClient.deleteComment(id).enqueue(new Callback<Void>() {
                        @Override
                        public void onResponse(Call<Void> call, Response<Void> response) {
                            // Success
                            if (response.code() == 204 && !UIUtil.isEmpty(mComments)) {
                                Iterator<Comment> iterator = mComments.iterator();
                                while (iterator.hasNext()) {
                                    Comment comment = iterator.next();
                                    if (id.equals(comment.getId())) {
                                        iterator.remove();
                                        break;
                                    }
                                }
                            }

                            EventBus.getDefault().post(new ItemCommentsEvent(true, null, mComments));
                        }

                        @Override
                        public void onFailure(Call<Void> call, Throwable t) {
                            EventBus.getDefault()
                                    .post(new ItemCommentsEvent(false,
                                            new Event.Error(Event.Error.ERROR_UNKNOWN, t.getLocalizedMessage()),
                                            mComments));
                        }
                    });
                }
            }).create().show();
}

From source file:gov.va.isaac.gui.preferences.plugins.ViewCoordinatePreferencesPluginViewController.java

public Region getContent() {
    Task<Void> task = new Task<Void>() {
        @Override/*from  ww  w. j  a  v a  2 s .c om*/
        protected Void call() throws Exception {
            log.debug("initializing content");

            try {
                if (!contentLoaded) {
                    contentLoaded = true;

                    // Populate selectableModules
                    final ConceptVersionBI moduleRootConcept = OTFUtility.getConceptVersion(
                            IsaacMetadataAuxiliaryBinding.MODULE.getPrimodialUuid(), panelViewCoordinate);
                    final Set<ConceptVersionBI> moduleConcepts = new HashSet<>();
                    try {
                        moduleConcepts.addAll(OTFUtility.getAllChildrenOfConcept(moduleRootConcept.getNid(),
                                panelViewCoordinate, false));
                    } catch (Exception e) {
                        log.error("Failed loading module concepts as children of " + moduleRootConcept, e);
                        e.printStackTrace();
                        AppContext.getCommonDialogs()
                                .showErrorDialog("Failed loading module concepts as children of "
                                        + moduleRootConcept + ". See logs.", e);
                    }
                    List<SelectableModule> modules = new ArrayList<>();
                    for (ConceptVersionBI cv : moduleConcepts) {
                        modules.add(new SelectableModule(cv.getNid()));
                    }
                    selectableModules.clear();
                    selectableModules.addAll(modules);

                    allModulesMarker.selected.addListener((observable, oldValue, newValue) -> {
                        if (newValue) {
                            for (SelectableModule module : selectableModules) {
                                module.selectedProperty().set(false);
                            }
                        }
                    });
                    selectableModules.forEach(selectableModule -> selectableModule.selectedProperty()
                            .addListener((observable, wasSelected, isSelected) -> {
                                if (isSelected) {
                                    if (!wasSelected) {
                                        //log.debug("Adding module nid={}, uuid={}, desc={}", selectableModule.getNid(), selectableModule.getUuid(), selectableModule.getDescription());
                                        selectedModules.add(selectableModule.getUuid());
                                        allModulesMarker.selectedProperty().set(false);
                                    }
                                } else {
                                    if (wasSelected) {
                                        //log.debug("Removing module nid={}, uuid={}, desc={}", selectableModule.getNid(), selectableModule.getUuid(), selectableModule.getDescription());
                                        selectedModules.remove(selectableModule.getUuid());

                                        if (selectedModules.size() == 0) {
                                            allModulesMarker.selectedProperty().set(true);
                                        }
                                    }
                                }
                            }));
                    selectableModuleListView.getItems().clear();
                    selectableModuleListView.getItems().add(allModulesMarker);
                    Collections.sort(selectableModules);
                    selectableModuleListView.getItems().addAll(selectableModules);

                    runLaterIfNotFXApplicationThread(
                            () -> pathComboBox.setTooltip(new Tooltip("Default path is \""
                                    + OTFUtility.getDescription(getDefaultPath(), panelViewCoordinate)
                                    + "\"")));

                    pathComboBox.getItems().clear();
                    pathComboBox.getItems().addAll(getPathOptions());
                }

                // Reload persisted values every time

                UserProfile loggedIn = ExtendedAppContext.getCurrentlyLoggedInUserProfile();
                pathComboBox.getSelectionModel().select(loggedIn.getViewCoordinatePath());

                // Reload storedStatedInferredOption
                loadStoredStatedInferredOption();

                // Reload storedStatuses
                loadStoredStatuses();

                // Reload storedModules
                final Set<UUID> storedModuleUuids = getStoredModules();
                if (storedModuleUuids.size() == 0) {
                    allModulesMarker.setSelected(true);
                } else {
                    // Check to make sure that stored UUID refers to an existing, known module
                    for (UUID storedModuleUuid : storedModuleUuids) {
                        boolean foundStoredUuidModuleInSelectableModules = false;
                        for (SelectableModule selectableModule : selectableModules) {
                            if (storedModuleUuid.equals(selectableModule.getUuid())) {
                                foundStoredUuidModuleInSelectableModules = true;
                                break;
                            }
                        }

                        if (!foundStoredUuidModuleInSelectableModules) {
                            log.error(
                                    "Loaded module (uuid={}) from user preferences that does not currently exist",
                                    storedModuleUuid);
                            AppContext.getCommonDialogs().showErrorDialog("Unsupported Module",
                                    "Loaded a module UUID from UserProfile that does not correspond to existing module",
                                    "Concept (UUID=" + storedModuleUuid
                                            + ") not a valid module.  Must be one of "
                                            + Arrays.toString(selectableModules.toArray()));
                        }
                    }
                    for (SelectableModule module : selectableModules) {
                        if (storedModuleUuids.contains(module.getUuid())) {
                            module.setSelected(true);
                        } else {
                            module.setSelected(false);
                        }
                    }
                }

                Long storedTime = getStoredTime();
                if (storedTime.equals(Long.MAX_VALUE)) {
                    dateSelectionMethodComboBox.getSelectionModel().select(DateSelectionMethod.USE_LATEST);
                    currentTimeProperty.set(Long.MAX_VALUE);
                    runLaterIfNotFXApplicationThread(() -> datePicker.setValue(LocalDate.now()));
                } else {
                    dateSelectionMethodComboBox.getSelectionModel().select(DateSelectionMethod.SPECIFY);
                    currentTimeProperty.set(storedTime);
                    setDatePickerFromCurrentTimeProperty();
                }

                return null;
            } catch (Exception e) {
                log.error("initContent() task caught " + e.getClass().getName() + " " + e.getLocalizedMessage(),
                        e);
                e.printStackTrace();
                throw e;
            }
        }

        @Override
        protected void succeeded() {
            log.debug("Content initialization succeeded");

            removeProgressIndicator();
        }

        @Override
        protected void failed() {
            removeProgressIndicator();

            Throwable ex = getException();
            log.error("loadContent() caught " + ex.getClass().getName() + " " + ex.getLocalizedMessage(), ex);
            AppContext.getCommonDialogs().showErrorDialog("Failed loading content. See logs.", ex);
        }
    };

    addProgressIndicator();

    Utility.execute(task);

    return gridPaneInRootStackPane;
}

From source file:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then
 * reads the response SOAP message back from the SOAP server
 *
 * @param msgContext the message context
 *
 * @throws AxisFault/* w w  w.  ja  v a 2 s. c o  m*/
 * @deprecated
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", //$NON-NLS-1$
                "CommonsHTTPSender::invoke")); //$NON-NLS-1$
    }
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(connectionManager);
        // the timeout value for allocation of connections from the pool
        httpClient.setHttpConnectionFactoryTimeout(clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, targetURL);
        httpClient.setHostConfiguration(hostConfiguration);

        // look for option to send credentials preemptively (w/out challenge)
        // Control of Preemptive is controlled via policy on a per call basis.
        String preemptive = (String) msgContext.getProperty("HTTPPreemptive"); //$NON-NLS-1$
        if ("true".equals(preemptive)) //$NON-NLS-1$
        {
            httpClient.getParams().setAuthenticationPreemptive(true);
        }

        String webMethod = null;
        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null) {
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
            }
        }

        Message reqMessage = msgContext.getRequestMessage();
        if (posting) {
            method = new PostMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            reqMessage.writeTo(baos);
            ((PostMethod) method).setRequestBody(new ByteArrayInputStream(baos.toByteArray()));
            ((PostMethod) method).setUseExpectHeader(false); // workaround for
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }
        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();
            boolean secure = hostConfiguration.getProtocol().isSecure();
            String ck1 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE);

            String ck2 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE2);
            if (ck1 != null) {
                int index = ck1.indexOf('=');
                state.addCookie(new Cookie(host, ck1.substring(0, index), ck1.substring(index + 1), path, null,
                        secure));
            }
            if (ck2 != null) {
                int index = ck2.indexOf('=');
                state.addCookie(new Cookie(host, ck2.substring(0, index), ck2.substring(index + 1), path, null,
                        secure));
            }
            httpClient.setState(state);
        }
        boolean hasSoapFault = false;
        int returnCode = httpClient.executeMethod(method);
        String contentType = null;
        String contentLocation = null;
        String contentLength = null;
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE) != null) {
            contentType = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue();
        }
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION) != null) {
            contentLocation = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION).getValue();
        }
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH) != null) {
            contentLength = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH).getValue();
        }
        contentType = (null == contentType) ? null : contentType.trim();
        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html") //$NON-NLS-1$
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
            hasSoapFault = true;
        } else {
            String statusMessage = method.getStatusText();
            AxisFault fault = new AxisFault("HTTP", //$NON-NLS-1$
                    "(" + returnCode + ")" //$NON-NLS-1$ //$NON-NLS-2$
                            + statusMessage,
                    null, null);

            try {
                fault.setFaultDetailString(Messages.getMessage("return01", //$NON-NLS-1$
                        "" + returnCode, method.getResponseBodyAsString())); //$NON-NLS-1$
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to pool.
            }
        }

        // wrap the response body stream so that close() also releases the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }

        OperationDesc operation = msgContext.getOperation();
        if (hasSoapFault || operation.getMep().equals(OperationType.REQUEST_RESPONSE)) {
            msgContext.setResponseMessage(outMsg);
        } else {
            // Change #1
            //
            // If the operation is a one-way, then don't set the response
            // on the msg context. Doing so will cause Axis to attempt to
            // read from a non-existent SOAP message which causes errors.
            //
            // Note: also checking to see if the return type is our "VOID"
            // QName from the AeInvokeHandler since that's our workaround
            // for avoiding Axis's Thread creation in Call.invokeOneWay()
            //
            // Since the message context won't have a chance to consume the
            // response stream (which closes the connection), close the
            // connection here.
            method.releaseConnection();
        }

        if (log.isDebugEnabled()) {
            if (null == contentLength) {
                log.debug("\n" //$NON-NLS-1$
                        + Messages.getMessage("no00", "Content-Length")); //$NON-NLS-1$ //$NON-NLS-2$
            }
            log.debug("\n" + Messages.getMessage("xmlRecd00")); //$NON-NLS-1$ //$NON-NLS-2$
            log.debug("-----------------------------------------------"); //$NON-NLS-1$
            log.debug(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE))
                    msgContext.setProperty(HTTPConstants.HEADER_COOKIE, cleanupCookie(headers[i].getValue()));
                else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2))
                    msgContext.setProperty(HTTPConstants.HEADER_COOKIE2, cleanupCookie(headers[i].getValue()));
            }

        }

    } catch (Throwable t) {
        log.debug(t);

        if (method != null) {
            method.releaseConnection();
        }

        // We can call Axis.makeFault() if it's an exception; otherwise
        // construct the AxisFault directly.
        throw (t instanceof Exception) ? AxisFault.makeFault((Exception) t)
                : new AxisFault(t.getLocalizedMessage(), t);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", //$NON-NLS-1$
                "CommonsHTTPSender::invoke")); //$NON-NLS-1$
    }
}

From source file:com.alkacon.opencms.formgenerator.database.CmsFormDataAccess.java

/**
 * Loads a Java properties hash containing SQL queries.<p>
 * // w  w  w .j  a v a 2 s  . c om
 * @param propertyFilename the package/filename of the properties hash
 */
private void loadQueryProperties(String propertyFilename) {

    Properties properties = new Properties();
    try {
        properties.load(getClass().getClassLoader().getResourceAsStream(propertyFilename));
        m_queries.putAll(properties);
    } catch (Throwable t) {
        if (LOG.isErrorEnabled()) {
            LOG.error(t.getLocalizedMessage(), t);
        }
        properties = null;
    }
}

From source file:net.anidb.udp.UdpConnection.java

/**
 * <p>Sends a request and receives a response from the server.</p>
 * <p>The session key will be set automatically, if the client is logged
 * in.</p>/*w  w w. ja  v  a2s . c  o  m*/
 * @param request The request.
 * @return The response.
 * @throws IllegalArgumentException If the request is <code>null</code>.
 * @throws UdpConnectionException If a connection problem occured.
 */
protected UdpResponse communicate(final UdpRequest request) throws UdpConnectionException {

    DatagramPacket packet;
    byte[] buffer;
    UdpResponse response;

    if (request == null) {
        throw new IllegalArgumentException("Argument request is null.");
    }
    synchronized (this.monitor) {
        if (this.socket == null) {
            throw new UdpConnectionException("Connection is already closed.");
        }
        if (this.sessionKey != null) {
            request.addParameter("s", this.sessionKey);
        }
        LOG.debug("send = [" + request.toString() + "]");
        // Flood protection.
        this.doFloodProtection();
        try {
            packet = request.createPacket(this.charset);
        } catch (UnsupportedEncodingException uee) {
            throw new UdpConnectionException("Couldn't encode the request.", uee);
        }
        try {
            // Remember timestamp for flood protection.
            this.timestampLastPacketSend = System.currentTimeMillis();
            this.socket.send(packet);
        } catch (Throwable t) {
            throw new UdpConnectionException("Couldn't send request: " + t.getLocalizedMessage(), t);
        }
        // All packets should be smaller than 64k -> maximum MTU size.
        buffer = new byte[65536];
        packet = new DatagramPacket(buffer, buffer.length);
        try {
            this.socket.receive(packet);
        } catch (Throwable t) {
            throw new UdpConnectionException("Couldn't receive reply: " + t.getLocalizedMessage(), t);
        }
    }
    try {
        response = UdpResponse.getInstance(packet, this.charset);
    } catch (UnsupportedEncodingException uee) {
        throw new UdpConnectionException("Couldn't decode the response.", uee);
    }
    this.checkState(response);
    return response;
}

From source file:org.pentaho.di.ui.repository.repositoryexplorer.controllers.BrowseController.java

public void renameFolder() throws Exception {
    try {/*from w ww . j  a  v  a2  s  . com*/
        Collection<UIRepositoryDirectory> directory = folderTree.getSelectedItems();
        final UIRepositoryDirectory toRename = directory.iterator().next();
        renameRepositoryObject(toRename);
        directoryBinding.fireSourceChanged();
        selectedItemsBinding.fireSourceChanged();
    } catch (Throwable th) {
        if (mainController == null || !mainController.handleLostRepository(th)) {
            messageBox.setTitle(BaseMessages.getString(PKG, "Dialog.Error"));
            messageBox.setAcceptLabel(BaseMessages.getString(PKG, "Dialog.Ok"));
            messageBox.setMessage(BaseMessages.getString(PKG, th.getLocalizedMessage()));
            messageBox.open();
        }
    }
}

From source file:org.pentaho.di.ui.repository.repositoryexplorer.controllers.BrowseController.java

public void renameContent() throws Exception {
    try {/*from  w ww  .  ja va  2 s.c o m*/
        Collection<UIRepositoryContent> content = fileTable.getSelectedItems();
        UIRepositoryObject contentToRename = content.iterator().next();
        renameRepositoryObject(contentToRename);
        if (contentToRename instanceof UIRepositoryDirectory) {
            directoryBinding.fireSourceChanged();
        }
        selectedItemsBinding.fireSourceChanged();
    } catch (Throwable th) {
        if (mainController == null || !mainController.handleLostRepository(th)) {
            messageBox.setTitle(BaseMessages.getString(PKG, "Dialog.Error"));
            messageBox.setAcceptLabel(BaseMessages.getString(PKG, "Dialog.Ok"));
            messageBox.setMessage(BaseMessages.getString(PKG, th.getLocalizedMessage()));
            messageBox.open();
        }
    }
}

From source file:org.orcid.api.common.jaxb.OrcidExceptionMapper.java

private OrcidError getOrcidError(int errorCode, int status, Throwable t) {
    Locale locale = localeManager.getLocale();
    OrcidError orcidError = new OrcidError();
    orcidError.setResponseCode(status);/*from   ww  w .ja  v a  2s .c  o m*/
    orcidError.setErrorCode(errorCode);
    orcidError.setMoreInfo(messageSource.getMessage("apiError." + errorCode + ".moreInfo", null, locale));
    Map<String, String> params = null;
    if (t instanceof ApplicationException) {
        params = ((ApplicationException) t).getParams();
    }
    // Returns an empty message if the key is not found
    String devMessage = messageSource.getMessage("apiError." + errorCode + ".developerMessage", null, "",
            locale);

    // Assign message from the exception
    if ("".equals(devMessage)) {
        devMessage = t.getClass().getCanonicalName();
        Throwable cause = t.getCause();
        String exceptionMessage = t.getLocalizedMessage();
        if (exceptionMessage != null) {
            devMessage += ": " + exceptionMessage;
        }

        if (cause != null) {
            String causeMessage = cause.getLocalizedMessage();
            if (causeMessage != null) {
                devMessage += " (" + causeMessage + ")";
            }
        }
        orcidError.setDeveloperMessage(devMessage);
    } else {
        orcidError.setDeveloperMessage(resolveMessage(devMessage, params));
    }

    orcidError.setUserMessage(resolveMessage(
            messageSource.getMessage("apiError." + errorCode + ".userMessage", null, locale), params));
    return orcidError;
}

From source file:org.opencms.workplace.explorer.CmsResourceUtil.java

/**
 * Returns the name of the user who created the given resource.<p>
 * //from w ww .  jav  a  2 s . com
 * @return the name of the user who created the given resource
 */
public String getUserCreated() {

    String user = m_resource.getUserCreated().toString();
    try {
        user = getCurrentOuRelativeName(
                CmsPrincipal.readPrincipalIncludingHistory(getCms(), m_resource.getUserCreated()).getName());
    } catch (Throwable e) {
        LOG.info(e.getLocalizedMessage());
    }
    return user;
}