Example usage for java.net MalformedURLException getLocalizedMessage

List of usage examples for java.net MalformedURLException getLocalizedMessage

Introduction

In this page you can find the example usage for java.net MalformedURLException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

protected synchronized void loadFromExistingAccount(Account account) {
    if (account == null) {
        throw new IllegalArgumentException("must specify account");
    }/*from   ww w . java2s  .co m*/

    String baseUrlString;

    final AccountManager am = AccountManager.get(mContext);
    baseUrlString = am.getUserData(account, AuthenticationService.USERDATA_LOCAST_API_URL);
    if (baseUrlString == null) {
        Log.w(TAG, "loading base URL from preferences instead of account metadata");
        baseUrlString = getBaseUrlFromPreferences(mContext);
        // if it's null in the userdata, then it must be an account from before this feature
        // was added.
        // Store for later use.
        am.setUserData(account, AuthenticationService.USERDATA_LOCAST_API_URL, baseUrlString);
    }

    try {
        setBaseUrl(baseUrlString);

        setCredentialsFromAccount(account);

    } catch (final MalformedURLException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);

    }
}

From source file:uk.ac.ox.oucs.vle.XcriOxCapPopulatorImpl.java

/**
 * @throws  /*from ww  w .j a  v a2  s .  c  o m*/
 * @throws MalformedURLException 
 * 
 */
