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:org.opencms.main.CmsUIServlet.java

/**
 * @see com.vaadin.server.VaadinServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*w w  w . j  a v  a 2  s.c  om*/
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // check to OpenCms runlevel
    int runlevel = OpenCmsCore.getInstance().getRunLevel();

    // write OpenCms server identification in the response header
    response.setHeader(CmsRequestUtil.HEADER_SERVER, OpenCmsCore.getInstance().getSystemInfo().getVersion());

    if (runlevel != OpenCms.RUNLEVEL_4_SERVLET_ACCESS) {
        // not the "normal" servlet runlevel
        if (runlevel == OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
            // we have shell runlevel only, upgrade to servlet runlevel (required after setup wizard)
            init(getServletConfig());
        } else {
            // illegal runlevel, we can't process requests
            // sending status code 403, indicating the server understood the request but refused to fulfill it
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            // goodbye
            return;
        }
    }

    // check if the given request matches the workplace site
    if ((OpenCms.getSiteManager().getSites().size() > 1)
            && !OpenCms.getSiteManager().isWorkplaceRequest(request)) {

        // do not send any redirects to the workplace site for security reasons
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    try {
        OpenCmsCore.getInstance().initCmsContextForUI(request, response, this);
        super.service(request, response);
        OpenCms.getSessionManager().updateSessionInfo(getCmsObject(), request);

    } catch (CmsRoleViolationException rv) {
        // don't log these into the error channel
        LOG.debug(rv.getLocalizedMessage(), rv);
        // error code not set - set "internal server error" (500)
        int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(status);
        try {
            response.sendError(status, rv.toString());
        } catch (IOException e) {
            // can be ignored
            LOG.error(e.getLocalizedMessage(), e);
        }
    } catch (Throwable t) {
        // error code not set - set "internal server error" (500)
        LOG.error(t.getLocalizedMessage(), t);
        int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(status);
        try {
            response.sendError(status, t.toString());
        } catch (IOException e) {
            // can be ignored
            LOG.error(e.getLocalizedMessage(), e);
        }
    } finally {
        // remove the thread local cms context
        setCms(null);
    }
}

From source file:com.ning.metrics.serialization.writer.DiskSpoolEventWriter.java

@Managed(description = "Flush events (forward them to final handler)")
public void flush() {
    if (!currentlyFlushing.compareAndSet(false, true)) {
        return;/*from  w ww  . j  a  v a2s . co m*/
    }

    for (final File file : getSpooledFileList()) {
        if (flushEnabled.get()) {
            // Move files aside, to avoid sending dups (the handler can take longer than the flushing period)
            final File lockedFile = renameFile(file, lockDirectory);
            final CallbackHandler callbackHandler = new CallbackHandler() {
                @Override
                public synchronized void onError(final Throwable t, final File file) {
                    log.warn("Error trying to flush file {}: {}", file, t.getLocalizedMessage());

                    if (file != null && file.exists()) {
                        quarantineFile(lockedFile);
                    }
                }

                @Override
                public void onSuccess(final File file) {
                    // Delete the file
                    if (!file.exists()) {
                        log.warn("Trying to delete a file that does not exist: {}", file);
                    } else if (!file.delete()) {
                        log.warn("Unable to delete file {}", file);
                    }
                    log.debug("Deleted [{}]", file);
                }
            };

            try {
                eventHandler.handle(lockedFile, callbackHandler);
            } catch (RuntimeException e) {
                log.warn(String.format(
                        "Unknown error transferring events from local disk spool to flusher. Quarantining local file %s to directory %s",
                        file, quarantineDirectory), e);
                callbackHandler.onError(e, lockedFile);
            }
        }
    }

    currentlyFlushing.set(false);
}

From source file:nz.co.senanque.vaadinsupport.MaduraPropertyWrapper.java

