Search in sources :

Example 41 with MalformedURLException

use of java.net.MalformedURLException in project iosched by google.

the class BasicNetwork method performRequest.

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        try {
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry() == null ? null : request.getCacheEntry().data, responseHeaders, true);
            }
            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);
            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) ServerError(com.android.volley.ServerError) HttpResponse(org.apache.http.HttpResponse) AuthFailureError(com.android.volley.AuthFailureError) NetworkError(com.android.volley.NetworkError) NoConnectionError(com.android.volley.NoConnectionError) IOException(java.io.IOException) TimeoutError(com.android.volley.TimeoutError) StatusLine(org.apache.http.StatusLine) SocketTimeoutException(java.net.SocketTimeoutException) NetworkResponse(com.android.volley.NetworkResponse) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 42 with MalformedURLException

use of java.net.MalformedURLException in project j2objc by google.

the class URLTest method testIPv6WithoutSquareBrackets.

public void testIPv6WithoutSquareBrackets() throws Exception {
    try {
        new URL("http://fe80::1234/");
        fail();
    } catch (MalformedURLException expected) {
    }
    URL url = new URL("http", "fe80::1234", "/");
    assertEquals("[fe80::1234]", url.getHost());
}
Also used : MalformedURLException(java.net.MalformedURLException) URL(java.net.URL)

Example 43 with MalformedURLException

use of java.net.MalformedURLException in project j2objc by google.

the class URLTest method testSquareBracketsWithIPv4.

public void testSquareBracketsWithIPv4() throws Exception {
    try {
        new URL("http://[192.168.0.1]/");
        fail();
    } catch (MalformedURLException expected) {
    }
    URL url = new URL("http", "[192.168.0.1]", "/");
    assertEquals("[192.168.0.1]", url.getHost());
}
Also used : MalformedURLException(java.net.MalformedURLException) URL(java.net.URL)

Example 44 with MalformedURLException

use of java.net.MalformedURLException in project react-native-image-picker by marcshilling.

the class ImagePickerModule method onActivityResult.