public void update(PopulatorContext context) throws PopulatorException {

    InputStream input = null;

    try {
        // This is so that collections don't get lost, this is a hack but I couldn't find the
        // simple fix to get it working.
        dao.setFlushMode(HibernateAccessor.FLUSH_EAGER);
        input = populatorInput.getInput(context);

        if (null == input) {
            throw new PopulatorException("No Input for Importer");
        }
        process(context, input);

    } catch (MalformedURLException e) {
        log.warn("MalformedURLException [" + context.getURI() + "]", e);
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IllegalStateException e) {
        log.warn("IllegalStateException [" + context.getURI() + "]", e);
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IOException e) {
        log.warn("IOException [" + context.getURI() + "]", e);
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (JDOMException e) {
        log.warn("JDOMException [" + context.getURI() + "]", e);
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (InvalidElementException e) {
        log.warn("InvalidElementException [" + context.getURI() + "]", e);
        throw new PopulatorException(e.getLocalizedMessage());

    } finally {
        if (null != input) {
            try {
                input.close();
            } catch (IOException e) {
                log.error("IOException [" + e + "]");
            }
        }
    }

}

From source file:de.uni.stuttgart.informatik.ToureNPlaner.UI.Activities.MapScreen.MapScreen.java

private void setupMapView(SharedPreferences preferences) {
    String newTileServer = preferences.getString("tile_server", MapScreenPreferences.defaultTileServer);
    String newOfflineMapLocation = preferences.getString("offline_map_location",
            MapScreenPreferences.defaultMapLocation);
    MapScreenPreferences.MapGenerator newMapGenerator = MapScreenPreferences.MapGenerator
            .valueOf(preferences.getString("map_generator", MapScreenPreferences.MapGenerator.MAPQUEST.name()));

    if (mapGenerator != newMapGenerator) {
        switch (newMapGenerator) {
        case MAPQUEST:
            try {
                mapView.setMapGenerator(new CustomTileDownloader(
                        new URL("http://otile1.mqcdn.com/tiles/1.0.0/osm/%1$d/%2$d/%3$d.jpg"), (byte) 18));
            } catch (MalformedURLException e) {
                // shouldn't happen
            }//from  w  ww  .  j ava  2  s.co m
            break;
        case MAPNIK:
            mapView.setMapGenerator(new MapnikTileDownloader());
            break;
        case OPENCYCLE:
            mapView.setMapGenerator(new OpenCycleMapTileDownloader());
            break;
        }
    }
    if (newMapGenerator == MapScreenPreferences.MapGenerator.CUSTOM
            && ((newMapGenerator != mapGenerator) || !tileServer.equals(newTileServer))) {
        try {
            mapView.setMapGenerator(new CustomTileDownloader(new URL(newTileServer), (byte) 17));
        } catch (MalformedURLException e) {
            mapView.setMapGenerator(new MapnikTileDownloader());
            Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    } else if (newMapGenerator == MapScreenPreferences.MapGenerator.FILE
            && ((newMapGenerator != mapGenerator) || !offlineMapLocation.equals(newOfflineMapLocation))) {
        if (mapGenerator != newMapGenerator) {
            mapView.setMapGenerator(new DatabaseRenderer());
        }
        FileOpenResult result;
        try {
            result = mapView.setMapFile(new File(newOfflineMapLocation));
        } catch (Exception e) {
            result = new FileOpenResult(getResources().getString(R.string.map_file_error));
        }
        if (!result.isSuccess()) {
            mapView.setMapGenerator(new MapnikTileDownloader());
            Toast.makeText(this, result.getErrorMessage(), Toast.LENGTH_LONG).show();
        }
    }

    ((TextView) findViewById(R.id.copyright))
            .setText(newMapGenerator == MapScreenPreferences.MapGenerator.MAPQUEST ? R.string.mapquest_copyright
                    : R.string.osm_copyright);

    tileServer = newTileServer;
    mapGenerator = newMapGenerator;
    offlineMapLocation = newOfflineMapLocation;
}

From source file:org.geotools.utils.imagemosaic.MosaicIndexBuilder.java

/**
 * Main thread for the mosaic index builder.
 */// w  w w . j  a  v  a 2s .  c  om
public void run() {

    // /////////////////////////////////////////////////////////////////////
    //
    // CREATING INDEX FILE
    //
    // /////////////////////////////////////////////////////////////////////

    // /////////////////////////////////////////////////////////////////////
    //
    // Create a file handler that write log record to a file called
    // my.log
    //
    // /////////////////////////////////////////////////////////////////////
    FileHandler handler = null;
    try {
        boolean append = true;
        handler = new FileHandler(new StringBuffer(locationPath).append("/error.txt").toString(), append);
        handler.setLevel(Level.SEVERE);
        // Add to the desired logger
        LOGGER.addHandler(handler);

        // /////////////////////////////////////////////////////////////////////
        //
        // Create a set of file names that have to be skipped since these are
        // our metadata files
        //
        // /////////////////////////////////////////////////////////////////////
        final Set<String> skipFiles = new HashSet<String>(
                Arrays.asList(new String[] { indexName + ".shp", indexName + ".dbf", indexName + ".shx",
                        indexName + ".prj", "error.txt", "error.txt.lck", indexName + ".properties" }));

        // /////////////////////////////////////////////////////////////////////
        //
        // Creating temp vars
        //
        // /////////////////////////////////////////////////////////////////////
        ShapefileDataStore index = null;
        Transaction t = new DefaultTransaction();
        // declaring a preciosion model to adhere the java double type
        // precision
        PrecisionModel precMod = new PrecisionModel(PrecisionModel.FLOATING);
        GeometryFactory geomFactory = new GeometryFactory(precMod);
        try {
            index = new ShapefileDataStore(
                    new File(locationPath + File.separator + indexName + ".shp").toURI().toURL());
        } catch (MalformedURLException ex) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            fireException(ex);
            return;
        }

        final List<File> files = new ArrayList<File>();
        recurse(files, locationPath);

        // /////////////////////////////////////////////////////////////////////
        //
        // Cycling over the files that have filtered out
        //
        // /////////////////////////////////////////////////////////////////////
        numFiles = files.size();
        String validFileName = null;
        final Iterator<File> filesIt = files.iterator();
        FeatureWriter<SimpleFeatureType, SimpleFeature> fw = null;
        boolean doneSomething = false;
        for (int i = 0; i < numFiles; i++) {

            StringBuffer message;
            // //
            //
            // Check that this file is actually good to go
            //
            // //         
            final File fileBeingProcessed = ((File) filesIt.next());
            if (!fileBeingProcessed.exists() || !fileBeingProcessed.canRead() || !fileBeingProcessed.isFile()) {
                // send a message
                message = new StringBuffer("Skipped file ").append(files.get(i))
                        .append(" snce it seems invalid.");
                if (LOGGER.isLoggable(Level.INFO))
                    LOGGER.info(message.toString());
                fireEvent(message.toString(), ((i * 99.0) / numFiles));
                continue;
            }

            // //
            //
            // Anyone has asked us to stop?
            //
            // //
            if (getStopThread()) {
                message = new StringBuffer("Stopping requested at file  ").append(i).append(" of ")
                        .append(numFiles).append(" files");
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine(message.toString());
                }
                fireEvent(message.toString(), ((i * 100.0) / numFiles));
                return;
            } // replacing chars on input path
            try {
                validFileName = fileBeingProcessed.getCanonicalPath();
            } catch (IOException e1) {
                fireException(e1);
                return;
            }
            validFileName = validFileName.replace('\\', '/');
            validFileName = validFileName.substring(locationPath.length() + 1,
                    fileBeingProcessed.getAbsolutePath().length());
            if (skipFiles.contains(validFileName))
                continue;
            message = new StringBuffer("Now indexing file ").append(validFileName);

            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine(message.toString());
            }
            fireEvent(message.toString(), ((i * 100.0) / numFiles));
            try {
                // ////////////////////////////////////////////////////////
                //
                //
                // STEP 1
                // Getting an ImageIO reader for this coverage.
                //
                //
                // ////////////////////////////////////////////////////////
                ImageInputStream inStream = ImageIO.createImageInputStream(fileBeingProcessed);
                if (inStream == null) {
                    if (LOGGER.isLoggable(Level.SEVERE))
                        LOGGER.severe(fileBeingProcessed
                                + " has been skipped since we could not get a stream for it");
                    continue;
                }
                inStream.mark();
                final Iterator<ImageReader> it = ImageIO.getImageReaders(inStream);
                ImageReader r = null;
                if (it.hasNext()) {
                    r = (ImageReader) it.next();
                    r.setInput(inStream);
                } else {
                    // release resources
                    try {
                        inStream.close();
                    } catch (Exception e) {
                        // ignore exception
                    }
                    //               try {
                    //                  r.dispose();
                    //               } catch (Exception e) {
                    //                  // ignore exception
                    //               }

                    // send a message
                    message = new StringBuffer("Skipped file ").append(files.get(i))
                            .append(":No ImageIO readeres avalaible.");
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.info(message.toString());
                    fireEvent(message.toString(), ((i * 99.0) / numFiles));
                    continue;
                }

                // ////////////////////////////////////////////////////////
                //
                // STEP 2
                // Getting a coverage reader for this coverage.
                //
                // ////////////////////////////////////////////////////////
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine(new StringBuffer("Getting a reader").toString());
                final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder
                        .findFormat(files.get(i));
                if (format == null || !format.accepts(files.get(i))) {
                    // release resources
                    try {
                        inStream.close();
                    } catch (Exception e) {
                        // ignore exception
                    }
                    try {
                        r.dispose();
                    } catch (Exception e) {
                        // ignore exception
                    }

                    message = new StringBuffer("Skipped file ").append(files.get(i))
                            .append(": File format is not supported.");
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.info(message.toString());
                    fireEvent(message.toString(), ((i * 99.0) / numFiles));
                    continue;
                }
                final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format
                        .getReader(files.get(i));
                envelope = (GeneralEnvelope) reader.getOriginalEnvelope();
                actualCRS = reader.getCrs();

                // /////////////////////////////////////////////////////////////////////
                //
                // STEP 3
                // Get the type specifier for this image and the check that the
                // image has the correct sample model and color model.
                // If this is the first cycle of the loop we initialize
                // eveything.
                //
                // /////////////////////////////////////////////////////////////////////
                final ImageTypeSpecifier its = ((ImageTypeSpecifier) r.getImageTypes(0).next());
                boolean skipFeature = false;
                if (globEnvelope == null) {
                    // /////////////////////////////////////////////////////////////////////
                    //
                    // at the first step we initialize everything that we will
                    // reuse afterwards starting with color models, sample
                    // models, crs, etc....
                    //
                    // /////////////////////////////////////////////////////////////////////
                    defaultCM = its.getColorModel();
                    if (defaultCM instanceof IndexColorModel) {
                        IndexColorModel icm = (IndexColorModel) defaultCM;
                        int numBands = defaultCM.getNumColorComponents();
                        defaultPalette = new byte[3][icm.getMapSize()];
                        icm.getReds(defaultPalette[0]);
                        icm.getGreens(defaultPalette[0]);
                        icm.getBlues(defaultPalette[0]);
                        if (numBands == 4)
                            icm.getAlphas(defaultPalette[0]);

                    }
                    defaultSM = its.getSampleModel();
                    defaultCRS = actualCRS;
                    globEnvelope = new GeneralEnvelope(envelope);

                    // /////////////////////////////////////////////////////////////////////
                    //
                    // getting information about resolution
                    //
                    // /////////////////////////////////////////////////////////////////////

                    // //
                    //
                    // get the dimension of the hr image and build the model
                    // as well as
                    // computing the resolution
                    // //
                    // resetting reader and recreating stream, turnaround for a
                    // strange imageio bug
                    r.reset();
                    try {
                        inStream.reset();
                    } catch (IOException e) {
                        inStream = ImageIO.createImageInputStream(fileBeingProcessed);
                    }
                    //let's check if we got something now
                    if (inStream == null) {
                        //skip file
                        if (LOGGER.isLoggable(Level.WARNING))
                            LOGGER.warning("Skipping file " + fileBeingProcessed.toString());
                        continue;
                    }
                    r.setInput(inStream);
                    numberOfLevels = r.getNumImages(true);
                    resolutionLevels = new double[2][numberOfLevels];
                    double[] res = getResolution(envelope, new Rectangle(r.getWidth(0), r.getHeight(0)),
                            defaultCRS);
                    resolutionLevels[0][0] = res[0];
                    resolutionLevels[1][0] = res[1];

                    // resolutions levels
                    if (numberOfLevels > 1) {

                        for (int k = 0; k < numberOfLevels; k++) {
                            res = getResolution(envelope, new Rectangle(r.getWidth(k), r.getHeight(k)),
                                    defaultCRS);
                            resolutionLevels[0][k] = res[0];
                            resolutionLevels[1][k] = res[1];
                        }
                    }

                    // /////////////////////////////////////////////////////////////////////
                    //
                    // creating the schema
                    //
                    // /////////////////////////////////////////////////////////////////////
                    final SimpleFeatureTypeBuilder featureBuilder = new SimpleFeatureTypeBuilder();
                    featureBuilder.setName("Flag");
                    featureBuilder.setNamespaceURI("http://www.geo-solutions.it/");
                    featureBuilder.add("location", String.class);
                    featureBuilder.add("the_geom", Polygon.class, this.actualCRS);
                    featureBuilder.setDefaultGeometry("the_geom");
                    final SimpleFeatureType simpleFeatureType = featureBuilder.buildFeatureType();
                    // create the schema for the new shape file
                    index.createSchema(simpleFeatureType);

                    // get a feature writer
                    fw = index.getFeatureWriter(t);
                } else {
                    // ////////////////////////////////////////////////////////
                    // 
                    // comparing ColorModel
                    // comparing SampeModel
                    // comparing CRSs
                    // ////////////////////////////////////////////////////////
                    globEnvelope.add(envelope);
                    actualCM = its.getColorModel();
                    actualSM = its.getSampleModel();
                    skipFeature = (i > 0 ? !(CRS.equalsIgnoreMetadata(defaultCRS, actualCRS)) : false);
                    if (skipFeature)
                        LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i))
                                .append(" because CRSs do not match.").toString());
                    skipFeature = checkColorModels(defaultCM, defaultPalette, actualCM);
                    if (skipFeature)
                        LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i))
                                .append(" because color models do not match.").toString());
                    // defaultCM.getNumComponents()==actualCM.getNumComponents()&&
                    // defaultCM.getClass().equals(actualCM.getClass())
                    // && defaultSM.getNumBands() == actualSM
                    // .getNumBands()
                    // && defaultSM.getDataType() == actualSM
                    // .getDataType() &&
                    //
                    // if (skipFeature)
                    // LOGGER
                    // .warning(new StringBuffer("Skipping image ")
                    // .append(files.get(i))
                    // .append(
                    // " because cm or sm does not match.")
                    // .toString());
                    // res = getResolution(envelope, new
                    // Rectangle(r.getWidth(0),
                    // r.getHeight(0)), defaultCRS);
                    // if (Math.abs((resX - res[0]) / resX) > EPS
                    // || Math.abs(resY - res[1]) > EPS) {
                    // LOGGER.warning(new StringBuffer("Skipping image
                    // ").append(
                    // files.get(i)).append(
                    // " because resolutions does not match.")
                    // .toString());
                    // skipFeature = true;
                    // }
                }

                // ////////////////////////////////////////////////////////
                //
                // STEP 4
                //
                // create and store features
                //
                // ////////////////////////////////////////////////////////
                if (!skipFeature) {

                    final SimpleFeature feature = fw.next();
                    feature.setAttribute(1,
                            geomFactory.toGeometry(new ReferencedEnvelope((Envelope) envelope)));
                    feature.setAttribute(
                            0, absolute
                                    ? new StringBuilder(this.locationPath).append(File.separatorChar)
                                            .append(validFileName).toString()
                                    : validFileName);
                    fw.write();

                    message = new StringBuffer("Done with file ").append(files.get(i));
                    if (LOGGER.isLoggable(Level.FINE)) {
                        LOGGER.fine(message.toString());
                    }
                    message.append('\n');
                    fireEvent(message.toString(), (((i + 1) * 99.0) / numFiles));
                    doneSomething = true;
                } else
                    skipFeature = false;

                // ////////////////////////////////////////////////////////
                //
                // STEP 5
                //
                // release resources
                //
                // ////////////////////////////////////////////////////////
                try {
                    inStream.close();
                } catch (Exception e) {
                    // ignore exception
                }
                try {
                    r.dispose();
                } catch (Exception e) {
                    // ignore exception
                }
                // release resources
                reader.dispose();

            } catch (IOException e) {
                fireException(e);
                break;
            } catch (ArrayIndexOutOfBoundsException e) {
                fireException(e);
                break;
            }

        }
        try {
            if (fw != null)
                fw.close();
            t.commit();
            t.close();
            index.dispose();
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
        createPropertiesFiles(globEnvelope, doneSomething);
    } catch (SecurityException el) {
        fireException(el);
        return;
    } catch (IOException el) {
        fireException(el);
        return;
    } finally {
        try {
            if (handler != null)
                handler.close();
        } catch (Throwable e) {
            // ignore
        }

    }

}

