Example usage for java.io IOException getLocalizedMessage

List of usage examples for java.io IOException getLocalizedMessage

Introduction

In this page you can find the example usage for java.io IOException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.zenoss.zep.index.impl.lucene.LuceneEventIndexBackend.java

private EventSummaryResult listInternal(EventSummaryRequest request, Set<String> fieldsToLoad)
        throws ZepException {
    IndexSearcher searcher = null;/*from   w  w w. ja  v  a2 s. co m*/
    long now = System.currentTimeMillis();
    Query query = null;
    try {
        searcher = getSearcher();
        query = buildQuery(searcher.getIndexReader(), request.getEventFilter(), request.getExclusionFilter());
        Sort sort = buildSort(request.getSortList());
        return searchToEventSummaryResult(searcher, query, sort, fieldsToLoad, request.getOffset(),
                request.getLimit());
    } catch (IOException e) {
        throw new ZepException(e.getLocalizedMessage(), e);
    } catch (OutOfMemoryError e) {
        closeSearcherManager();
        throw e;
    } finally {
        returnSearcher(searcher);
        if (query != null) {
            logger.debug("Query {} finished in {} milliseconds", query.toString(),
                    System.currentTimeMillis() - now);
        }
    }
}

From source file:TimestreamsTests.java

/**
 * Performs HTTP get for a given URL//from ww  w .  j a v  a2  s.  c o m
 * 
 * @param url
 *            is the URL to get
 * @return a String with the contents of the get
 */
private Map<String, List<String>> doGet(URL url) {
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        Map<String, List<String>> responseHeaderFields = conn.getHeaderFields();
        System.out.println(responseHeaderFields);
        if (responseHeaderFields.get(null).get(0).equals("HTTP/1.1 200 OK")) {
            InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line;
            do {
                line = buff.readLine();
                System.out.println(line + "\n");
            } while (line != null);
        }
        return responseHeaderFields;
    } catch (IOException e) {
        fail = e.getLocalizedMessage();
        return null;
    }
}

From source file:io.hops.hopsworks.apiV2.projects.DatasetsResource.java

@ApiOperation(value = "Create a dataset", notes = "Create a dataset in this project.")
@POST//from   ww w.j  a  v  a  2s.com
@Produces(MediaType.APPLICATION_JSON)
@AllowedProjectRoles({ AllowedProjectRoles.DATA_SCIENTIST, AllowedProjectRoles.DATA_OWNER })
public Response createDataSet(CreateDatasetView createDatasetView, @Context SecurityContext sc,
        @Context HttpServletRequest req, @Context UriInfo uriInfo) throws AppException {

    Users user = userFacade.findByEmail(sc.getUserPrincipal().getName());
    DistributedFileSystemOps dfso = dfs.getDfsOps();
    String username = hdfsUsersBean.getHdfsUserName(project, user);
    if (username == null) {
        throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(), "User not found");
    }
    DistributedFileSystemOps udfso = dfs.getDfsOps(username);

    try {
        datasetController.createDataset(user, project, createDatasetView.getName(),
                createDatasetView.getDescription(), createDatasetView.getTemplate(),
                createDatasetView.isSearchable(), false, dfso); // both are dfso to create it as root user

        //Generate README.md for the dataset if the user requested it
        if (createDatasetView.isGenerateReadme()) {
            //Persist README.md to hdfs
            datasetController.generateReadme(udfso, createDatasetView.getName(),
                    createDatasetView.getDescription(), project.getName());
        }
    } catch (IOException e) {
        throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
                "Failed to create dataset: " + e.getLocalizedMessage());
    } finally {
        if (dfso != null) {
            dfso.close();
        }
        if (udfso != null) {
            dfs.closeDfsClient(udfso);
        }
    }
    Dataset dataset = getDataset(createDatasetView.getName());
    GenericEntity<DatasetView> created = new GenericEntity<DatasetView>(new DatasetView(dataset)) {
    };

    UriBuilder builder = uriInfo.getAbsolutePathBuilder();
    builder.path(dataset.getName());
    return Response.created(builder.build()).type(MediaType.APPLICATION_JSON_TYPE).entity(created).build();
}