@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
    //robustness code
    if (callback == null || (cameraCaptureURI == null && requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE) || (requestCode != REQUEST_LAUNCH_IMAGE_CAPTURE && requestCode != REQUEST_LAUNCH_IMAGE_LIBRARY && requestCode != REQUEST_LAUNCH_VIDEO_LIBRARY && requestCode != REQUEST_LAUNCH_VIDEO_CAPTURE)) {
        return;
    }
    responseHelper.cleanResponse();
    // user cancel
    if (resultCode != Activity.RESULT_OK) {
        responseHelper.invokeCancel(callback);
        callback = null;
        return;
    }
    Uri uri;
    switch(requestCode) {
        case REQUEST_LAUNCH_IMAGE_CAPTURE:
            uri = cameraCaptureURI;
            this.fileScan(uri.getPath());
            break;
        case REQUEST_LAUNCH_IMAGE_LIBRARY:
            uri = data.getData();
            break;
        case REQUEST_LAUNCH_VIDEO_LIBRARY:
            responseHelper.putString("uri", data.getData().toString());
            responseHelper.putString("path", getRealPathFromURI(data.getData()));
            responseHelper.invokeResponse(callback);
            callback = null;
            return;
        case REQUEST_LAUNCH_VIDEO_CAPTURE:
            final String path = getRealPathFromURI(data.getData());
            responseHelper.putString("uri", data.getData().toString());
            responseHelper.putString("path", path);
            this.fileScan(path);
            responseHelper.invokeResponse(callback);
            callback = null;
            return;
        default:
            uri = null;
    }
    String realPath = getRealPathFromURI(uri);
    boolean isUrl = false;
    if (realPath != null) {
        try {
            URL url = new URL(realPath);
            isUrl = true;
        } catch (MalformedURLException e) {
        // not a url
        }
    }
    // image isn't in memory cache
    if (realPath == null || isUrl) {
        try {
            File file = createFileFromURI(uri);
            realPath = file.getAbsolutePath();
            uri = Uri.fromFile(file);
        } catch (Exception e) {
            // image not in cache
            responseHelper.putString("error", "Could not read photo");
            responseHelper.putString("uri", uri.toString());
            responseHelper.invokeResponse(callback);
            callback = null;
            return;
        }
    }
    int currentRotation = 0;
    try {
        ExifInterface exif = new ExifInterface(realPath);
        // extract lat, long, and timestamp and add to the response
        float[] latlng = new float[2];
        exif.getLatLong(latlng);
        float latitude = latlng[0];
        float longitude = latlng[1];
        if (latitude != 0f || longitude != 0f) {
            responseHelper.putDouble("latitude", latitude);
            responseHelper.putDouble("longitude", longitude);
        }
        final String timestamp = exif.getAttribute(ExifInterface.TAG_DATETIME);
        final SimpleDateFormat exifDatetimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        try {
            final String isoFormatString = new StringBuilder(isoFormat.format(exifDatetimeFormat.parse(timestamp))).append("Z").toString();
            responseHelper.putString("timestamp", isoFormatString);
        } catch (Exception e) {
        }
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        boolean isVertical = true;
        switch(orientation) {
            case ExifInterface.ORIENTATION_ROTATE_270:
                isVertical = false;
                currentRotation = 270;
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                isVertical = false;
                currentRotation = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                currentRotation = 180;
                break;
        }
        responseHelper.putInt("originalRotation", currentRotation);
        responseHelper.putBoolean("isVertical", isVertical);
    } catch (IOException e) {
        e.printStackTrace();
        responseHelper.invokeError(callback, e.getMessage());
        callback = null;
        return;
    }
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(realPath, options);
    int initialWidth = options.outWidth;
    int initialHeight = options.outHeight;
    // don't create a new file if contraint are respected
    if (((initialWidth < maxWidth && maxWidth > 0) || maxWidth == 0) && ((initialHeight < maxHeight && maxHeight > 0) || maxHeight == 0) && quality == 100 && (rotation == 0 || currentRotation == rotation)) {
        responseHelper.putInt("width", initialWidth);
        responseHelper.putInt("height", initialHeight);
    } else {
        File resized = getResizedImage(realPath, initialWidth, initialHeight);
        if (resized == null) {
            responseHelper.putString("error", "Can't resize the image");
        } else {
            realPath = resized.getAbsolutePath();
            uri = Uri.fromFile(resized);
            BitmapFactory.decodeFile(realPath, options);
            responseHelper.putInt("width", options.outWidth);
            responseHelper.putInt("height", options.outHeight);
        }
    }
    if (saveToCameraRoll && requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE) {
        final File oldFile = new File(uri.getPath());
        final File newDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        final File newFile = new File(newDir.getPath(), uri.getLastPathSegment());
        try {
            moveFile(oldFile, newFile);
            uri = Uri.fromFile(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            responseHelper.putString("error", "Error moving image to camera roll: " + e.getMessage());
        }
    }
    responseHelper.putString("uri", uri.toString());
    responseHelper.putString("path", realPath);
    if (!noData) {
        responseHelper.putString("data", getBase64StringFromFile(realPath));
    }
    putExtraFileInfo(realPath, responseHelper);
    responseHelper.invokeResponse(callback);
    callback = null;
    this.options = null;
}
Also used : Options(android.graphics.BitmapFactory.Options) MalformedURLException(java.net.MalformedURLException) Options(android.graphics.BitmapFactory.Options) ExifInterface(android.media.ExifInterface) IOException(java.io.IOException) Uri(android.net.Uri) URL(java.net.URL) FileNotFoundException(java.io.FileNotFoundException) ActivityNotFoundException(android.content.ActivityNotFoundException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) BitmapFactory(android.graphics.BitmapFactory) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 45 with MalformedURLException

use of java.net.MalformedURLException in project CoreNLP by stanfordnlp.

the class ParseFiles method parseFiles.