From source file:com.salesmanBuddy.dao.JDBCSalesmanBuddyDAO.java

public GoogleUserInfo getGoogleUserInfo(String token) throws GoogleUserInfoException {
    URL url;//  w w w . j  a  v a2s.  c o m
    byte[] body = null;
    JSONObject json = null;
    String whatItHas = "";
    try {
        url = new URL(GoogleUserEndpoint);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");

        conn.setRequestProperty("Authorization", token);
        whatItHas = conn.getRequestProperty("Authorization");

        body = IOUtils.toByteArray(conn.getInputStream());
        json = new JSONObject(new String(body));

    } catch (ProtocolException pe) {
        throw new RuntimeException("protocolExceptions: " + pe.getLocalizedMessage());
    } catch (MalformedURLException e) {
        throw new RuntimeException("malformedUrlException: " + e.getLocalizedMessage());
    } catch (IOException e) {
        throw new RuntimeException("IOException: " + e.getLocalizedMessage() + ", token:" + token + ", auth:"
                + whatItHas + ", json: " + json + ", e: " + e);
    } catch (JSONException jse) {
        throw new RuntimeException("JSONException: " + jse.getLocalizedMessage());
    }
    GoogleUserInfo gui = new GoogleUserInfo(json);
    return gui;
}

From source file:com.salesmanBuddy.dao.JDBCSalesmanBuddyDAO.java

