Example usage for java.io UnsupportedEncodingException getClass

List of usage examples for java.io UnsupportedEncodingException getClass

Introduction

In this page you can find the example usage for java.io UnsupportedEncodingException getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:wjhk.jupload2.upload.FileUploadThreadHTTP.java

/**
 * Returns the header for this file, within the http multipart body.
 * /*from   www  .jav  a 2 s.  c  om*/
 * @param numInCurrentUpload Index of the file in the array that contains
 *            all files to upload.
 * @param bound The boundary that separate files in the http multipart post
 *            body.
 * @param chunkPart The numero of the current chunk (from 1 to n)
 * @return The encoded header for this file. The {@link ByteArrayEncoder} is
 *         closed within this method.
 * @throws JUploadException
 */
private final ByteArrayEncoder getFileHeader(UploadFileData uploadFileData, int numInCurrentUpload,
        String bound, int chunkPart) throws JUploadException {
    String filenameEncoding = this.uploadPolicy.getFilenameEncoding();
    String mimetype = uploadFileData.getMimeType();
    String uploadFilename = uploadFileData.getUploadFilename(numInCurrentUpload);
    ByteArrayEncoder bae = new ByteArrayEncoderHTTP(this.uploadPolicy, bound);

    if (numInCurrentUpload == 0) {
        // Only once when uploading multiple files in same request.
        // We'll encode the output stream into UTF-8.
        String form = this.uploadPolicy.getFormdata();
        if (null != form) {
            bae.appendFormVariables(form);
        }
    }
    // We ask the current FileData to add itself its properties.
    uploadFileData.appendFileProperties(bae, numInCurrentUpload);

    // boundary.
    bae.append(bound).append("\r\n");

    // Content-Disposition.
    bae.append("Content-Disposition: form-data; name=\"");
    bae.append(uploadFileData.getUploadName(numInCurrentUpload)).append("\"; filename=\"");
    if (filenameEncoding == null) {
        bae.append(uploadFilename);
    } else {
        try {
            this.uploadPolicy.displayDebug(
                    "Encoded filename: " + URLEncoder.encode(uploadFilename, filenameEncoding), 70);
            bae.append(URLEncoder.encode(uploadFilename, filenameEncoding));
        } catch (UnsupportedEncodingException e) {
            this.uploadPolicy.displayWarn(
                    e.getClass().getName() + ": " + e.getMessage() + " (in UploadFileData.getFileHeader)");
            bae.append(uploadFilename);
        }
    }
    bae.append("\"\r\n");

    // Line 3: Content-Type.
    bae.append("Content-Type: ").append(mimetype).append("\r\n");

    // An empty line to finish the header.
    bae.append("\r\n");

    // The ByteArrayEncoder is now filled.
    bae.close();
    return bae;
}

From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java