public void setValue(Object newValue) {
    if (isReadOnly()) {
        return;/*www .  j  av a  2s .c o m*/
    }
    try {
        Class<?> clazz = this.getDataType();
        Object converted = newValue;
        if (m_propertyFormatter != null) {
            try {
                converted = m_propertyFormatter.parse(String.valueOf(newValue));
            } catch (Exception e) {
                MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(m_messageSource);
                String message = messageSourceAccessor.getMessage(
                        "nz.co.senanque.validationengine.numericparse",
                        new Object[] { this.m_label, String.valueOf(newValue) });
                throw new ValidationException(message);
            }
        } else {
            if (converted instanceof ChoiceBase) {
                converted = ((ChoiceBase) converted).getKey();
            }
            if (clazz != String.class) {
                try {
                    if (clazz.isEnum()) {
                        Method fromValueMethod = clazz.getMethod("fromValue", String.class);
                        converted = fromValueMethod.invoke(null, new Object[] { String.valueOf(newValue) });
                    } else {
                        MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(
                                m_messageSource);
                        converted = ConvertUtils.convertToObject(clazz, newValue, messageSourceAccessor);
                    }
                } catch (Exception e) {
                    throw e;
                }
            }
        }
        m_setter.invoke(m_owner, new Object[] { converted });
        setErrorText(null);
        m_lastFailedValue = null;
    } catch (InvocationTargetException e) {
        logger.warn("error", e);
        Throwable target = e.getTargetException();
        if (target != null) {
            if (target instanceof ValidationException) {
                setErrorText(target.getLocalizedMessage());
                m_lastFailedValue = newValue;
            } else {
                throw new RuntimeException(target);
            }
        } else {
            throw new RuntimeException(e);
        }
    } catch (ValidationException e) {
        logger.warn("error", e);
        setErrorText(e.getLocalizedMessage());
        m_lastFailedValue = newValue;
    } catch (Exception e) {
        logger.warn("error", e);
        throw new RuntimeException(e);
    }
}

From source file:com.midooo.ui.activitys.ImageGridFragment.java

private void faXingQuan_getList(String style, String length, String curl, String color, String sex,
        String curpage, String pagesize) {
    RequestParams params = new RequestParams();

    Log.w("---doop---", "start---------faXingQuan_getList-----111----");
    params.put("style", (style == null) ? "0" : style);
    params.put("length", (style == null) ? "0" : style);
    params.put("curl", (style == null) ? "0" : style);
    params.put("color", (style == null) ? "0" : style);
    params.put("sex", (style == null) ? "" : style);
    params.put("curpage", (style == null) ? "1" : style);
    params.put("pagesize", (style == null) ? "10" : style);
    Log.w("---doop---", "start---------faXingQuan_getList----222-----");

    midooRequest.post("/faxingquan/index/getlist", params, new JsonHttpResponseHandler() {//

        Message msg = new Message();

        @Override//  w  ww  . j a v  a  2  s  .  c  o  m
        public void onStart() {
            Log.w("---doop---faXingQuan_getList---", "---onStart---");
        }

        @Override
        public void onFinish() {
            Log.w("---doop---faXingQuan_getList---", "---onFinish---");
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.w("---doop---", "---onFailure---" + responseString + "------" + statusCode + "------"
                    + throwable.getLocalizedMessage());

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            Log.w("---doop---", "---onSuccess---" + response.toString() + "------" + statusCode + "------");
            Toast.makeText((FaXingQuanMainActivity) getActivity(), response.toString(), Toast.LENGTH_LONG)
                    .show();

            //JSONArray jsonList;
            try {
                imageUrls = response.getJSONArray("data");

                msg.what = (true) ? 1 : 0;
                msg.obj = (true) ? imageUrls : null;// ?
                /*
                for (int i = 0; i < jsonList.length(); i++) {
                    JSONObject row = jsonList.getJSONObject(i);
                    Log.w("---doop---", "---row---"+row.toString()+"------------");
                    imageUrls.add(row);
                    //name = row.getString("stylephoto");
                }*/
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                msg.what = -1;
                msg.obj = e;
            }
            mHandler.sendMessage(msg);

        }
    });

}

From source file:org.opencms.jlan.CmsJlanDiskInterface.java

/**
 * Tries to unlock the file at the given path.<p>
 *
 * @param cms the CMS context wrapper//from w  ww.j  a  v  a2s .co  m
 * @param path the path of the resource to unlock
 */
private void tryUnlock(CmsObjectWrapper cms, String path) {

    try {
        cms.unlockResource(path);
    } catch (Throwable e) {
        LOG.info(e.getLocalizedMessage(), e);
    }

}

From source file:org.apache.hadoop.hdfs.AvatarZKShell.java

/**
 * run/*from   www  . j ava2 s  . c o m*/
 */
