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:it.geosolutions.geobatch.postgres.shp2pg.Shp2pgAction.java

/**
 * Removes TemplateModelEvents from the queue and put
 */// w w  w . j ava 2 s  .  c o m
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {
    listenerForwarder.setTask("config");
    listenerForwarder.started();
    if (configuration == null) {
        throw new IllegalStateException("ActionConfig is null.");
    }
    File workingDir = Path.findLocation(configuration.getWorkingDirectory(),
            ((FileBaseCatalog) CatalogHolder.getCatalog()).getConfigDirectory());
    if (workingDir == null) {
        throw new IllegalStateException("Working directory is null.");
    }
    if (!workingDir.exists() || !workingDir.isDirectory()) {
        throw new IllegalStateException((new StringBuilder()).append("Working directory does not exist (")
                .append(workingDir.getAbsolutePath()).append(").").toString());
    }
    FileSystemEvent event = (FileSystemEvent) events.peek();
    // String shapeName = null;
    File shapefile = null;
    File zippedFile = null;
    File files[];
    if (events.size() == 1) {
        zippedFile = event.getSource();
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace((new StringBuilder()).append("Testing for compressed file: ")
                    .append(zippedFile.getAbsolutePath()).toString());
        }
        String tmpDirName = null;
        try {
            tmpDirName = Extract.extract(zippedFile.getAbsolutePath());
        } catch (Exception e) {
            final String message = "Shp2pgAction.execute(): Unable to read zip file: "
                    + e.getLocalizedMessage();
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new ActionException(this, message);
        }
        listenerForwarder.progressing(5F, "File extracted");
        File tmpDirFile = new File(tmpDirName);
        if (!tmpDirFile.isDirectory()) {
            throw new IllegalStateException("Not valid input: we need a zip file ");
        }
        Collector c = new Collector(null);
        List fileList = c.collect(tmpDirFile);
        if (fileList != null) {
            files = (File[]) fileList.toArray(new File[1]);
        } else {
            String message = "Input is not a zipped file nor a valid collection of files";
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(message);
            }
            throw new IllegalStateException(message);
        }
    } else if (events.size() >= 3) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Checking input collection...");
        }
        listenerForwarder.progressing(6F, "Checking input collection...");
        files = new File[events.size()];
        int i = 0;
        for (Iterator i$ = events.iterator(); i$.hasNext();) {
            FileSystemEvent ev = (FileSystemEvent) i$.next();
            files[i++] = ev.getSource();
        }

    } else {
        throw new IllegalStateException("Input is not a zipped file nor a valid collection of files");
    }
    if ((shapefile = acceptable(files)) == null) {
        throw new IllegalStateException("The file list do not contains mondadory files");
    }

    listenerForwarder.progressing(10F, "In progress");

    // At this moment i have the shape and a file list

    // connect to the shapefile
    final Map<String, Serializable> connect = new HashMap<String, Serializable>();
    connect.put("url", DataUtilities.fileToURL(shapefile));

    DataStore sourceDataStore = null;
    String typeName = null;
    SimpleFeatureType originalSchema = null;
    try {
        sourceDataStore = SHP_FACTORY.createDataStore(connect);
        String[] typeNames = sourceDataStore.getTypeNames();
        typeName = typeNames[0];

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Reading content " + typeName);
        }

        originalSchema = sourceDataStore.getSchema(typeName);
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("SCHEMA HEADER: " + DataUtilities.spec(originalSchema));
        }
    } catch (IOException e) {
        final String message = "Error to create PostGres datastore" + e.getLocalizedMessage();
        if (LOGGER.isErrorEnabled())
            LOGGER.error(message);
        if (sourceDataStore != null)
            sourceDataStore.dispose();
        throw new ActionException(this, message);
    }
    // prepare to open up a reader for the shapefile
    Query query = new Query();
    query.setTypeName(typeName);
    CoordinateReferenceSystem prj = originalSchema.getCoordinateReferenceSystem();
    query.setCoordinateSystem(prj);

    DataStore destinationDataSource = null;
    try {
        destinationDataSource = createPostgisDataStore(configuration);

        // check if the schema is present in postgis
        boolean schema = false;
        if (destinationDataSource.getTypeNames().length != 0) {
            for (String tableName : destinationDataSource.getTypeNames()) {
                if (tableName.equalsIgnoreCase(typeName)) {
                    schema = true;
                }
            }
        } else {
            schema = false;
        }
        if (!schema)
            destinationDataSource.createSchema(originalSchema);
        LOGGER.info("SCHEMA: " + schema);

    } catch (IOException e) {
        String message = "Error to create postGis datastore";
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(message);
        }
        if (destinationDataSource != null)
            destinationDataSource.dispose();
        throw new IllegalStateException(message);
    }

    final Transaction transaction = new DefaultTransaction("create");
    FeatureWriter<SimpleFeatureType, SimpleFeature> fw = null;
    FeatureReader<SimpleFeatureType, SimpleFeature> fr = null;
    try {
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(destinationDataSource.getSchema(typeName));
        fw = destinationDataSource.getFeatureWriter(typeName, transaction);
        fr = sourceDataStore.getFeatureReader(query, transaction);
        SimpleFeatureType sourceSchema = sourceDataStore.getSchema(typeName);
        FeatureStore postgisStore = (FeatureStore) destinationDataSource.getFeatureSource(typeName);
        while (fr.hasNext()) {
            final SimpleFeature oldfeature = fr.next();

            for (AttributeDescriptor ad : sourceSchema.getAttributeDescriptors()) {
                String attribute = ad.getLocalName();
                builder.set(attribute, oldfeature.getAttribute(attribute));
            }
            postgisStore.addFeatures(DataUtilities.collection(builder.buildFeature(null)));

        }

        // close transaction
        transaction.commit();

    } catch (Throwable e) {
        try {
            transaction.rollback();
        } catch (IOException e1) {
            final String message = "Transaction rollback unsuccessful: " + e1.getLocalizedMessage();
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new ActionException(this, message);
        }
    } finally {
        try {
            transaction.close();
        } catch (IOException e) {
            final String message = "Transaction close unsuccessful: " + e.getLocalizedMessage();
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new ActionException(this, message);
        }
        if (fr != null) {
            try {
                fr.close();
            } catch (IOException e1) {
                final String message = "Feature reader IO exception: " + e1.getLocalizedMessage();
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(message);
                throw new ActionException(this, message);
            }
        }
        if (fw != null) {
            try {
                fw.close();
            } catch (IOException e1) {
                final String message = "Feature writer IO exception: " + e1.getLocalizedMessage();
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(message);
                throw new ActionException(this, message);
            }
        }
        if (sourceDataStore != null) {
            try {
                sourceDataStore.dispose();
            } catch (Throwable t) {
            }
        }
        if (destinationDataSource != null) {
            try {
                destinationDataSource.dispose();
            } catch (Throwable t) {
            }
        }
    }

    GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(configuration.getGeoserverURL(),
            configuration.getGeoserverUID(), configuration.getGeoserverPWD());

    publisher.createWorkspace(configuration.getDefaultNamespace());

    GSPostGISDatastoreEncoder datastoreEncoder = new GSPostGISDatastoreEncoder();

    datastoreEncoder.setUser(configuration.getDbUID());
    datastoreEncoder.setDatabase(configuration.getDbName());
    datastoreEncoder.setPassword(configuration.getDbPWD());
    datastoreEncoder.setHost(configuration.getDbServerIp());
    datastoreEncoder.setPort(Integer.valueOf(configuration.getDbPort()));
    datastoreEncoder.setName(configuration.getDbName());

    publisher.createPostGISDatastore(configuration.getDefaultNamespace(), datastoreEncoder);
    String shapeFileName = FilenameUtils.getBaseName(shapefile.getName());

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Layer postgis publishing xml-> ");
        LOGGER.info("datastoreEncoder xml: " + datastoreEncoder.toString());
    }

    if (publisher.publishDBLayer(configuration.getDefaultNamespace(), configuration.getDbName(), shapeFileName,
            configuration.getCrs(), configuration.getDefaultStyle())) {
        String message = "PostGis layer SUCCESFULLY registered";
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(message);
        }
        listenerForwarder.progressing(100F, message);
    } else {
        String message = "PostGis layer not registered";
        ActionException ae = new ActionException(this, message);
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(message, ae);
        }
        listenerForwarder.failed(ae);
    }
    events.clear();

    return events;
}