private String postRequest(String postData, String baseUrl, String contentType) {

    // Connect to google.com
    URL url;/*from  w w w .jav a2s .co m*/
    StringBuilder responseSB = new StringBuilder();
    try {
        url = new URL(baseUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Content-Length", String.valueOf(postData.length()));
        //      connection.setRequestProperty("Accept", "application/json");

        // Write data
        OutputStream os = connection.getOutputStream();
        os.write(postData.getBytes());

        // Read response

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line;
        while ((line = br.readLine()) != null)
            responseSB.append(line);

        // Close streams
        br.close();
        os.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getLocalizedMessage());
    } catch (ProtocolException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getLocalizedMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getLocalizedMessage());
    }

    return responseSB.toString();
}

From source file:com.salesmanBuddy.dao.JDBCSalesmanBuddyDAO.java

public GoogleToken getValidTokenForUser(String googleUserId, Users user)
        throws GoogleRefreshTokenResponseException {
    if (user == null)
        user = this.getUserByGoogleId(googleUserId);

    GoogleToken gt = this.getTokenForUserFromCache(user.getId());
    if (gt != null)
        return gt;

    String iosString = "client_secret=" + GoogleClientSecretiOS + "&grant_type=refresh_token"
            + "&refresh_token=" + user.getRefreshToken() + "&client_id=" + GoogleClientIdiOS;
    String webString = "refresh_token=" + user.getRefreshToken() + "&client_id=" + GoogleClientIdWeb
            + "&client_secret=" + GoogleClientSecretWeb + "&grant_type=refresh_token";
    String androidString = "refresh_token=" + user.getRefreshToken() + "&client_id=" + GoogleClientIdAndroid
            + "&client_secret=" + GoogleClientSecretAndroid + "&grant_type=refresh_token";

    /*/*from  w  ww.  j a va 2  s.  c  om*/
     * 
     * client_id=8819981768.apps.googleusercontent.com&
    client_secret={client_secret}&
    refresh_token=1/6BMfW9j53gdGImsiyUH5kU5RsR4zwI9lUVX-tqf8JXQ&
    grant_type=refresh_token
            
            
            
    url: https://accounts.google.com/o/oauth2/auth, params:access_type=offline&client_id=38235450166-dgbh1m7aaab7kopia2upsdj314odp8fc.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.me%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email
     */
    byte[] body = null;

    if (user.getDeviceType() == 1)
        body = iosString.getBytes();
    else if (user.getDeviceType() == 2)
        body = webString.getBytes();
    else if (user.getDeviceType() == 3)
        body = androidString.getBytes();
    else
        throw new RuntimeException("the user's device type doesnt conform to any known types, their type: "
                + user.getDeviceType());

    URL url;
    JSONObject json = null;
    try {
        url = new URL(GoogleRefreshTokenEndpoint);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setFixedLengthStreamingMode(body.length);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.getOutputStream().write(body);
        body = IOUtils.toByteArray(conn.getInputStream());
        json = new JSONObject(new String(body));
    } catch (MalformedURLException e) {
        throw new RuntimeException("malformedUrlException: " + e.getLocalizedMessage());
    } catch (IOException e) {
        // TODO make this error handling more comprehensive, if refreshtoken is invalid we need to be able to handle it
        JDBCSalesmanBuddyDAO.sendErrorToMe("couldnt exchange refresh token for googleUserId: " + googleUserId
                + ", error: " + e.getLocalizedMessage());
        String jsonString = "";
        throw new RuntimeException("!IOException: " + e.getLocalizedMessage() + ", deviceType:"
                + user.getDeviceType() + ", " + new String(body) + ", json: " + jsonString);
    } catch (JSONException jse) {
        throw new RuntimeException("JSONException: " + jse.getLocalizedMessage());
    }

    GoogleRefreshTokenResponse grtr = new GoogleRefreshTokenResponse(json);
    // put token in database for caching
    this.saveGoogleTokenInCache(grtr, user);
    return this.getTokenForUserFromCache(user.getId());
}

