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:de.thm.arsnova.ImageUtils.java

/**
 * Rescales an image represented by a Base64-encoded {@link String}
 *
 * @param originalImageString// w w w.ja va2s. co m
 *            The original image represented by a Base64-encoded
 *            {@link String}
 * @param width
 *            the new width
 * @param height
 *            the new height
 * @return The rescaled Image as Base64-encoded {@link String}, returns null
 *         if the passed-on image isn't in a valid format (a Base64-Image).
 */
public String createCover(String originalImageString, final int width, final int height) {
    if (!isBase64EncodedImage(originalImageString)) {
        return null;
    } else {
        final String[] imgInfo = extractImageInfo(originalImageString);

        // imgInfo isn't null and contains two fields, this is checked by "isBase64EncodedImage"-Method
        final String extension = imgInfo[0];
        final String base64String = imgInfo[1];

        byte[] imageData = Base64.decodeBase64(base64String);
        try {
            BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
            BufferedImage newImage = new BufferedImage(width, height, originalImage.getType());
            Graphics2D g = newImage.createGraphics();

            final double ratio = ((double) originalImage.getWidth()) / ((double) originalImage.getHeight());

            int x = 0, y = 0, w = width, h = height;
            if (originalImage.getWidth() > originalImage.getHeight()) {
                final int newWidth = (int) Math.round((float) height * ratio);
                x = -(newWidth - width) >> 1;
                w = newWidth;
            } else if (originalImage.getWidth() < originalImage.getHeight()) {
                final int newHeight = (int) Math.round((float) width / ratio);
                y = -(newHeight - height) >> 1;
                h = newHeight;
            }
            g.drawImage(originalImage, x, y, w, h, null);
            g.dispose();

            StringBuilder result = new StringBuilder();
            result.append("data:image/");
            result.append(extension);
            result.append(";base64,");

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            ImageIO.write(newImage, extension, output);

            output.flush();
            output.close();

            result.append(Base64.encodeBase64String(output.toByteArray()));

            return result.toString();
        } catch (IOException e) {
            LOGGER.error(e.getLocalizedMessage());
            return null;
        }
    }
}

From source file:ca.phon.app.query.SaveQueryDialog.java

private void save() {
    if (checkForm()) {
        File saveFile = getSaveLocation();
        if (saveFile == null) {
            return;
        }// w w  w  .  j ava  2  s .c  o m
        File parentDir = saveFile.getParentFile();
        if (!parentDir.exists())
            parentDir.mkdirs();
        try {
            QueryScriptLibrary.saveScriptToFile(queryScript, saveFile.getAbsolutePath());

            final QueryName queryName = new QueryName(saveFile.toURI().toURL());
            queryScript.putExtension(QueryName.class, queryName);
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex);

            final MessageDialogProperties props = new MessageDialogProperties();
            props.setParentWindow(this);
            props.setRunAsync(false);
            props.setTitle("Save failed");
            props.setHeader("Save failed");
            props.setMessage(ex.getLocalizedMessage());
            NativeDialogs.showMessageDialog(props);
            return;
        }
        this.setVisible(false);
    }
}

From source file:net.sourceforge.dvb.projectx.xinput.ftp.FtpServer.java

public boolean test() {

    int base = 0;
    boolean error = false;
    FTPFile[] ftpFiles;/*from  w w w  .  j a v  a 2 s .  com*/

    testMsg = null;

    try {
        int reply;
        ftpClient.connect(ftpVO.getServer(), ftpVO.getPortasInteger());

        // Check connection
        reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            testMsg = Resource.getString("ftpchooser.msg.noconnect");
            return false;
        }

        // Login
        if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) {
            ftpClient.logout();
            testMsg = Resource.getString("ftpchooser.msg.nologin");
            return false;
        }

        ftpClient.syst();

        // Change directory
        if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) {
            testMsg = Resource.getString("ftpchooser.msg.nodirectory");
            return false;
        }

        testMsg = Resource.getString("ftpchooser.msg.success");
        ftpClient.logout();

    } catch (IOException ex) {
        testMsg = ex.getLocalizedMessage();
        error = true;
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException f) {
            }
        }
    }
    return !error;
}

From source file:de.badw.strauss.glyphpicker.controller.alltab.TeiLoadWorker.java

/**
 * Loads TEI data from a URL./*from w w w. j  a v a  2 s  . c  o  m*/
 *
 * @return the resulting GlyphDefinition list
 */