public void parseFiles(String[] args, int argIndex, boolean tokenized, TokenizerFactory<? extends HasWord> tokenizerFactory, String elementDelimiter, String sentenceDelimiter, Function<List<HasWord>, List<HasWord>> escaper, String tagDelimiter) {
    final DocType docType = (elementDelimiter == null) ? DocType.Plain : DocType.XML;
    if (op.testOptions.verbose) {
        if (tokenizerFactory != null)
            pwErr.println("parseFiles: Tokenizer factory is: " + tokenizerFactory);
    }
    final Timing timer = new Timing();
    //Loop over the files
    for (int i = argIndex; i < args.length; i++) {
        final String filename = args[i];
        final DocumentPreprocessor documentPreprocessor;
        if (filename.equals("-")) {
            try {
                documentPreprocessor = new DocumentPreprocessor(IOUtils.readerFromStdin(op.tlpParams.getInputEncoding()), docType);
            } catch (IOException e) {
                throw new RuntimeIOException(e);
            }
        } else {
            documentPreprocessor = new DocumentPreprocessor(filename, docType, op.tlpParams.getInputEncoding());
        }
        //Unused values are null per the main() method invocation below
        //null is the default for these properties
        documentPreprocessor.setSentenceFinalPuncWords(tlp.sentenceFinalPunctuationWords());
        documentPreprocessor.setEscaper(escaper);
        documentPreprocessor.setSentenceDelimiter(sentenceDelimiter);
        documentPreprocessor.setTagDelimiter(tagDelimiter);
        documentPreprocessor.setElementDelimiter(elementDelimiter);
        if (tokenizerFactory == null)
            documentPreprocessor.setTokenizerFactory((tokenized) ? null : tlp.getTokenizerFactory());
        else
            documentPreprocessor.setTokenizerFactory(tokenizerFactory);
        //Setup the output
        PrintWriter pwo = pwOut;
        if (op.testOptions.writeOutputFiles) {
            String normalizedName = filename;
            try {
                // this will exception if not a URL
                new URL(normalizedName);
                normalizedName = normalizedName.replaceAll("/", "_");
            } catch (MalformedURLException e) {
            //It isn't a URL, so silently ignore
            }
            String ext = (op.testOptions.outputFilesExtension == null) ? "stp" : op.testOptions.outputFilesExtension;
            String fname = normalizedName + '.' + ext;
            if (op.testOptions.outputFilesDirectory != null && !op.testOptions.outputFilesDirectory.isEmpty()) {
                String fseparator = System.getProperty("file.separator");
                if (fseparator == null || fseparator.isEmpty()) {
                    fseparator = "/";
                }
                File fnameFile = new File(fname);
                fname = op.testOptions.outputFilesDirectory + fseparator + fnameFile.getName();
            }
            try {
                pwo = op.tlpParams.pw(new FileOutputStream(fname));
            } catch (IOException ioe) {
                throw new RuntimeIOException(ioe);
            }
        }
        treePrint.printHeader(pwo, op.tlpParams.getOutputEncoding());
        pwErr.println("Parsing file: " + filename);
        int num = 0;
        int numProcessed = 0;
        if (op.testOptions.testingThreads != 1) {
            MulticoreWrapper<List<? extends HasWord>, ParserQuery> wrapper = new MulticoreWrapper<>(op.testOptions.testingThreads, new ParsingThreadsafeProcessor(pqFactory, pwErr));
            for (List<HasWord> sentence : documentPreprocessor) {
                num++;
                numSents++;
                int len = sentence.size();
                numWords += len;
                pwErr.println("Parsing [sent. " + num + " len. " + len + "]: " + SentenceUtils.listToString(sentence, true));
                wrapper.put(sentence);
                while (wrapper.peek()) {
                    ParserQuery pq = wrapper.poll();
                    processResults(pq, numProcessed++, pwo);
                }
            }
            wrapper.join();
            while (wrapper.peek()) {
                ParserQuery pq = wrapper.poll();
                processResults(pq, numProcessed++, pwo);
            }
        } else {
            ParserQuery pq = pqFactory.parserQuery();
            for (List<HasWord> sentence : documentPreprocessor) {
                num++;
                numSents++;
                int len = sentence.size();
                numWords += len;
                pwErr.println("Parsing [sent. " + num + " len. " + len + "]: " + SentenceUtils.listToString(sentence, true));
                pq.parseAndReport(sentence, pwErr);
                processResults(pq, numProcessed++, pwo);
            }
        }
        treePrint.printFooter(pwo);
        if (op.testOptions.writeOutputFiles)
            pwo.close();
        pwErr.println("Parsed file: " + filename + " [" + num + " sentences].");
    }
    long millis = timer.stop();
    if (summary) {
        if (pcfgLL != null)
            pcfgLL.display(false, pwErr);
        if (depLL != null)
            depLL.display(false, pwErr);
        if (factLL != null)
            factLL.display(false, pwErr);
    }
    if (saidMemMessage) {
        ParserUtils.printOutOfMemory(pwErr);
    }
    double wordspersec = numWords / (((double) millis) / 1000);
    double sentspersec = numSents / (((double) millis) / 1000);
    // easier way!
    NumberFormat nf = new DecimalFormat("0.00");
    pwErr.println("Parsed " + numWords + " words in " + numSents + " sentences (" + nf.format(wordspersec) + " wds/sec; " + nf.format(sentspersec) + " sents/sec).");
    if (numFallback > 0) {
        pwErr.println("  " + numFallback + " sentences were parsed by fallback to PCFG.");
    }
    if (numUnparsable > 0 || numNoMemory > 0 || numSkipped > 0) {
        pwErr.println("  " + (numUnparsable + numNoMemory + numSkipped) + " sentences were not parsed:");
        if (numUnparsable > 0) {
            pwErr.println("    " + numUnparsable + " were not parsable with non-zero probability.");
        }
        if (numNoMemory > 0) {
            pwErr.println("    " + numNoMemory + " were skipped because of insufficient memory.");
        }
        if (numSkipped > 0) {
            pwErr.println("    " + numSkipped + " were skipped as length 0 or greater than " + op.testOptions.maxLength);
        }
    }
}
Also used : HasWord(edu.stanford.nlp.ling.HasWord) RuntimeIOException(edu.stanford.nlp.io.RuntimeIOException) MalformedURLException(java.net.MalformedURLException) MulticoreWrapper(edu.stanford.nlp.util.concurrent.MulticoreWrapper) DecimalFormat(java.text.DecimalFormat) RuntimeIOException(edu.stanford.nlp.io.RuntimeIOException) IOException(java.io.IOException) URL(java.net.URL) ParsingThreadsafeProcessor(edu.stanford.nlp.parser.common.ParsingThreadsafeProcessor) FileOutputStream(java.io.FileOutputStream) List(java.util.List) Timing(edu.stanford.nlp.util.Timing) DocumentPreprocessor(edu.stanford.nlp.process.DocumentPreprocessor) File(java.io.File) DocType(edu.stanford.nlp.process.DocumentPreprocessor.DocType) PrintWriter(java.io.PrintWriter) ParserQuery(edu.stanford.nlp.parser.common.ParserQuery) NumberFormat(java.text.NumberFormat)

Aggregations

MalformedURLException (java.net.MalformedURLException)1597 URL (java.net.URL)1204 IOException (java.io.IOException)482 File (java.io.File)405 ArrayList (java.util.ArrayList)168 InputStream (java.io.InputStream)135 HttpURLConnection (java.net.HttpURLConnection)131 HashMap (java.util.HashMap)100 URISyntaxException (java.net.URISyntaxException)98 URI (java.net.URI)95 Map (java.util.Map)80 URLClassLoader (java.net.URLClassLoader)77 InputStreamReader (java.io.InputStreamReader)75 BufferedReader (java.io.BufferedReader)72 URLConnection (java.net.URLConnection)62 FileNotFoundException (java.io.FileNotFoundException)59 Test (org.junit.Test)54 HashSet (java.util.HashSet)53 UnsupportedEncodingException (java.io.UnsupportedEncodingException)44 JSONException (org.json.JSONException)40