private byte[] doPost(String uri, byte[] requestBody) throws ExchangeException {
    mCancelable = false;//  ww w .  j a v  a 2  s.  com

    if (!SafeSlinger.getApplication().isOnline()) {
        throw new ExchangeException(mCtx.getString(R.string.error_CorrectYourInternetConnection));
    }

    // sets up parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    if (mHttpClient == null) {
        mHttpClient = new CheckedHttpClient(params, mCtx);
    }
    HttpPost httppost = new HttpPost(uri);
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    byte[] reqData = null;
    HttpResponse response = null;
    long startTime = SystemClock.elapsedRealtime();
    int statCode = 0;
    String statMsg = "";
    String error = "";

    try {
        // Execute HTTP Post Request
        httppost.addHeader("Content-Type", "application/octet-stream");
        httppost.setEntity(new ByteArrayEntity(requestBody));

        mTxTotalBytes = requestBody.length;

        final long totalTxBytes = TrafficStats.getTotalTxBytes();
        final long totalRxBytes = TrafficStats.getTotalRxBytes();
        if (totalTxBytes != TrafficStats.UNSUPPORTED) {
            mTxStartBytes = totalTxBytes;
        }
        if (totalRxBytes != TrafficStats.UNSUPPORTED) {
            mRxStartBytes = totalRxBytes;
        }
        response = mHttpClient.execute(httppost);
        reqData = responseHandler.handleResponse(response).getBytes("8859_1");

    } catch (UnsupportedEncodingException e) {
        error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")";
    } catch (HttpResponseException e) {
        // this subclass of java.io.IOException contains useful data for
        // users, do not swallow, handle properly
        statCode = e.getStatusCode();
        statMsg = e.getLocalizedMessage();
        error = (String.format(mCtx.getString(R.string.error_HttpCode), statCode) + ", \'" + statMsg + "\'");
    } catch (java.io.IOException e) {
        // just show a simple Internet connection error, so as not to
        // confuse users
        error = mCtx.getString(R.string.error_CorrectYourInternetConnection);
    } catch (RuntimeException e) {
        error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")";
    } catch (OutOfMemoryError e) {
        error = mCtx.getString(R.string.error_OutOfMemoryError);
    } finally {
        long msDelta = SystemClock.elapsedRealtime() - startTime;
        if (response != null) {
            StatusLine status = response.getStatusLine();
            if (status != null) {
                statCode = status.getStatusCode();
                statMsg = status.getReasonPhrase();
            }
        }
        MyLog.d(TAG, uri + ", " + requestBody.length + "b sent, " + (reqData != null ? reqData.length : 0)
                + "b recv, " + statCode + " code, " + msDelta + "ms");
    }

    if (!TextUtils.isEmpty(error) || reqData == null) {
        throw new ExchangeException(error);
    }
    return reqData;
}

From source file:eu.trentorise.smartcampus.permissionprovider.auth.internal.RegistrationController.java

/**
 * Login the user /* w w  w. j  a  v a  2s .c  om*/
 * 
 * @param model
 * @param username
 * @param password
 * @param req
 * @return
 */
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, @RequestParam String username, @RequestParam String password,
        HttpServletRequest req) {
    try {
        Registration user = manager.getUser(username, password);
        String targetEnc = null;
        try {
            targetEnc = URLEncoder.encode((String) req.getSession().getAttribute("redirect"), "UTF8");
        } catch (UnsupportedEncodingException e) {
            throw new RegistrationException(e);
        }
        req.getSession().setAttribute(InternalRegFilter.SESSION_INTERNAL_CHECK, "true");
        String redirect = String.format("redirect:/eauth/internal?target=%s&email=%s&name=%s&surname=%s",
                targetEnc, user.getEmail(), user.getName(), user.getSurname());
        ;
        return redirect;
    } catch (RegistrationException e) {
        model.addAttribute("error", e.getClass().getSimpleName());
        return "registration/login";
    }
}

From source file:com.gmt2001.TwitchAPIv3.java

public JSONObject SearchGame(String game) {
    try {/*from  w  ww .  j  ava 2 s . co m*/
        return GetData(request_type.GET,
                base_url + "/search/games?q=" + URLEncoder.encode(game, "UTF-8") + "&type=suggest", false);
    } catch (UnsupportedEncodingException ex) {
        JSONObject j = new JSONObject("{}");

        j.put("_success", false);
        j.put("_type", "");
        j.put("_url", "");
        j.put("_post", "");
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);

        return j;
    }
}

From source file:org.jwebsocket.plugins.mail.MailPlugInService.java

/**
 *
 * @param aConnector//from ww  w. j  av  a 2s  . co  m
 * @param aToken
 * @param aResponse
 * @param aServer
 * @param aPlugInNS
 */