From source file:Main.java

@SuppressWarnings("resource")
public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) {
    Logd(TAG, "Starting post...");
    String html = "";
    Boolean cont = true;/*from  w w  w . j  a  v  a 2s .  c  o  m*/
    URL url = null;
    try {
        url = new URL(targetUrl);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Invalid url: " + targetUrl);
        cont = false;
        throw new IllegalArgumentException("Invalid url: " + targetUrl);
    }
    if (cont) {
        if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        } else {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }
            } };
            // Install the all-trusting trust manager
            SSLContext sc;
            try {
                sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                // Create all-trusting host name verifier
                HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                };
                // Install the all-trusting host verifier
                HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            } catch (NoSuchAlgorithmException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            } catch (KeyManagementException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            }
        }
        Logd(TAG, "Filename: " + file);
        Logd(TAG, "URL: " + targetUrl);
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        String pathToOurFile = file;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024;
        try {
            connection = (HttpURLConnection) url.openConnection();
            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header)
            //connection.setChunkedStreamingMode(1024);
            // Enable POST method
            connection.setRequestMethod("POST");
            setBasicAuthentication(connection, url);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            outputStream = new DataOutputStream(connection.getOutputStream());
            //outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> param = iterator.next();
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\""
                        + lineEnd + lineEnd);
                outputStream.write(param.getValue().getBytes("UTF-8"));
                outputStream.writeBytes(lineEnd);
            }
            String connstr = null;
            if (!file.equals("")) {
                FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\""
                        + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    while (bytesRead > 0) {
                        try {
                            outputStream.write(buffer, 0, bufferSize);
                        } catch (OutOfMemoryError e) {
                            e.printStackTrace();
                            html = "Error: outofmemoryerror";
                            return html;
                        }
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
                fileInputStream.close();
            } else if (data != null) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = data.length;
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    outputStream.write(data, 0, data.length);
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    html = "Error: outofmemoryerror";
                    return html;
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
            }
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();
            Logd(TAG, "Server Response Code " + serverResponseCode);
            Logd(TAG, "Server Response Message: " + serverResponseMessage);
            if (serverResponseCode == 200) {
                InputStreamReader in = new InputStreamReader(connection.getInputStream());
                BufferedReader br = new BufferedReader(in);
                String decodedString;
                while ((decodedString = br.readLine()) != null) {
                    html += decodedString;
                }
                in.close();
            }
            outputStream.flush();
            outputStream.close();
            outputStream = null;
        } catch (Exception ex) {
            // Exception handling
            html = "Error: Unknown error";
            Logd(TAG, "Send file Exception: " + ex.getMessage());
        }
    }
    if (html.startsWith("success:"))
        Logd(TAG, "Server returned: success:HIDDEN");
    else
        Logd(TAG, "Server returned: " + html);
    return html;
}