public List<GlyphDefinition> loadDataFromUrl() {
    SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient();
    try {
        HttpGet httpGet = new HttpGet(dataSource.getBasePath());
        return httpClient.execute(httpGet, new XMLResponseHandler());
    } catch (IOException e) {
        String message = String.format(i18n.getString("TeiLoadWorker.couldNotLoadData"),
                e.getLocalizedMessage(), dataSource.getBasePath());
        if (e instanceof UnknownHostException) {
            message += " Unknown host";
        }
        JOptionPane.showMessageDialog(null, message, i18n.getString("TeiLoadWorker.error"),
                JOptionPane.ERROR_MESSAGE);
        LOGGER.info(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return null;
}

From source file:com.visionspace.jenkins.vstart.plugin.VSPluginPublisher.java

@Override
public boolean perform(AbstractBuild build, Launcher launcher, final BuildListener listener) {

    Result buildResult = build.getResult();

    if (!Result.SUCCESS.equals(buildResult)) {
        // Don't process for unsuccessful builds
        listener.getLogger().println("Build status is not SUCCESS (" + build.getResult().toString() + ").");
        return false;
    }//from   w w  w. ja va 2 s. co  m

    VSPluginPerformer performer = new VSPluginPerformer();
    //add build action
    performer.addBuildAction(build);

    try {

        //DO REPORT HERE
        FilePath jPath = new FilePath(build.getWorkspace(), build.getWorkspace() + "/VSTART_JSON");

        if (!jPath.exists()) {
            return false;
        }

        String filePath = jPath + "/VSTART_JSON_" + build.getId() + ".json";

        //read .json file
        String content = new String(Files.readAllBytes(Paths.get(filePath)));
        JSONArray reports = new JSONArray(content);

        //Generate html report
        VSPluginHtmlWriter htmlWriter = new VSPluginHtmlWriter();
        boolean reportResult = htmlWriter.doHtmlReport(build, reports);

        return reportResult;

    } catch (IOException ex) {
        Logger.getLogger(VSPluginPublisher.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger()
                .println("Exception during the Publisher's perform! -> " + ex.getLocalizedMessage());
        return false;
    } catch (InterruptedException ex) {
        Logger.getLogger(VSPluginPublisher.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Exception during the VSTART run! -> " + ex.getLocalizedMessage());
        return false;
    }
}

From source file:edu.unc.lib.dl.schematron.SchematronValidatorTest.java

@Test
public void testObjectModsSchema() {
    SchematronValidator sv = new SchematronValidator();
    // now add a schema by means of a Spring Resource object
    ClassPathResource test = new ClassPathResource("object-mods.sch", SchematronValidator.class);
    sv.getSchemas().put("object-mods", test);
    sv.loadSchemas();// w ww  .  j  a va  2  s.c  o  m

    try {
        ClassPathResource mods = new ClassPathResource("/samples/raschke_mods.xml", SchematronValidator.class);
        Document report = sv.validate(mods, "object-mods");
        XMLOutputter out = new XMLOutputter();
        out.setFormat(Format.getPrettyFormat());
        String doc = out.outputString(report);
        log.info(doc);
        boolean valid = sv.isValid(mods, "object-mods");
        assertTrue("The Raschke example MODS file should be valid.", valid);
    } catch (IOException e) {
        log.error("cannot read test file", e);
        fail(e.getLocalizedMessage());
    }
}

From source file:net.osten.watermap.convert.PCTReport.java

/**
 * Parse the PCT water report Google docs files.
 *
 * @return set of water reports/*ww w  .  j av a  2 s.  c o  m*/
 */
public synchronized Set<WaterReport> convert() throws IOException {
    Set<WaterReport> results = new HashSet<WaterReport>();

    log.info("dataDir=" + dataDir);

    if (waypoints.size() == 0) {
        log.warning("Waypoints empty, re-initializing...");
        initialize();
    }

    // parse json files
    if (dataDir != null) {
        for (String stateChar : stateChars) {
            for (char sectionChar : sectionChars) {
                try {
                    String fileName = "pct-" + stateChar + "-" + sectionChar + ".json";
                    File jsonFile = new File(dataDir + File.separator + fileName);
                    if (jsonFile.exists() && jsonFile.canRead()) {
                        log.info("reading json file " + jsonFile);
                        String htmlSource = Files.toString(jsonFile, Charset.forName("UTF-8"));
                        JsonParser parser = new JsonParser();
                        JsonElement root = parser.parse(htmlSource);
                        log.info("json root is obj=" + root.isJsonObject());
                        results.addAll(parseDocument(root.getAsJsonObject()));
                    }
                } catch (IOException e) {
                    log.severe(e.getLocalizedMessage());
                }
            }
        }
    }

    return results;
}

From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.SetStudyTreeListener.java

public void writeLine(TreeNode node, BufferedWriter out, String path) {
    for (TreeNode child : node.getChildren()) {
        String newPath = path;/*from  w  w w . ja v  a 2s .co m*/
        if (child.isLabel()) {
            if (child.getParent().isLabel()) {
                String fullname = child.toString();
                String rawFileName = fullname.split(" - ", -1)[0];
                String header = fullname.split(" - ", -1)[1];
                File rawFile = new File(
                        ((ClinicalData) this.dataType).getPath() + File.separator + rawFileName);
                try {
                    String dataLabel = this.labels.get(header);
                    if (dataLabel == null) {
                        dataLabel = header;
                    }
                    int columnNumber = FileHandler.getHeaderNumber(rawFile, header);
                    out.write(rawFileName
                            + "\t" + path + "\t" + columnNumber + "\t" + "\\" + "\t" + FileHandler
                                    .getHeaderNumber(rawFile, child.getParent().toString().split(" - ", -1)[1])
                            + "\t\n");
                    this.columnsDone.get(rawFileName).add(columnNumber);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    this.setStudyTreeUI.displayMessage("File error: " + e.getLocalizedMessage());
                    e.printStackTrace();
                }
            } else {
                String fullname = child.toString();
                String rawFileName = fullname.split(" - ", -1)[0];
                String header = fullname.split(" - ", -1)[1];
                File rawFile = new File(
                        ((ClinicalData) this.dataType).getPath() + File.separator + rawFileName);
                try {
                    String dataLabel = this.labels.get(header);
                    if (dataLabel == null) {
                        dataLabel = header;
                    }
                    int columnNumber = FileHandler.getHeaderNumber(rawFile, header);
                    if (child.hasChildren()) {
                        out.write(rawFileName + "\t" + path + "\t" + columnNumber + "\t" + "DATA_LABEL"
                                + "\t\t\n");
                    } else {
                        out.write(
                                rawFileName + "\t" + path + "\t" + columnNumber + "\t" + dataLabel + "\t\t\n");
                    }
                    this.columnsDone.get(rawFileName).add(columnNumber);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    this.setStudyTreeUI.displayMessage("File error: " + e.getLocalizedMessage());
                    e.printStackTrace();
                }
            }
        } else {
            if (path.compareTo("") != 0) {
                newPath = path + "+";
            }
            newPath += child.toString().replace(' ', '_');
        }
        if (child.hasChildren()) {
            writeLine(child, out, newPath);
        }
    }
}

From source file:com.epam.wilma.extras.shortcircuit.ShortCircuitResponseInformationFileHandler.java

/**
 * Saves the map to a folder, to preserve it for later use.
 *
 * @param httpServletResponse is the response object
 * @return with the response body - that is a json info about the result of the call
 *//*from   www. j av a  2 s.  c  o  m*/
String savePreservedMessagesFromMap(String path, FileFactory fileFactory,
        FileOutputStreamFactory fileOutputStreamFactory, HttpServletResponse httpServletResponse) {
    String response = null;
    String filenamePrefix = "sc" + UniqueIdGenerator.getNextUniqueId() + "_";
    if (!SHORT_CIRCUIT_MAP.isEmpty()) {
        String[] keySet = SHORT_CIRCUIT_MAP.keySet().toArray(new String[SHORT_CIRCUIT_MAP.size()]);
        for (String entryKey : keySet) {
            ShortCircuitResponseInformation information = SHORT_CIRCUIT_MAP.get(entryKey);
            if (information != null) { //save only the cached files
                //save this into file, folder is in folder variable
                String filename = path + filenamePrefix + UniqueIdGenerator.getNextUniqueId() + ".json";
                File file = fileFactory.createFile(filename);
                try {
                    saveMapObject(fileOutputStreamFactory, file, entryKey, information);
                } catch (IOException e) {
                    String message = "Cache save failed at file: " + filename + ", with message: "
                            + e.getLocalizedMessage();
                    logger.info("ShortCircuit: " + message);
                    response = "{ \"resultsFailure\": \"" + message + "\" }";
                    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    break;
                }
            }
        }
    }
    if (response == null) {
        String message = "Cache saved as: " + path + filenamePrefix + "*.json files";
        response = "{ \"resultsSuccess\": \"" + message + "\" }";
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        logger.info("ShortCircuit: " + message);
    }
    return response;
}

From source file:org.puremvc.java.demos.android.currencyconverter.converter.model.HttpCall.java

/**
 * Try to clean everything related to the call here.
 *///from w w w  .  j  av a  2s  .c  o  m
public void close() {
    if (closed)
        return;

    request.abort();
    httpClient.getConnectionManager().shutdown();

    if (inputStream != null) {
        try {
            inputStream.close();
        } catch (IOException e) {
            Log.d(TAG, e.getLocalizedMessage());
        }
    }

    closed = true;
}