From source file:net.sf.logsaw.ui.impl.LogResourceManagerImpl.java

private synchronized void loadState() throws CoreException {
    logSet = new CopyOnWriteArraySet<ILogResource>();
    if (!stateFile.toFile().exists()) {
        // Not exists yet
        return;//from   w ww  .ja  v a2  s.  c  o m
    }
    IMemento rootElem = null;
    try {
        rootElem = XMLMemento.createReadRoot(new BufferedReader(
                new InputStreamReader(FileUtils.openInputStream(stateFile.toFile()), "UTF-8"))); //$NON-NLS-1$
    } catch (IOException e) {
        // Unexpected exception; wrap with CoreException
        throw new CoreException(new Status(IStatus.ERROR, UIPlugin.PLUGIN_ID,
                NLS.bind(Messages.LogResourceManager_error_failedToLoadState,
                        new Object[] { e.getLocalizedMessage() }),
                e));
    }
    // Check if we can read this
    Integer compat = rootElem.getInteger(ATTRIB_COMPAT);
    if ((compat == null) || (compat.intValue() != COMPAT_VERSION)) {
        throw new CoreException(new Status(IStatus.WARNING, UIPlugin.PLUGIN_ID,
                Messages.LogResourceManager_warn_stateFileIncompatible));
    }

    List<IStatus> statuses = new ArrayList<IStatus>();
    for (IMemento logElem : rootElem.getChildren(ELEM_LOG_RESOURCE)) {
        String name = null;
        try {
            name = logElem.getChild(ELEM_NAME).getTextData();
            IMemento dialectElem = logElem.getChild(ELEM_DIALECT);
            String dialectFactory = dialectElem.getString(ATTRIB_FACTORY);
            ILogDialectFactory factory = CorePlugin.getDefault().getLogDialectFactory(dialectFactory);
            ILogDialect dialect = factory.createLogDialect();

            // Restore config options of dialect
            loadConfigOptions(dialectElem, (IConfigurableObject) dialect.getAdapter(IConfigurableObject.class));
            String pk = logElem.getChild(ELEM_PK).getTextData();

            // TODO Dynamic factory for log resource
            ILogResource log = SimpleLogResourceFactory.getInstance().createLogResource();
            log.setDialect(dialect);
            log.setName(name);
            log.setPK(pk);

            // Restore config options of resource
            loadConfigOptions(logElem, (IConfigurableObject) log.getAdapter(IConfigurableObject.class));

            // Unlock if necessary
            if (IndexPlugin.getDefault().getIndexService().unlock(log)) {
                logger.warn("Unlocked log resource " + log.getName()); //$NON-NLS-1$
            }
            // Register log resource
            registerLogResource(log);
        } catch (Exception e) {
            statuses.add(new Status(IStatus.ERROR, UIPlugin.PLUGIN_ID, NLS.bind(
                    Messages.LogResourceManager_error_failedToRestoreLogResource, new Object[] { name }), e));
        }
    }
    if (!statuses.isEmpty()) {
        MultiStatus multiStatus = new MultiStatus(UIPlugin.PLUGIN_ID, 0,
                statuses.toArray(new IStatus[statuses.size()]),
                Messages.LogResourceManager_error_someLogResourcesCouldNotBeRestored, null);
        throw new CoreException(multiStatus);
    }
    logger.info("Loaded " + logSet.size() + " log resource(s)"); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:com.otisbean.keyring.Ring.java

/**
 * Initialize the cipher object and create the key object.
 * /*from w  w  w  .j av a2s.  c  om*/
 * @param password
 * @return A checkData string, which can be compared against the existing
 * one to determine if the password is valid.
 * @throws GeneralSecurityException
 */
private String initCipher(char[] password) throws GeneralSecurityException {
    log("initCipher()");
    String base64Key = null;
    try {
        // Convert a char array into a UTF-8 byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter out = new OutputStreamWriter(baos, "UTF-8");
        try {
            out.write(password);
            out.close();
        } catch (IOException e) {
            // the only reason this would throw is an encoding problem.
            throw new RuntimeException(e.getLocalizedMessage());
        }
        byte[] passwordBytes = baos.toByteArray();

        /* The following code looks like a lot of monkey-motion, but it yields
         * results compatible with the on-phone Keyring Javascript and Mojo code.
         * 
         * In newPassword() in ring.js, we have this (around line 165):
         * this._key = b64_sha256(this._salt + newPassword); */
        byte[] saltBytes = salt.getBytes("UTF-8");
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(saltBytes, 0, saltBytes.length);
        md.update(passwordBytes, 0, passwordBytes.length);
        byte[] keyHash = md.digest();
        String paddedBase64Key = Base64.encodeBytes(keyHash);
        /* The Javascript SHA-256 library used in Keyring doesn't pad base64 output,
         * so we need to trim off any trailing "=" signs. */
        base64Key = paddedBase64Key.replace("=", "");
        byte[] keyBytes = base64Key.getBytes("UTF-8");

        /* Keyring passes data to Mojo.Model.encrypt(key, data), which eventually
         * make a JNI call to OpenSSL's blowfish api.  The following is the
         * equivalent in straight up JCE. */
        key = new SecretKeySpec(keyBytes, "Blowfish");
        iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
    } catch (UnsupportedEncodingException e) {
        // This is a bit dodgy, but handling a UEE elsewhere is foolish
        throw new GeneralSecurityException(e.getLocalizedMessage());
    }
    return "{" + base64Key + "}";
}

From source file:Main_Window.java

public void Send_Receive_Data_Google_Service(boolean State) {
    try {/*from  www  .j ava  2  s .  c o m*/
        ServerAddress = new URL("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                + Double.parseDouble(Latitude_TextField.getText()) + ","
                + Double.parseDouble(Longitude_TextField.getText()) + "&radius="
                + Double.parseDouble(Radius_TextField.getText()) + "&opennow=" + Boolean.toString(State)
                + "&types=" + Categories.getSelectedItem().toString() + "&key=" + API_KEY);
        //DELTE
        String str = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                + Double.parseDouble(Latitude_TextField.getText()) + ","
                + Double.parseDouble(Longitude_TextField.getText()) + "&radius="
                + Double.parseDouble(Radius_TextField.getText()) + "&opennow=" + Boolean.toString(State)
                + "&types=" + Categories.getSelectedItem().toString() + "&key=" + API_KEY;
        System.out.println(" To url einai -> " + str);
        //set up out communications stuff
        Connection = null;
        //Set up the initial connection
        Connection = (HttpURLConnection) ServerAddress.openConnection();
        Connection.setRequestMethod("GET");
        Connection.setDoOutput(true); //Set the DoOutput flag to true if you intend to use the URL connection for output
        Connection.setDoInput(true);
        Connection.setRequestProperty("Content-type", "text/xml"); //Sets the general request property
        Connection.setAllowUserInteraction(false);
        Encode_String = URLEncoder.encode("test", "UTF-8");
        Connection.setRequestProperty("Content-length", "" + Encode_String.length());
        Connection.setReadTimeout(10000);
        // A non-zero value specifies the timeout when reading from Input stream when a connection is established to a resource. 
        //If the timeout expires before there is data available for read, a java.net.SocketTimeoutException is raised. 
    } catch (IOException IOE) {
        JOptionPane.showMessageDialog(null, "Error -> " + IOE.getLocalizedMessage(), "Exception - IOException",
                JOptionPane.ERROR_MESSAGE, null);
    }

    try {
        wr = new DataOutputStream(Connection.getOutputStream());
        //open output stream to write
    } catch (IOException IOE) {
        JOptionPane.showMessageDialog(null, "Error -> " + IOE.getLocalizedMessage(), "Exception - IOException",
                JOptionPane.ERROR_MESSAGE, null);
    }

    try {
        wr.writeBytes("q=" + strData);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException",
                JOptionPane.ERROR_MESSAGE, null);
    }

    try {
        wr.flush();
        //Force all data to write in channel
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException",
                JOptionPane.ERROR_MESSAGE, null);
    }

    try {
        //read the result from the server
        Buffered_Reader = new BufferedReader(new InputStreamReader(Connection.getInputStream()));
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException",
                JOptionPane.ERROR_MESSAGE, null);
    }

    jsonParser = new JSONParser(); //JSON Parser

    try {
        JsonObject = (JSONObject) jsonParser.parse(Buffered_Reader); //Parse whole BuffererReader IN Object
        JSONArray Results_Array_Json = (JSONArray) JsonObject.get("results"); //take whole array - from json format
        //results - is as string unique that contains all the essential information such as arrays, and strings. So to extract all info we extract results into JSONarray
        //And this comes up due to json format
        for (int i = 0; i < Results_Array_Json.size(); i++) // Loop over each each part of array that contains info we must extract
        {
            JSONObject o = (JSONObject) Results_Array_Json.get(i);

            try { //We assume that for every POI exists for sure an address !!! thats why the code is not insida a try-catch
                Temp_Name = (String) o.get("name");
                Temp_Address = (String) o.get("vicinity");
                JSONObject Str_1 = (JSONObject) o.get("geometry"); //Geometry is object so extract geometry
                JSONArray Photo_1 = (JSONArray) o.get("photos");
                JSONObject Photo_2 = (JSONObject) Photo_1.get(0);
                String Photo_Ref = (String) Photo_2.get("photo_reference");
                JSONObject Str_2 = (JSONObject) Str_1.get("location");
                Temp_X = (double) Str_2.get("lat");
                Temp_Y = (double) Str_2.get("lng");
                //In case some POI has no Rating
                try {
                    //Inside try-catch block because may some POI has no rating
                    Temp_Rating = (double) o.get("rating");
                    Point POI_Object = new Point(Temp_Name, Temp_Address, Photo_Ref, Temp_Rating, Temp_X,
                            Temp_Y);
                    POI_List.add(POI_Object); //Add POI in List to keep it
                } catch (Exception Er) {
                    //JOptionPane.showMessageDialog ( null, "No rating for this POI " ) ;
                    Point POI_Object_2 = new Point(Temp_Name, Temp_Address, Photo_Ref, 0.0, Temp_X, Temp_Y);
                    POI_List.add(POI_Object_2); //Add POI in List to keep it
                }
            } catch (Exception E) {
                //JOptionPane.showMessageDialog ( this, "Error -> " + E.getLocalizedMessage ( ) + ", " + E.getMessage ( ) ) ;
            }
            o.clear();
        }
    } catch (ParseException PE) {
        JOptionPane.showMessageDialog(this, "Error -> " + PE.getLocalizedMessage(),
                "Parse, inside while JSON ERROR", JOptionPane.ERROR_MESSAGE, null);
    } catch (IOException IOE) {
        JOptionPane.showMessageDialog(this, "Error -> " + IOE.getLocalizedMessage(), "IOExcpiton",
                JOptionPane.ERROR_MESSAGE, null);
    }

    if (POI_List.isEmpty()) {
        JOptionPane.showMessageDialog(this, "No Results");
    } else {
        //Calculate Distance every POI from Longitude and latitude of User

        for (int k = 0; k < POI_List.size(); k++) {
            double D1 = Double.parseDouble(Latitude_TextField.getText()) - POI_List.get(k).Get_Distance_X();
            double D2 = Double.parseDouble(Longitude_TextField.getText()) - POI_List.get(k).Get_Distance_Y();
            double a = pow(sin(D1 / 2), 2) + cos(POI_List.get(k).Get_Distance_X())
                    * cos(Double.parseDouble(Latitude_TextField.getText())) * pow(sin(D2 / 2), 2);
            double c = 2 * atan2(sqrt(a), sqrt(1 - a));
            double d = 70000 * c; // (where R is the radius of the Earth)  in meters
            //add to list
            Distances_List.add(d);
        }

        //COPY array because Distances_List will be corrupted
        for (int g = 0; g < Distances_List.size(); g++) {
            Distances_List_2.add(Distances_List.get(g));
        }

        for (int l = 0; l < Distances_List.size(); l++) {
            int Dou = Distances_List.indexOf(Collections.min(Distances_List)); //Take the min , but the result is the position that the min is been placed
            Number_Name N = new Number_Name(POI_List.get(Dou).Get_Name()); //Create an object  with the name of POI in the min position in the POI_List
            Temp_List.add(N);
            Distances_List.set(Dou, 9999.99); //Make the number in the min position so large so be able to find the next min
        }
        String[] T = new String[Temp_List.size()]; //String array to holds all names of POIS that are going to be dispayled in ascending order
        //DISPLAY POI IN JLIST - Create String Array with Names in ascending order to create JList
        for (int h = 0; h < Temp_List.size(); h++) {
            T[h] = Temp_List.get(h).Get_Name();
        }
        //System.out.println ( " Size T -> " + T.length ) ;
        //Make JList and put String names 
        list = new JList(T);
        list.setForeground(Color.BLACK);
        list.setBackground(Color.GRAY);
        list.setBounds(550, 140, 400, 400);
        //list.setSelectionMode ( ListSelectionModel.SINGLE_SELECTION ) ;
        JScrollPane p = new JScrollPane(list);
        P.add(p);
        setContentPane(pane);
        //OK
        list.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent event) {
                String selected = list.getSelectedValue().toString();
                System.out.println("Selected string" + selected);
                for (int n = 0; n < POI_List.size(); n++) {
                    if (selected.equals(POI_List.get(n).Get_Name())) {
                        try {
                            //read the result from the server
                            BufferedImage img = null;
                            URL u = new URL(
                                    "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference="
                                            + POI_List.get(n).Get_Photo_Ref() + "&key=" + API_KEY);
                            Image image = ImageIO.read(u);
                            IMAGE_LABEL.setText("");
                            IMAGE_LABEL.setIcon(new ImageIcon(image));
                            IMAGE_LABEL.setBounds(550, 310, 500, 200); //SOSOSOSOSOS
                            pane.add(IMAGE_LABEL);
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(),
                                    "Exception - IOException", JOptionPane.ERROR_MESSAGE, null);
                        }

                        Distance_L.setBounds(550, 460, 350, 150);
                        Distance_L.setText("");
                        Distance_L.setText(
                                "Distance from the current location: " + Distances_List_2.get(n) + "m");
                        pane.add(Distance_L);

                        Address_L.setBounds(550, 500, 350, 150);
                        Address_L.setText("");
                        Address_L.setText("Address: " + POI_List.get(n).Get_Address());
                        pane.add(Address_L);

                        Rating_L.setBounds(550, 540, 350, 150);
                        Rating_L.setText("");
                        Rating_L.setText("Rating: " + POI_List.get(n).Get_Rating());
                        pane.add(Rating_L);
                    }
                }
            }
        });
    } //Else not empty
}