public int run(String argv[]) throws Exception {

    if (argv.length < 1) {
        printUsage("");
        return -1;
    }

    int exitCode = 0;
    String zkCmd = null;
    String serviceName = null;
    String instance = null;
    boolean force = false;

    // enforce to specify service if configured
    if (!AvatarShell.isServiceSpecified("AvatarZKShell", conf, argv)) {
        return -1;
    }

    for (int i = 0; i < argv.length; i++) {
        String cmd = argv[i];

        //
        // verify that we have enough command line parameters
        //
        if ("-service".equals(cmd)) {
            if (i + 1 == argv.length) {
                printUsage(cmd);
                return -1;
            }
            serviceName = argv[++i];
        } else if ("-updateZK".equals(cmd)) {
            zkCmd = cmd;
            if (i + 1 == argv.length) {
                printUsage(cmd);
                return -1;
            }
            instance = argv[++i];
            if (i + 1 < argv.length && argv[i + 1].equals("-force")) {
                force = true;
                i++;
            }
        } else if ("-clearZK".equals(cmd)) {
            zkCmd = cmd;
        } else if ("-createZK".equals(cmd)) {
            zkCmd = cmd;
            if (i + 1 == argv.length) {
                printUsage(cmd);
                return -1;
            }
            instance = argv[++i];
        } else if ("-getZK".equals(cmd)) {
            zkCmd = cmd;
        } else {
            exitCode = -1;
            System.err.println(cmd.substring(1) + ": Unknown command");
            printUsage("");
        }
    }

    // make sure that command is provided
    if (zkCmd == null) {
        printUsage("");
        return -1;
    }

    Collection<String> services;
    if (serviceName != null) { // for one service
        if (!AvatarNode.validateServiceName(conf, serviceName)) {
            return -1;
        }
        services = new ArrayList<String>(1);
        services.add(serviceName);
    } else { // for all configured services
        services = DFSUtil.getNameServiceIds(conf);
        if (services.size() == 0) {
            //non-federation
            services.add("");
        }
    }

    try {
        for (String service : services) {
            AvatarNode.initializeGenericKeys(originalConf, service);
            if ("-updateZK".equals(zkCmd) || "-createZK".equals(zkCmd)) {
                if (instance == null || (conf = updateConf(instance, originalConf)) == null) {
                    printUsage(zkCmd);
                    return -1;
                }
            }

            if ("-updateZK".equals(zkCmd)) {
                updateZooKeeper(force, service, instance);
            } else if ("-clearZK".equals(zkCmd)) {
                clearZooKeeper(service);
            } else if ("-createZK".equals(zkCmd)) {
                updateZooKeeper(true, false, service, instance);
            } else if ("-getZK".equals(zkCmd)) {
                getZooKeeper(service);
            }
        }
    } catch (IllegalArgumentException arge) {
        exitCode = -1;
        arge.printStackTrace();
        System.err.println(zkCmd.substring(1) + ": " + arge.getLocalizedMessage());
        printUsage(zkCmd);
    } catch (RemoteException e) {
        exitCode = -1;
        try {
            String[] content;
            content = e.getLocalizedMessage().split("\n");
            System.err.println(zkCmd.substring(1) + ": " + content[0]);
        } catch (Exception ex) {
            System.err.println(zkCmd.substring(1) + ": " + ex.getLocalizedMessage());
        }
    } catch (IOException e) {
        //
        // IO exception encountered locally.
        //
        exitCode = -1;
        System.err.println(zkCmd.substring(1) + ": " + e.getLocalizedMessage());
        e.printStackTrace();
    } catch (Throwable re) {
        exitCode = -1;
        System.err.println(zkCmd.substring(1) + ": " + re.getLocalizedMessage());
        re.printStackTrace();
    } finally {
    }
    return exitCode;
}

From source file:com.example.parkhere.seeker.SeekerProfileVehicleFragment.java

public void editVehicle() {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()).build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.UPDATE_VEHICLE_OPERATION);
    request.setUser(user);/*from ww  w.  jav  a2  s  .  c o m*/
    request.setVehicle(vehicles[selectedIndex - 1]);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
            ServerResponse resp = response.body();

            if (resp.getResult().equals(Constants.SUCCESS)) {
            }
            Snackbar.make(rootView, resp.getMessage(), Snackbar.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {
            Snackbar.make(rootView, t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
        }
    });
}

From source file:pt.webdetails.cpf.SimpleContentGenerator.java