From source file:nl.sogeti.android.gpstracker.actions.ShareTrack.java

/**
 * POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website publishing 
 * this track to the public./*  ww w.j a v  a 2 s .  co m*/
 * 
 * @param fileUri
 * @param contentType
 */
private void sendToOsm(Uri fileUri, Uri trackUri, String contentType) {
    String username = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_USERNAME, "");
    String password = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_PASSWORD, "");
    String visibility = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_VISIBILITY,
            "trackable");
    File gpxFile = new File(fileUri.getEncodedPath());
    String hostname = getString(R.string.osm_post_host);
    Integer port = new Integer(getString(R.string.osm_post_port));
    HttpHost targetHost = new HttpHost(hostname, port, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;
    String responseText = "";
    int statusCode = 0;
    Cursor metaData = null;
    String sources = null;
    try {
        metaData = this.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"),
                new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ",
                new String[] { Constants.DATASOURCES_KEY }, null);
        if (metaData.moveToFirst()) {
            sources = metaData.getString(0);
        }
        if (sources != null && sources.contains(LoggerMap.GOOGLE_PROVIDER)) {
            throw new IOException("Unable to upload track with materials derived from Google Maps.");
        }

        // The POST to the create node
        HttpPost method = new HttpPost(getString(R.string.osm_post_context));

        // Preemptive basic auth on the first request 
        method.addHeader(
                new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), method));

        // Build the multipart body with the upload data
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("file", new FileBody(gpxFile));
        entity.addPart("description", new StringBody(queryForTrackName()));
        entity.addPart("tags", new StringBody(queryForNotes()));
        entity.addPart("visibility", new StringBody(visibility));
        method.setEntity(entity);

        // Execute the POST to OpenStreetMap
        response = httpclient.execute(targetHost, method);

        // Read the response
        statusCode = response.getStatusLine().getStatusCode();
        InputStream stream = response.getEntity().getContent();
        responseText = convertStreamToString(stream);
    } catch (IOException e) {
        Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e);
        responseText = getString(R.string.osm_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG);
        toast.show();
    } catch (AuthenticationException e) {
        Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e);
        responseText = getString(R.string.osm_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG);
        toast.show();
    } finally {
        if (metaData != null) {
            metaData.close();
        }
    }

    if (statusCode == 200) {
        Log.i(TAG, responseText);
        CharSequence text = getString(R.string.osm_success) + responseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    } else {
        Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText);
        CharSequence text = getString(R.string.osm_failed) + responseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    }
}

From source file:com.datascience.gal.service.Service.java

/**
 * TODO: make async w/ a callback call to run the iterative ds algorithm
 * /*w w  w. ja va  2 s.  c  o  m*/
 * @return success message
 */
@GET
@Path("computeBlocking")
@Produces(MediaType.APPLICATION_JSON)
public Response computeDsBlocking(@QueryParam("iterations") String iterations, @QueryParam("id") String idstr) {
    int its = 1;
    long time = 0;

    String id = 0 + "";
    if (null == idstr) {
        logger.info("no id input, using id 0");
    } else {
        id = idstr;
    }

    try {
        setup(context);
        DawidSkene ds = dscache.getDawidSkene(id);

        StopWatch sw = new StopWatch();
        sw.start();
        its = Math.max(1, null == iterations ? 1 : Integer.parseInt(iterations));
        ds.estimate(its);
        sw.stop();
        time = sw.getTime();
        String message = "performed ds iteration " + its + " times, took: " + time + "ms.";
        logger.info(message);
        dscache.insertDawidSkene(ds);

        return Response.ok(message).build();

    } catch (IOException e) {
        logger.error("ioexception: " + e.getLocalizedMessage());
    } catch (ClassNotFoundException e) {
        logger.error("class not found exception: " + e.getLocalizedMessage());
    } catch (SQLException e) {
        logger.error("sql exception: " + e.getLocalizedMessage());
    } catch (Exception e) {
        logger.error(e.getLocalizedMessage());
    }
    return Response.status(500).build();
}