From source file:edu.fullerton.ldvplugin.ExternalPlotManager.java

public double[][] rdBinXYFile(File in) throws FileNotFoundException, IOException, WebUtilException {
    ArrayList<double[]> data = new ArrayList<>();
    DataInputStream input = new DataInputStream(new FileInputStream(in));

    try {/*w  w w.ja v  a2 s . c  o  m*/
        while (true) {
            double[] it = new double[2];
            it[0] = input.readDouble();
            it[1] = input.readDouble();
            data.add(it);
        }
    } catch (EOFException eof) {
        // we're good
    } catch (IOException ex) {
        String ermsg = "Reading binary xy data from file: " + ex.getClass().getSimpleName();
        ermsg += " - " + ex.getLocalizedMessage();
        throw new WebUtilException(ermsg);
    }
    // return as array
    double[][] ret = new double[1][2];
    ret = data.toArray(ret);
    return ret;
}

From source file:net.launchpad.jabref.plugins.ZentralSearch.java

private BibtexDatabase importZentralblattEntries(String key, OutputPrinter status) {
    String url = getZentralblattUrl();
    HttpURLConnection zentralblattConnection = null;
    try {/*  w  w w .j av a 2 s  . c  o  m*/
        log.debug("Zentralblatt URL: " + url);
        URL ZBUrl = new URL(url);
        String query = constructQuery(key);

        if (StringUtils.isBlank(query)) {
            log.error("Search entry was empty.");
            status.showMessage("Please select or enter keyword");
            return null;

        }
        zentralblattConnection = (HttpURLConnection) ZBUrl.openConnection();
        zentralblattConnection.setDoOutput(true); // Triggers POST.
        zentralblattConnection.setRequestProperty("Accept-Charset", CHARSET);
        zentralblattConnection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + CHARSET);
        zentralblattConnection.setRequestProperty("User-Agent", "Jabref");

        OutputStream output = null;
        try {
            output = zentralblattConnection.getOutputStream();
            output.write(query.getBytes(CHARSET));
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException e) {
                    log.debug(e.getMessage(), e);
                }
        }

        Set<String> bibtex = fetchBibtexEntries(IOUtils.toString(zentralblattConnection.getInputStream()));
        return makeBibtexDB(bibtex);
    } catch (IOException e) {
        log.error("IO-Problem: " + e.getMessage(), e);
        status.showMessage(Globals.lang("An Exception ocurred while accessing '%0'", url) + "\n\n"
                + e.getLocalizedMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE);
    } catch (RuntimeException e) {
        log.error("General Problem: " + e.getMessage(), e);
        status.showMessage(
                Globals.lang("An Error occurred while fetching from Mathematisches Zentralblatt (%0):",
                        new String[] { url }) + "\n\n" + e.getMessage(),
                Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE);
    }
    return null;
}