From source file:org.methodize.nntprss.admin.AdminServlet.java

private void cmdAddChannel(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ChannelManager channelManager = (ChannelManager) getServletContext()
            .getAttribute(AdminServer.SERVLET_CTX_RSS_MANAGER);

    NNTPServer nntpServer = (NNTPServer) getServletContext().getAttribute(AdminServer.SERVLET_CTX_NNTP_SERVER);

    String name = request.getParameter("name").trim();
    String urlString = request.getParameter("url").trim();
    //      boolean historical = isChecked(request, "historical");
    boolean validate = isChecked(request, "validate");
    long expiration = Long.parseLong(request.getParameter("expiration"));
    int categoryId = Integer.parseInt(request.getParameter("categoryId"));

    List errors = new ArrayList();
    if (name.length() == 0) {
        errors.add("Name cannot be empty");
    } else if (name.indexOf(' ') > -1) {
        errors.add("Name cannot contain spaces");
    } else if (channelManager.channelByName(name) != null || channelManager.categoryByName(name) != null) {
        errors.add("Name is already is use");
    }/*from w  w  w . ja v a  2  s.  c  o m*/

    if (urlString.length() == 0) {
        errors.add("URL cannot be empty");
    } else if (urlString.equals("http://") || urlString.equals("https://")) {
        errors.add("You must specify a URL");
    } else if (!urlString.startsWith("http://") && !urlString.startsWith("https://")) {
        errors.add("Only URLs starting http:// or https:// are supported");
    }

    Channel newChannel = null;
    if (errors.size() == 0) {
        try {
            newChannel = new Channel(name, urlString);
            //            newChannel.setHistorical(historical);
            newChannel.setExpiration(expiration);
            if (validate && !newChannel.isValid()) {
                errors.add("URL does not point to valid RSS or ATOM document");
                errors.add("<a target='validate' href='http://feedvalidator.org/check?url=" + urlString
                        + "'>Check the URL with the RSS and ATOM Validator @ archive.org</a>");
                newChannel = null;
            }
        } catch (HttpUserException hue) {
            if (hue.getStatus() == HttpStatus.SC_UNAUTHORIZED) {
                errors.add("This feed requires user name and password authentication.");
                errors.add("Please specify User Name and Password in the URL, e.g.");
                errors.add("http://username:password@www.myhost.com/");
            } else if (hue.getStatus() == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                errors.add("You are using a proxy server that requires authentication.");
                errors.add(
                        "Please enter your User Name and Password in the <a href='?action=showconfig'>System Configuration.</a>");
            }
        } catch (MalformedURLException me) {
            errors.add("URL is malformed (" + me.getLocalizedMessage() + ")");
        }
    }

    Writer writer = response.getWriter();
    writeHeader(writer, TAB_ADD_CHANNEL);

    if (errors.size() > 0) {
        writer.write("<b>There were errors adding your channel:</b><p>");
        writeErrors(writer, errors);
        writer.write("<p>");
        writer.write("<form action='/?action=add' method='post'>");
        writer.write("<table class='tableborder'>");

        writer.write("<tr><th colspan='2'>Add Channel</th></tr>");
        writer.write(
                "<tr><td class='row1' align='right'>Newsgroup Name:</td><td class='row2'><input type='text' name='name' size='64' value='"
                        + HTMLHelper.escapeString(name) + "'></td></tr>");
        writer.write(
                "<tr><td class='row1' align='right'>Feed URL:</td><td class='row2'><input type='text' name='url' size='64' value='"
                        + HTMLHelper.escapeString(urlString)
                        + "'><br><i>(nntp//rss supports both RSS and ATOM feeds)</i></td></tr>");

        //         writer.write("<tr><td class='row1' align='right' valign='top'>Historical</td><td class='row2'><input type='checkbox' value='true' name='historical' "
        //            + (historical ? "checked" : "")
        //            + ">"
        //            + "<br><i>(Checked = Keep items removed from the original RSS document)</i></td></tr>");

        writer.write("<tr><td class='row1' align='right' valign='top'>Item Expiration</td><td class='row2'>");

        writer.write("<select name='expiration'>");
        writeOption(writer, "Keep all items", Channel.EXPIRATION_KEEP, expiration);
        writeOption(writer, "Keep only current items", 0, expiration);
        writeOption(writer, "Keep items for 1 day", (1000 * 60 * 60 * 24 * 1), expiration);
        writeOption(writer, "Keep items for 2 days", (1000 * 60 * 60 * 24 * 2), expiration);
        writeOption(writer, "Keep items for 4 days", (1000 * 60 * 60 * 24 * 4), expiration);
        writeOption(writer, "Keep items for 1 week", (1000 * 60 * 60 * 24 * 7), expiration);
        writeOption(writer, "Keep items for 2 weeks", (1000 * 60 * 60 * 24 * 14), expiration);
        writeOption(writer, "Keep items for 4 weeks", (1000 * 60 * 60 * 24 * 28), expiration);

        writer.write("</select></td></tr>");

        writer.write(
                "<tr><td class='row1' align='right' valign='top'>Validate</td><td class='row2'><input type='checkbox'  value='true' name='validate' "
                        + (validate ? "checked" : "") + ">"
                        + "<br><i>(Checked = Ensure URL points to a valid RSS document)</i></td></tr>");

        writer.write("<tr><td class='row1' align='right'>Category</td>");
        writer.write("<td class='row2'><select name='categoryId'>");

        writeOption(writer, "[No Category]", 0, categoryId);
        Iterator categories = channelManager.categories();
        while (categories.hasNext()) {
            Category category = (Category) categories.next();
            writeOption(writer, category.getName(), category.getId(), categoryId);
        }
        writer.write("</select></td></tr>");

        writer.write(
                "<tr><td class='row2' align='center' colspan='2'><input type='submit' value='Add'> <input type='reset'></td></tr></table>");
        writer.write("</form>");
    } else {
        channelManager.addChannel(newChannel);
        if (categoryId != 0) {
            Category category = channelManager.categoryById(categoryId);
            category.addChannel(newChannel);
            newChannel.setCategory(category);
            newChannel.save();
        }

        writer.write("Channel " + newChannel.getName() + " successfully added.<p>");

        writer.write("<a href='" + getNewsURLPrefix(nntpServer) + newChannel.getName() + "'>"
                + "[View the channel in your newsreader]</a>");
    }

    writeFooter(writer);
    writer.flush();

}

From source file:it.geosolutions.geoserver.rest.GeoServerRESTPublisher.java

/**
 * Remove a layer group./*from  w ww  . j a v  a  2s . c o m*/
 * 
 * @param workspace the layer group workspace.
 * @param name the layer group name.
 * @return true if succeeded.
 */
public boolean removeLayerGroup(String workspace, String name) {
    String url = restURL + "/rest";
    if (workspace == null) {
        url += "/layergroups/" + name;
    } else {
        url += "/workspaces/" + workspace + "/layergroups/" + name;
    }

    try {
        URL deleteUrl = new URL(url);
        boolean deleted = HTTPUtils.delete(deleteUrl.toExternalForm(), gsuser, gspass);
        if (!deleted) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn("Could not delete layergroup " + name);
        } else {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Layergroup successfully deleted: " + name);
        }

        return deleted;
    } catch (MalformedURLException ex) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error(ex.getLocalizedMessage(), ex);
        return false;
    }
}