public void addAttachment(WebSocketConnector aConnector, Token aToken, Token aResponse, TokenServer aServer,
        String aPlugInNS) {
    String lId = aToken.getString("id");
    String lFilename = aToken.getString("filename");
    String lData = aToken.getString("data");
    String lEncoding = aToken.getString("encoding", "base64");
    String lMsg;

    Token lMailStoreToken = mMailStore.getMail(lId);
    if (null == lMailStoreToken) {
        lMsg = "No mail with id '" + lId + "' found.";
        if (mLog.isDebugEnabled()) {
            mLog.debug(lMsg);
        }
        aResponse.setInteger("code", -1);
        aResponse.setString("msg", lMsg);
        // send error response to requester
        aServer.sendToken(aConnector, aResponse);
        return;
    }

    byte[] lBA = null;
    try {
        if ("base64".equals(lEncoding)) {
            int lIdx = lData.indexOf(',');
            if (lIdx >= 0) {
                lData = lData.substring(lIdx + 1);
            }
            lBA = Base64.decodeBase64(lData);
        } else {
            lBA = lData.getBytes("UTF-8");
        }
    } catch (UnsupportedEncodingException lEx) {
        mLog.error(lEx.getClass().getSimpleName() + " on save: " + lEx.getMessage());
    }

    String lBaseDir;
    String lUsername = aServer.getUsername(aConnector);
    lBaseDir = mSettings.getMailRoot();
    if (lUsername != null) {
        lBaseDir = FilenameUtils
                .getFullPath(JWebSocketConfig.expandEnvVarsAndProps(lBaseDir).replace("{username}", lUsername));
    }

    // complete the response token
    String lFullPath = lBaseDir + lFilename;
    File lFile = new File(lFullPath);
    try {
        // prevent two threads at a time writing to the same file
        synchronized (this) {
            // force create folder if not yet exists
            File lDir = new File(FilenameUtils.getFullPath(lFullPath));
            FileUtils.forceMkdir(lDir);
            if (lBA != null) {
                FileUtils.writeByteArrayToFile(lFile, lBA);
            } else {
                FileUtils.writeStringToFile(lFile, lData, "UTF-8");
            }
        }
        List<Object> lAttachments = lMailStoreToken.getList("attachments");
        if (null == lAttachments) {
            lAttachments = new FastList<Object>();
            lMailStoreToken.setList("attachments", lAttachments);
        }
        lAttachments.add(lFile.getAbsolutePath());

        mMailStore.storeMail(lMailStoreToken);

        Token lSplitToken = archiveAttachments(aConnector, aToken, lMailStoreToken, lBaseDir, aServer,
                aPlugInNS);

    } catch (IOException lEx) {
        aResponse.setInteger("code", -1);
        lMsg = lEx.getClass().getSimpleName() + " on save: " + lEx.getMessage();
        aResponse.setString("msg", lMsg);
        mLog.error(lMsg);
    }
}

From source file:com.gmt2001.TwitchAPIv5.java

public JSONObject SearchGame(String game) {
    try {/*from  w w w  .j  a  v a  2  s.  c o m*/
        String url = base_url + "/search/games?q=" + URLEncoder.encode(game, "UTF-8") + "&type=suggest";
        return GetData(request_type.GET, url, false);
    } catch (UnsupportedEncodingException ex) {
        JSONObject j = new JSONObject("{}");
        fillJSONObject(j, false, "", "", base_url + "/search/games", 0, ex.getClass().getName(),
                ex.getMessage(), "");
        com.gmt2001.Console.err.println(ex.getClass().getName() + ": " + ex.getMessage());
        return j;
    }
}

From source file:ezbake.services.provenance.thrift.ProvenanceServiceImpl.java