private void handleError(final String methodName, Throwable e) throws IOException {

    logger.error(methodName + ": " + e.getMessage(), e);

    String msg = e.getLocalizedMessage();
    if (e instanceof QueryTimeoutException || e instanceof TimeoutException)
    //          ||
    //          (e instanceof RuntimeException &&
    //              StringUtils.containsIgnoreCase(e.getClass().getName(), "timeout"))) 
    {/*w  w  w  .j  ava2 s  .co m*/
        getResponse().sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, msg);
    } else {// default to 500
        getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    }
}

From source file:com.example.parkhere.seeker.SeekerProfileVehicleFragment.java

public void deleteVehicle() {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()).build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.DELETE_VEHICLE_OPERATION);
    request.setUser(user);/*from  w ww. j av  a2  s . c  o m*/
    Vehicle v = getVehicle(selectedLicensePlate);
    request.setVehicle(v);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
            ServerResponse resp = response.body();

            if (resp.getResult().equals(Constants.SUCCESS)) {
                vehicles[selectedIndex - 1] = new Vehicle();
                TableRow tr = (TableRow) tl.findViewWithTag(selectedIndex);
                tl.removeView(tr);
                selectedIndex = -1;
                tag--;
            }
            Snackbar.make(rootView, resp.getMessage(), Snackbar.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {
            Snackbar.make(rootView, t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
        }
    });
}

From source file:org.geotools.coverage.io.netcdf.NetCDFPolyphemusTest.java