From source file:com.safi.workshop.serverview.ServerViewPanel.java

protected void saveLogToFile() {
    String text = logText.getText();
    if (StringUtils.isBlank(text))
        return;/*from   www.j av a2s  . co m*/

    if (saveLogDialog == null) {
        saveLogDialog = new FileDialog(getShell(), SWT.SAVE);
        saveLogDialog.setFilterExtensions(new String[] { "*.log" });
    }
    try {
        saveLogDialog
                .setFileName("SafiServer_" + SafiServerPlugin.getDefault().getSafiServer(true).getBindIP());
        String name = saveLogDialog.open();
        if (StringUtils.isNotBlank(name)) {
            try {
                FileUtils.writeFile(name, text.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                MessageDialog.openError(getShell(), "Save Error",
                        "Couldn't save log contents: " + e.getLocalizedMessage());
                return;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        MessageDialog.openError(getShell(), "SafiServer Error",
                "Couldn't retrieve production SafiServer instance: " + e.getLocalizedMessage());
    }

}

From source file:com.googlecode.jgenhtml.Config.java

/**
* Loads the lcovrc config file from the home directory or the location specified on the
* command line and sets properties in the config object accordingly.
* Does not look for a system wide config file because there is no consistent directory to
* look in across all platforms./* w ww. j a v a  2  s . c om*/
*
* @param alternatePath
*/
private void loadConfigFile(final String alternatePath) {
    try {
        //don't use FileUtils.getUserDirectoryPath() here, it was causing issues when run from Ant
        String lcovrc = System.getProperty("user.home") + File.separatorChar + ".lcovrc";
        Properties properties = loadFileToProperties(alternatePath);
        if (properties != null || (properties = loadFileToProperties(lcovrc)) != null) {

            LOGGER.log(Level.INFO, "Loaded config file {0}.", lcovrc);
            if (properties.containsKey(ConfFileArg.CSS.toString())) {
                setCssFile(properties.getProperty(ConfFileArg.CSS.toString()));
            }
            Integer optionValue = getNumericValue(properties, ConfFileArg.FUNCOV.toString());
            if (optionValue != null) {
                setFunctionCoverage(optionValue != 0);
            }
            optionValue = getNumericValue(properties, ConfFileArg.BRANCOV.toString());
            if (optionValue != null) {
                setBranchCoverage(optionValue != 0);
            }
            optionValue = getNumericValue(properties, ConfFileArg.GZIP.toString());
            if (optionValue != null) {
                setGzip(optionValue != 0);
            }
            optionValue = getNumericValue(properties, ConfFileArg.KEEPDESC.toString());
            if (optionValue != null) {
                setKeepDescriptions(optionValue != 0);
            }
            optionValue = getNumericValue(properties, ConfFileArg.NOSOURCE.toString());
            if (optionValue != null) {
                setNoSource(optionValue != 0);
            }
            optionValue = getNumericValue(properties, ConfFileArg.SORT.toString());
            if (optionValue != null) {
                setNoSort(optionValue == 0);
            }
            optionValue = getNumericValue(properties, ConfFileArg.SPACES.toString());
            if (optionValue != null) {
                setNumSpaces(optionValue);
            }
            optionValue = getNumericValue(properties, ConfFileArg.HILIMIT.toString());
            if (optionValue != null) {
                setHiLimit(optionValue);
            }
            optionValue = getNumericValue(properties, ConfFileArg.MEDLIMIT.toString());
            if (optionValue != null) {
                setMedLimit(optionValue);
            }
            optionValue = getNumericValue(properties, ConfFileArg.NOPREFIX.toString());
            if (optionValue != null) {
                setNoPrefix(optionValue != 0);
            }
            optionValue = getNumericValue(properties, ConfFileArg.LEGEND.toString());
            if (optionValue != null) {
                setLegend(optionValue != 0);
            }
            if (properties.containsKey(ConfFileArg.HTML_EXT.toString())) {
                setHtmlExt(properties.getProperty(ConfFileArg.HTML_EXT.toString()));
            }
            optionValue = getNumericValue(properties, ConfFileArg.HTMLONLY.toString());
            if (optionValue != null) {
                setHtmlOnly(optionValue != 0);
            }
            optionValue = getNumericValue(properties, ConfFileArg.VERBOSE.toString());
            if (optionValue != null) {
                if (optionValue != 0) {
                    Logger parent = Logger.getLogger("com.googlecode.jgenhtml");
                    parent.setLevel(Level.ALL);
                }
            }
        }
    } catch (IOException ex) {
        LOGGER.log(Level.WARNING, ex.getLocalizedMessage());
    }
}

From source file:com.datascience.gal.service.Service.java

/**
 * Loads a json set of category objects/*from   w ww . j  a v a2s  .  co m*/
 * 
 * @return a simple success message
 */
@POST
@Path("loadCategories")
@Produces(MediaType.APPLICATION_JSON)
public Response loadCategories(@FormParam("categories") String input, @FormParam("id") String idstr,
        @FormParam("incremental") String incremental) {
    Collection<Category> categories;
    if (null == input || input.length() < 3) {
        String message = "invalid input. requires json-ified collection of category objects";
        logger.error(message);
        return Response.status(500).build();
    }
    String id = "" + 0;
    if (null == idstr) {
        logger.info("no id input, using id 0");
    } else {
        id = idstr;
    }

    try {
        setup(context);
        categories = JSONUtils.gson.fromJson(input, JSONUtils.categorySetType);
        DawidSkene ds;

        if (null == incremental)
            ds = new BatchDawidSkene(id, categories);
        else
            ds = new IncrementalDawidSkene(id, categories);
        dscache.insertDawidSkene(ds);

        String message = "built a ds with " + categories.size() + " categories"
                + JSONUtils.gson.toJson(categories);
        logger.info(message);
        return Response.ok(message).build();

    } catch (IOException e) {
        logger.error("ioexception: " + e.getLocalizedMessage());
    } catch (ClassNotFoundException e) {
        logger.error("class not found exception: " + e.getLocalizedMessage());
    } catch (SQLException e) {
        logger.error("sql exception: " + e.getLocalizedMessage());
    } catch (Exception e) {
        logger.error("some other exception: " + e.getMessage());
    }
    return Response.status(500).build();
}

From source file:net.sf.logsaw.index.internal.LuceneIndexServiceImpl.java

@Override
public boolean unlock(ILogResource log) throws CoreException {
    Assert.isNotNull(log, "log"); //$NON-NLS-1$
    try {/*from   w ww. java  2  s.c  o m*/
        Directory dir = FSDirectory.open(IndexPlugin.getDefault().getIndexFile(log));
        if (IndexWriter.isLocked(dir)) {
            IndexWriter.unlock(dir);
            return true;
        }
        return false;
    } catch (IOException e) {
        // Unexpected exception; wrap with CoreException
        throw new CoreException(new Status(IStatus.ERROR, IndexPlugin.PLUGIN_ID,
                NLS.bind(Messages.LuceneIndexService_error_failedToUnlockIndex,
                        new Object[] { log.getName(), e.getLocalizedMessage() }),
                e));
    }
}

From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java

private String generateEncodedImg(BufferedImage upperTreeBImage) {
    String sideTreeBase64 = "";
    try {/*  ww w  . j  av  a  2s  .  c o m*/
        ImageEncoder in = ImageEncoderFactory.newInstance(ImageFormat.PNG, 0);

        byte[] imageData = in.encode(upperTreeBImage);
        sideTreeBase64 = Base64.encodeBase64String(imageData);
        sideTreeBase64 = "data:image/png;base64," + sideTreeBase64;
        System.gc();
    } catch (IOException exp) {
        System.err.println(exp.getLocalizedMessage());
    }
    return sideTreeBase64;
}