@Override
public void recordObjectAccess(ezbake.base.thrift.EzSecurityToken securityToken, String documentUri,
        ObjectAccessType accessType) throws TException {
    validateSecurityToken(securityToken);
    String accessStr;/*from   w w  w.  java2  s  .c  o m*/
    AuditEvent evt = null;
    switch (accessType) {
    case CREATE:
        accessStr = "create";
        evt = event(AuditEventType.FileObjectCreate.getName(), securityToken);
        break;
    case READ:
        accessStr = "read";
        evt = event(AuditEventType.FileObjectAccess.getName(), securityToken);
        break;
    case WRITE:
        accessStr = "write";
        evt = event(AuditEventType.FileObjectModify.getName(), securityToken);
        break;
    case MANAGE:
        accessStr = "manage";
        evt = event(AuditEventType.FileObjectModify.getName(), securityToken);
        break;
    case DELETE:
        evt = event(AuditEventType.FileObjectDelete.getName(), securityToken);
        accessStr = "delete";
        break;
    default:
        accessStr = "unknown";
        evt = event(AuditEventType.FileObjectAccess.getName(), securityToken);
    }
    evt.arg("event", "recordObjectAccess").arg("accessType", accessType.name()).arg("documentUri", documentUri);
    // verify table created
    try {

        Integer append = randomGenerator.nextInt();

        Long currentTime = System.currentTimeMillis();
        String principalJson = new String(
                new TSerializer(new TSimpleJSONProtocol.Factory()).serialize(securityToken.tokenPrincipal),
                EzSecurityConstant.CHARSET);
        String record = String.format("{timestamp:%d uri:%s access:%s principal:%s}", currentTime, documentUri,
                accessStr, principalJson);
        writeRow(documentUri, String.format("%019d", currentTime), String.format("%d", append), "U", record);
        writeRow(securityToken.tokenPrincipal.principal, String.format("%019d", currentTime),
                String.format("%d", append), "U", record);
    } catch (UnsupportedEncodingException e) {
        evt.failed();
        evt.arg(e.getClass().getName(), e);
        throw new TException("Unable to encode " + EzSecurityConstant.CHARSET + " string");
    } catch (Exception e) {
        evt.failed();
        evt.arg(e.getClass().getName(), e);
        throw e;
    } finally {
        auditLogger.logEvent(evt);
    }

}

From source file:com.amalto.service.calltransformer.CallTransformerServiceBean.java

public String receiveFromInbound(ItemPOJOPK itemPK, String routingOrderID, String parameters)
        throws com.amalto.core.util.XtentisException {
    try {/* www .j a  v  a 2s.  c  o m*/
        String transformer = null;
        if (parameters != null) {
            String kvs[] = parameters.split("&");
            for (String kv1 : kvs) {
                String[] kv = kv1.split("=");
                String key = kv[0].trim().toLowerCase();
                if ((Param_Transformer_Name.equals(key)) && (kv.length == 2)) {
                    transformer = kv[1].trim();
                }
            }
            if (transformer == null || "".equals(transformer)) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Service CallTransformer - mandatory parameter transformer name is missing");
                }
                throw new XtentisException(
                        "Service CallTransformer - mandatory parameter transformer name is missing");
            }
            Transformer tctrl = Util.getTransformerV2CtrlLocal();
            if (tctrl.existsTransformer(new TransformerV2POJOPK(transformer)) == null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Service CallTransformer is unable to call transformer " + transformer
                            + " - transformer doesn't exist");
                }
                throw new XtentisException("Unable to find the transformer " + transformer);
            }
            Item ictrl = Util.getItemCtrl2Local();
            ItemPOJO pojo = ictrl.getItem(itemPK);
            TransformerContext context = new TransformerContext(new TransformerV2POJOPK(transformer));
            context.putInPipeline(Transformer.DEFAULT_VARIABLE,
                    new TypedContent(pojo.getProjectionAsString().getBytes(), "text/xml"));
            AbstractRoutingOrderV2POJO routingOrder = getRoutingOrderPOJO();
            String userToken = null;
            if (routingOrder != null) {
                try {
                    userToken = new String(
                            (new BASE64Decoder()).decodeBuffer(routingOrder.getBindingUserToken()), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    LOGGER.error("Unable to read user token.", e);
                }
            }
            TransformerGlobalContext globalContext = new TransformerGlobalContext(context);
            globalContext.setUserToken(userToken);
            tctrl.executeUntilDone(globalContext);
        }
        return "CallTransformer Service successfully executed transformer '" + transformer + "'";
    } catch (Exception e) {
        String err = (new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss, SSS"))
                .format(new Date(System.currentTimeMillis())) + ": ERROR routing to Call Transformer Service "
                + ": " + e.getLocalizedMessage();
        if (e instanceof XtentisException) {
            throw new XtentisException(e);
        } else {
            LOGGER.error(err + " (" + e.getClass().getName() + ")", e);
            throw new XtentisException(e);
        }
    }

}