@Test
public void geoToolsReader() throws IllegalArgumentException, IOException, NoSuchAuthorityCodeException {
    boolean isInteractiveTest = TestData.isInteractiveTest();

    // create a base driver
    final DefaultFileDriver driver = new NetCDFDriver();
    final File[] files = TestData.file(this, ".").listFiles(new FileFilter() {

        @Override//from  www.j a va2 s .  c om
        public boolean accept(File pathname) {
            return FilenameUtils.getName(pathname.getAbsolutePath()).equalsIgnoreCase("O3-NO2.nc");
        }

    });

    for (File f : files) {

        // move to test directory
        final File file = new File(testDirectory, "O3-NO2.nc");
        FileUtils.copyFile(f, file);

        // get the file
        final URL source = file.toURI().toURL();
        assertTrue(driver.canProcess(DriverCapabilities.CONNECT, source, null));

        LOGGER.info("ACCEPTED: " + source.toString());

        // getting access to the file
        CoverageAccess access = null;

        try {
            access = driver.process(DriverCapabilities.CONNECT, source, null, null, null);
            if (access == null) {
                throw new IOException("Unable to connect");
            }
            // get the names
            final List<Name> names = access.getNames(null);
            for (Name name : names) {
                // get a source
                final CoverageSource gridSource = access.access(name, null, AccessType.READ_ONLY, null, null);
                if (gridSource == null) {
                    throw new IOException("Unable to access");
                }
                LOGGER.info("Connected to coverage: " + name.toString());

                // TEMPORAL DOMAIN
                final TemporalDomain temporalDomain = gridSource.getTemporalDomain();
                if (temporalDomain == null) {
                    LOGGER.info("Temporal domain is null");
                } else {
                    // temporal crs
                    LOGGER.info("TemporalCRS: " + temporalDomain.getCoordinateReferenceSystem());

                    // print the temporal domain elements
                    for (DateRange tg : temporalDomain.getTemporalElements(true, null)) {
                        LOGGER.info("Global Temporal Domain: " + tg.toString());
                    }

                    // print the temporal domain elements with overall = true
                    StringBuilder overallTemporal = new StringBuilder(
                            "Temporal domain element (overall = true):\n");
                    for (DateRange tg : temporalDomain.getTemporalElements(false, null)) {
                        overallTemporal.append(tg.toString()).append("\n");
                    }
                    LOGGER.info(overallTemporal.toString());
                }

                // VERTICAL DOMAIN
                final VerticalDomain verticalDomain = gridSource.getVerticalDomain();
                if (verticalDomain == null) {
                    LOGGER.info("Vertical domain is null");
                } else {
                    // vertical crs
                    LOGGER.info("VerticalCRS: " + verticalDomain.getCoordinateReferenceSystem());

                    // print the Vertical domain elements
                    for (NumberRange<Double> vg : verticalDomain.getVerticalElements(true, null)) {
                        LOGGER.info("Vertical domain element: " + vg.toString());
                    }

                    // print the Vertical domain elements with overall = true
                    StringBuilder overallVertical = new StringBuilder(
                            "Vertical domain element (overall = true):\n");
                    for (NumberRange<Double> vg : verticalDomain.getVerticalElements(false, null)) {
                        overallVertical.append(vg.toString()).append("\n");
                    }
                    LOGGER.info(overallVertical.toString());
                }

                // HORIZONTAL DOMAIN
                final SpatialDomain spatialDomain = gridSource.getSpatialDomain();
                if (spatialDomain == null) {
                    LOGGER.info("Horizontal domain is null");
                } else {
                    // print the horizontal domain elements
                    final CoordinateReferenceSystem crs2D = spatialDomain.getCoordinateReferenceSystem2D();
                    assert crs2D != null;
                    final MathTransform2D g2w = spatialDomain.getGridToWorldTransform(null);
                    assert g2w != null;
                    final Set<? extends BoundingBox> spatialElements = spatialDomain.getSpatialElements(true,
                            null);
                    assert spatialElements != null && !spatialElements.isEmpty();

                    final StringBuilder buf = new StringBuilder();
                    buf.append("Horizontal domain is as follows:\n");
                    buf.append("G2W:").append("\t").append(g2w).append("\n");
                    buf.append("CRS2D:").append("\t").append(crs2D).append("\n");
                    for (BoundingBox bbox : spatialElements) {
                        buf.append("BBOX:").append("\t").append(bbox).append("\n");
                    }
                    LOGGER.info(buf.toString());
                }

                CoverageReadRequest readRequest = new CoverageReadRequest();
                // //
                //
                // Setting up a limited range for the request.
                //
                // //

                LinkedHashSet<NumberRange<Double>> requestedVerticalSubset = new LinkedHashSet<NumberRange<Double>>();
                SortedSet<? extends NumberRange<Double>> verticalElements = verticalDomain
                        .getVerticalElements(false, null);
                final int numLevels = verticalElements.size();
                final Iterator<? extends NumberRange<Double>> iterator = verticalElements.iterator();
                for (int i = 0; i < numLevels; i++) {
                    NumberRange<Double> level = iterator.next();
                    if (i % (numLevels / 5) == 1) {
                        requestedVerticalSubset.add(level);
                    }
                }
                readRequest.setVerticalSubset(requestedVerticalSubset);

                SortedSet<DateRange> requestedTemporalSubset = new DateRangeTreeSet();
                SortedSet<? extends DateRange> temporalElements = temporalDomain.getTemporalElements(false,
                        null);
                final int numTimes = temporalElements.size();
                Iterator<? extends DateRange> iteratorT = temporalElements.iterator();
                for (int i = 0; i < numTimes; i++) {
                    DateRange time = iteratorT.next();
                    if (i % (numTimes / 5) == 1) {
                        requestedTemporalSubset.add(time);
                    }
                }
                readRequest.setTemporalSubset(requestedTemporalSubset);

                CoverageResponse response = gridSource.read(readRequest, null);
                if (response == null || response.getStatus() != Status.SUCCESS
                        || !response.getExceptions().isEmpty()) {
                    throw new IOException("Unable to read");
                }

                final Collection<? extends Coverage> results = response.getResults(null);
                int index = 0;
                for (Coverage c : results) {
                    GridCoverageResponse resp = (GridCoverageResponse) c;
                    GridCoverage2D coverage = resp.getGridCoverage2D();
                    String title = coverage.getSampleDimension(0).getDescription().toString();
                    // Crs and envelope
                    if (isInteractiveTest) {
                        // ImageIOUtilities.visualize(coverage.getRenderedImage(), "tt",true);
                        coverage.show(title + " " + index++);
                    } else {
                        PlanarImage.wrapRenderedImage(coverage.getRenderedImage()).getTiles();
                    }

                    final StringBuilder buffer = new StringBuilder();
                    buffer.append("GridCoverage CRS: ")
                            .append(coverage.getCoordinateReferenceSystem2D().toWKT()).append("\n");
                    buffer.append("GridCoverage GG: ").append(coverage.getGridGeometry().toString())
                            .append("\n");
                    LOGGER.info(buffer.toString());
                }
                gridSource.dispose();
            }
        } catch (Throwable t) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.log(Level.WARNING, t.getLocalizedMessage(), t);
            }
        } finally {
            if (access != null) {
                try {
                    access.dispose();
                } catch (Throwable t) {
                    // Does nothing
                }
            }
        }
    }
}