From source file:cross.io.xml.FragmentXMLSerializer.java

@Override
public boolean write(final IFileFragment f) {
    try {//from  ww w.  j  a va2 s .co  m
        serialize(f);
        return true;
    } catch (final IOException ioex) {
        log.error("{}", ioex.getLocalizedMessage());
        return false;
    }
}

From source file:org.geowebcache.storage.blobstore.memory.MemoryBlobStore.java

/***
 * This method is used for converting a {@link TileObject} {@link Resource} into a {@link ByteArrayResource}.
 * //from w w w  .  ja v  a2  s.  c o m
 * @param obj
 * @return a TileObject with resource stored in a Byte Array
 * @throws StorageException
 */
private TileObject getByteResourceTile(TileObject obj) throws StorageException {
    // Get TileObject resource
    Resource blob = obj.getBlob();
    final Resource finalBlob;
    // If it is a ByteArrayResource, the result is simply copied
    if (obj.getBlob() instanceof ByteArrayResource) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resource is already a Byte Array, only a copy is needed");
        }
        ByteArrayResource byteArrayResource = (ByteArrayResource) obj.getBlob();
        byte[] contents = byteArrayResource.getContents();
        byte[] copy = new byte[contents.length];
        System.arraycopy(contents, 0, copy, 0, contents.length);
        finalBlob = new ByteArrayResource(copy);
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resource is not a Byte Array, data must be transferred");
        }
        // Else the result is written to a new WritableByteChannel
        final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        WritableByteChannel wChannel = Channels.newChannel(bOut);
        try {
            blob.transferTo(wChannel);
        } catch (IOException e) {
            throw new StorageException(e.getLocalizedMessage(), e);

        }
        finalBlob = new ByteArrayResource(bOut.toByteArray());
    }
    // Creation of a new Resource
    TileObject cached = TileObject.createCompleteTileObject(obj.getLayerName(), obj.getXYZ(),
            obj.getGridSetId(), obj.getBlobFormat(), obj.getParameters(), finalBlob);
    return cached;
}

From source file:com.nextgis.firereporter.GetFiresService.java

protected boolean writeToFile(File filePath, String sData) {
    try {/*from  w ww  .  j a  v  a2 s  . c  o  m*/
        FileOutputStream os = new FileOutputStream(filePath, false);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(os);
        outputStreamWriter.write(sData);
        outputStreamWriter.close();
        return true;
    } catch (IOException e) {
        SendError(e.getLocalizedMessage());
        return false;
    }
}