From source file:it.jnrpe.plugin.CheckHttp.java

/**
 * Do the actual http request and return the response string.
 * /*from  w  w w . ja  va 2 s.com*/
 * @param cl
 *            - The received command line
 * @param hostname
 *            - The server hostname
 * @param port
 *            - The server port
 * @param method
 *            - The HTTP method
 * @param path
 *            - The connection path
 * @param timeout
 *            - The timeout
 * @param ssl
 *            - if SSL must be used
 * @param metrics
 *            - This list will be filled with the gathered metrics
 * @return - the response
 * @throws MetricGatheringException
 *             - if an error occurs during the execution
 */
private String getHttpResponse(final ICommandLine cl, final String hostname, final String port,
        final String method, final String path, final int timeout, final boolean ssl,
        final List<Metric> metrics) throws MetricGatheringException {
    Properties props = null;
    try {
        props = getRequestProperties(cl, method);
    } catch (UnsupportedEncodingException e) {
        throw new MetricGatheringException("Error occurred: " + e.getMessage(), Status.CRITICAL, e);
    }
    String response = null;
    String redirect = cl.getOptionValue("onredirect");
    boolean ignoreBody = false;
    try {
        String data = null;
        if ("POST".equals(method)) {
            data = getPostData(cl);
        }

        if (cl.hasOption("no-body")) {
            ignoreBody = true;
        }
        String urlString = hostname + ":" + port + path;
        if (cl.hasOption("authorization")) {
            urlString = cl.getOptionValue("authorization") + "@" + urlString;
        } else if (cl.hasOption("proxy-authorization")) {
            urlString = cl.getOptionValue("proxy-authorization") + "@" + urlString;
        }
        if (ssl) {
            urlString = "https://" + urlString;
        } else {
            urlString = "http://" + urlString;
        }
        URL url = new URL(urlString);
        if (cl.getOptionValue("certificate") != null) {
            checkCertificateExpiryDate(url, metrics);
        } else if (redirect != null) {
            response = checkRedirectResponse(url, method, timeout, props, data, redirect, ignoreBody, metrics);
        } else {
            try {
                if ("GET".equals(method)) {
                    response = HttpUtils.doGET(url, props, timeout, true, ignoreBody);
                } else if ("POST".equals(method)) {
                    response = HttpUtils.doPOST(url, props, null, data, true, ignoreBody);
                } else if ("HEAD".equals(method)) {
                    response = HttpUtils.doHEAD(url, props, timeout, true, ignoreBody);
                }
                // @TODO complete for other http methods

            } catch (MalformedURLException e) {
                LOG.error(getContext(), "Bad url", e);
                throw new MetricGatheringException("Bad url string : " + urlString, Status.CRITICAL, e);
            }
        }

    } catch (Exception e) {
        LOG.error(getContext(), "Exception: " + e.getMessage(), e);
        throw new MetricGatheringException(e.getClass().getName() + ": " + e.getMessage(), Status.CRITICAL, e);
    }
    return response;
}

From source file:com.secupwn.aimsicd.utils.RequestTask.java

@Override
protected String doInBackground(String... commandString) {

    // We need to create a separate case for UPLOADING to DBe (OCID, MLS etc)
    switch (mType) {
    // OCID upload request from "APPLICATION" drawer title
    case DBE_UPLOAD_REQUEST:
        try {//from w  w  w. ja v  a 2s  .  com
            @Cleanup
            Realm realm = Realm.getDefaultInstance();
            boolean prepared = mDbAdapter.prepareOpenCellUploadData(realm);

            log.info("OCID upload data prepared - " + String.valueOf(prepared));
            if (prepared) {
                File file = new File((mAppContext.getExternalFilesDir(null) + File.separator)
                        + "OpenCellID/aimsicd-ocid-data.csv");
                publishProgress(25, 100);

                RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                        .addFormDataPart("key", CellTracker.OCID_API_KEY).addFormDataPart("datafile",
                                "aimsicd-ocid-data.csv", RequestBody.create(MediaType.parse("text/csv"), file))
                        .build();

                Request request = new Request.Builder().url("http://www.opencellid.org/measure/uploadCsv")
                        .post(requestBody).build();

                publishProgress(60, 100);

                Response response = okHttpClient.newCall(request).execute();

                publishProgress(80, 100);
                if (response != null) {
                    log.info("OCID Upload Response: " + response.code() + " - " + response.message());
                    if (response.code() == 200) {
                        Realm.Transaction transaction = mDbAdapter.ocidProcessed();
                        realm.executeTransaction(transaction);
                    }
                    publishProgress(95, 100);
                }
                return "Successful";
            } else {
                Helpers.msgLong(mAppContext, mAppContext.getString(R.string.no_data_for_publishing));
                return null;
            }

            // all caused by httpclient.execute(httppost);
        } catch (UnsupportedEncodingException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (FileNotFoundException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (IOException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (Exception e) {
            log.error("Upload OpenCellID data Exception", e);
        }

        // DOWNLOADING...
    case DBE_DOWNLOAD_REQUEST: // OCID download request from "APPLICATION" drawer title
        mTimeOut = REQUEST_TIMEOUT_MENU;
    case DBE_DOWNLOAD_REQUEST_FROM_MAP: // OCID download request from "Antenna Map Viewer"
        int count;
        try {
            long total;
            int progress = 0;
            String dirName = getOCDBDownloadDirectoryPath(mAppContext);
            File dir = new File(dirName);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, OCDB_File_Name);
            log.info("DBE_DOWNLOAD_REQUEST write to: " + dirName + OCDB_File_Name);

            Request request = new Request.Builder().url(commandString[0]).get().build();

            Response response;
            try {
                // OCID's API can be slow. Give it up to a minute to do its job. Since this
                // is a backgrounded task, it's ok to wait for a while.
                okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
                response = okHttpClient.newCall(request).execute();
                okHttpClient.setReadTimeout(10, TimeUnit.SECONDS); // Restore back to default
            } catch (SocketTimeoutException e) {
                log.warn("Trying to talk to OCID timed out after 60 seconds. API is slammed? Throttled?");
                return "Timeout";
            }

            if (response.code() != 200) {
                try {
                    String error = response.body().string();
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + error);
                    log.error("Download OCID data error: " + error);
                } catch (Exception e) {
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " "
                            + e.getClass().getName() + " - " + e.getMessage());
                    log.error("Download OCID exception: ", e);
                }
                return "Error";
            } else {
                // This returns "-1" for streamed response (Chunked Transfer Encoding)
                total = response.body().contentLength();
                if (total == -1) {
                    log.debug("doInBackground DBE_DOWNLOAD_REQUEST total not returned!");
                    total = 1024; // Let's set it arbitrarily to something other than "-1"
                } else {
                    log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
                    publishProgress((int) (0.25 * total), (int) total); // Let's show something!
                }

                FileOutputStream output = new FileOutputStream(file, false);
                InputStream input = new BufferedInputStream(response.body().byteStream());

                byte[] data = new byte[1024];
                while ((count = input.read(data)) > 0) {
                    // writing data to file
                    output.write(data, 0, count);
                    progress += count;
                    publishProgress(progress, (int) total);
                }
                input.close();
                // flushing output
                output.flush();
                output.close();
            }
            return "Successful";

        } catch (IOException e) {
            log.warn("Problem reading data from steam", e);
            return null;
        }
    }

    return null;
}