protected void processRequest(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final String uri = req.getRequestURI(); log.debug("Received URI: {}", uri); final Map<String, String> params = HttpUtils.toParamMap(req); log.debug("Params: {}", params); log.debug("Headers: {}", HttpUtils.toHeaderMap(req)); log.debug("Query string: {}", req.getQueryString()); if (this.censored.isCensored()) { proxifier.proxyGoogle(); } final String location = newGtalkOauthUrl(); // We have to completely recreate the server each time because we // stop it and start it only when we need oauth callbacks. If we // attempt to restart a stopped server, things get funky. final GoogleOauth2CallbackServer server = new GoogleOauth2CallbackServer( handler, model, this.internalState, this.modelIo, this.proxifier, this.httpClientFactory, modelUtils); // Note that this call absolutely ensures the server is started. server.start(); log.debug("Sending redirect to {}", location); resp.sendRedirect(location); }
public static void main(String[] args) { HttpUtils.createhttpClient(); HttpUtils.HttpResult result1 = HttpUtils.doGet("http://www.jsds.gov.cn/kpgl/rzxt/query2.jsp"); Map<String, String> header = new HashMap<>(); header.put("Content-Type", "application/x-www-form-urlencoded"); header.put("Origin", "http://www.jsds.gov.cn"); header.put("Referer", "http://www.jsds.gov.cn/kpgl/rzxt/query2.jsp"); header.put( "Cookie", "Secure; Secure; JSID_KPGL=9zQtW0zdYd5ffJcvLX5HBSJ11hpCkRmJzgVWRfPKPhp1G0TD4pJy!541357520; _gsref_1161164261=http://www.jsds.gov.cn/kpgl/rzxt/query2.jsp; _gscu_1161164261=58867921tztrwj64; _gscs_1161164261=58867921hpl4dj64|pv:3; _gscbrs_1161164261=1"); HttpUtils.createhttpClient(); System.out.println(result1.getRequestHeaders().toString() + "\r\n"); System.out.println(result1.getResponseHeaders().toString() + "\r\n"); System.out.println("_________________"); List<Part> params = new ArrayList<>(); // params.add(new StringPart("fptxm", "232001506120109005337070")); // params.add(new StringPart("cxfs", "1")); // params.add(new StringPart("hideshow_tm1", "0")); // params.add(new StringPart("INVOICE_CHECKING_CHECKCODE", "6002")); // params.add(new StringPart("yzm", "")); HttpUtils.HttpResult result = HttpUtils.doPost("http://www.jsds.gov.cn/kpgl/rzxt/wss_wwall", header, params, "gbk"); System.out.println(result.getRequestHeaders().toString() + "\r\n"); System.out.println(result.getResponseHeaders().toString() + "\r\n"); System.out.println(result.getReturnObj()); }
public void displayStructure(QueryControl q_cntl, int index, HttpUtils h, Xdsview xv, String cntl) throws MetadataValidationException, MetadataException { System.out.println("Related QueryContents"); this.displayStructureHeader(index, xv); Metadata m = getMetadata(); boolean object_refs = m.isObjectRefsOnly(); if (m.getWrapper() == null) return; xv.getMetadata().addMetadata(m); if (object_refs) { // no idea what to do here } else { String ref_id = this.getReferenceId(); h.indent1( xv.build_details_link(ref_id, cntl) + " (" + xv.build_xml_link(ref_id, cntl) + " " + ")"); for (OMElement a_ele : m.getAssociations()) { String src_id = m.getAssocSource(a_ele); String a_type = m.getSimpleAssocType(a_ele); String a_id = m.getId(a_ele); String tgt_id = m.getAssocTarget(a_ele); if (src_id == null) { } else if (src_id != null && !src_id.equals(this.getReferenceId())) { if (a_type.equals("RPLC")) a_type = "replaced by"; else if (a_type.equals("APND")) a_type = "has appended"; else if (a_type.equals("XFRM")) a_type = "transformed to"; else a_type = a_type + " by"; h.indent2( xv.build_assoc_link(a_id, a_type, cntl) + " " + xv.build_details_link(src_id, cntl) + " (" + xv.build_xml_link(src_id, cntl) + " " + ") " + " [" + ((q_cntl.hasEndpoint()) ? xv.build_related_link(src_id) : "") + "]"); } else { if (a_type.equals("RPLC")) a_type = "replaces"; else if (a_type.equals("APND")) a_type = "appended to"; else if (a_type.equals("XFRM")) a_type = "transform of"; h.indent2( xv.build_assoc_link(a_id, a_type, cntl) + " " + xv.build_details_link(tgt_id, cntl) + " (" + xv.build_xml_link(tgt_id, cntl) + " " + ") " + " [" + ((q_cntl.hasEndpoint()) ? xv.build_related_link(tgt_id) : "") + "]"); } } } }
/** @return the remote's HEAD {@link Ref}. */ @Override public Ref headRef() { HttpURLConnection connection = null; Ref headRef = null; try { String expanded = repositoryURL.toString() + "/repo/manifest"; connection = HttpUtils.connect(expanded); // Get Response InputStream is = HttpUtils.getResponseStream(connection); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rd.readLine()) != null) { if (line.startsWith("HEAD")) { headRef = HttpUtils.parseRef(line); } } rd.close(); } finally { is.close(); } } catch (Exception e) { Throwables.propagate(e); } finally { HttpUtils.consumeErrStreamAndCloseConnection(connection); } return headRef; }
/** * List the remote's {@link Ref refs}. * * @param getHeads whether to return refs in the {@code refs/heads} namespace * @param getTags whether to return refs in the {@code refs/tags} namespace * @return an immutable set of refs from the remote */ @Override public ImmutableSet<Ref> listRefs(final boolean getHeads, final boolean getTags) { HttpURLConnection connection = null; ImmutableSet.Builder<Ref> builder = new ImmutableSet.Builder<Ref>(); try { String expanded = repositoryURL.toString() + "/repo/manifest"; connection = HttpUtils.connect(expanded); // Get Response InputStream is = HttpUtils.getResponseStream(connection); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; try { while ((line = rd.readLine()) != null) { if ((getHeads && line.startsWith("refs/heads")) || (getTags && line.startsWith("refs/tags"))) { builder.add(HttpUtils.parseRef(line)); } } } finally { rd.close(); } } catch (Exception e) { throw Throwables.propagate(e); } finally { HttpUtils.consumeErrStreamAndCloseConnection(connection); } return builder.build(); }
public void testCallServlet() { boolean result = true; try { // run tests by calling a servlet Header runParam = new Header("run", "run"); HttpMethodBase request = HttpUtils.accessURL( new URL(serverUrl), null, HttpURLConnection.HTTP_OK, new Header[] {runParam}, HttpUtils.POST); String response = null; int index = 0; do { System.err.println("_____________ " + (index++) + "th round"); // we have to give some time to the tests to finish Thread.sleep(10000); // 10 secs // tries to get results request = HttpUtils.accessURL(new URL(serverUrl), null, HttpURLConnection.HTTP_OK, HttpUtils.GET); response = request.getResponseBodyAsString(); } while (response != null && response.indexOf("finished") == -1 && index < LOOP_RETRY_MAX); if (response != null && response.indexOf("finished") == -1) { System.err.println("======================================================"); System.err.println("==================== TIMED OUT ====================="); System.err.println("======================================================"); result = false; } else { System.err.println("======================================================"); System.err.println("==================== RESULT ====================="); System.err.println("======================================================"); System.err.println(response); // writes response to the outfile BufferedWriter writer = new BufferedWriter(new FileWriter(outfile)); writer.write(response); writer.close(); } } catch (Exception e) { System.err.println("======================================================"); System.err.println("==================== EXCEPTION ====================="); System.err.println("======================================================"); e.printStackTrace(); result = false; } assertTrue(result); }
public static void performLoginGetYTCookie(SessionData loginData, String token) throws MessengerException, IOException { String cs = YahooMessengerConstants.pwTokenLoginURL + "src=ymsgr&" + "token=" + token; String resultString = HttpUtils.performHttpGet(cs); String[] nameValuePairs = StringUtils.tokenize(resultString, '\n', true); if (nameValuePairs.length == 1) { try { if (Integer.parseInt(nameValuePairs[0]) == 100) // INVALID TOKEN throw new MessengerException(MessengerException.INVALID_TOKEN, "Invalid token"); else // UNKNOWN ERROR throw new MessengerException(MessengerException.UNKNOWN_ERROR, "Unknown error"); } catch (NumberFormatException e) { throw new MessengerException(MessengerException.UNKNOWN_ERROR, "Unknown error"); } } else if (nameValuePairs.length == 6) { // Assemble the Y and T name value pairs into the information needed // for the cookie. String cookie = nameValuePairs[2] + " " + nameValuePairs[3]; loginData.setCookie(cookie); } else { throw new MessengerException(MessengerException.UNKNOWN_ERROR, "Unknown error"); } }
public SplashObj getSplashObj() { try { String json = HttpUtils.getHttpContentWithCache( BiliUtils.getSplashApi(), "splash", "splash.json", true); if (json == null) return null; JSONObject jsobj = new JSONObject(json); if (jsobj.optString("message").equals("success")) { JSONArray array = jsobj.getJSONArray("result"); JSONObject temp = array.getJSONObject(0); SplashObj obj = new SplashObj(); obj.setAnimation(temp.optString("animation")); obj.setDuration(temp.optString("duration")); obj.setEnd(temp.optLong("end")); obj.setHeight(temp.optInt("height")); obj.setImage(temp.optString("image")); obj.setStart(temp.optLong("start")); obj.setWidth(temp.optInt("width")); obj.setVer(temp.optInt("ver")); return obj; } } catch (JSONException e) { } return null; }
public void run() { if (!isRunning) { isRunning = true; context.log("开始执行指定任务"); logger.info("开始执行指定任务 -- 上传文件过期删除记录"); String urlStr = SystemConfig.getSystemConfig().getFileSavePath() + "/sysAction.do?method=fileSystemDel"; String retstr = HttpUtils.callRPC(urlStr); System.out.println("retstr===" + retstr); if (retstr.equals("0")) { logger.info("开始执行指定任务 -- 删除成功"); } else { logger.info("开始执行指定任务 -- 删除失败"); } // 在这里编写自己的功能,例: // File file = new File("temp"); // file.mkdir(); // 启动tomcat,可以发现在tomcat根目录下,会自动创建temp文件夹 // -------------------结束 isRunning = false; context.log("指定任务执行结束"); } else { context.log("上一次任务执行还未结束"); } }
/** * 删除入库单中的半成品 * * @throws IOException */ public String deleteBom() throws IOException { List<ZgTstorageCanclebomEx> bomECancleList = (List<ZgTstorageCanclebomEx>) this.getSession().getAttribute("bomECancleList"); for (int i = 0; i < items.length; i++) { Hashtable params = HttpUtils.parseQueryString(items[i]); String cuid = (String) params.get("cuid"); for (ZgTstorageCanclebomEx obj : bomECancleList) { if (cuid.equals(obj.getCuid())) { obj.setIsDel(true); obj.setIsModity(true); break; } } } this.getSession().setAttribute("bomECancleList", bomECancleList); // 保存bomIds到session中,用于页面展示可选bom的时候过滤 String bomECancleIds = ""; for (ZgTstorageCanclebomEx obj : bomECancleList) { if (!obj.getIsDel()) { bomECancleIds = bomECancleIds + obj.getStorageId() + obj.getOrderBomId() + ","; } } this.getSession().setAttribute("bomECancleIds", bomECancleIds); return SUCCESS; }
/** 根据经纬度获取地址 */ public static AMapAddress getAddress(double longitude, double latitude) { AMapAddress address = null; String url = MessageFormat.format(aMapUrl, String.valueOf(longitude), String.valueOf(latitude)); String str = HttpUtils.get(url); try { if (StringUtils.isNotBlank(url)) { JSONObject json = JSONObject.parseObject(str); if (null != json) { int status = json.getIntValue("status"); if (status == 1) { JSONObject regeocode = json.getJSONObject("regeocode"); if (null != regeocode) { JSONObject addressComponent = regeocode.getJSONObject("addressComponent"); if (null != addressComponent) { // city 值不固定 String province = addressComponent.getString("province"); String citycode = addressComponent.getString("citycode"); String city = addressComponent.getString("city"); if (StringUtils.isNotBlank(city) && city.equals("[]")) { city = ""; } address = new AMapAddress(); address.setCityCode(citycode); address.setProvince(province); address.setCity(city); } } } } } } catch (Exception e) { } return address; }
public String getBamIndexPath() { if (indexPath != null) return indexPath; if (path.toLowerCase().startsWith("http://") || path.toLowerCase().startsWith("https://")) { // See if bam file is specified by parameter try { URL url = new URL(path); String queryString = url.getQuery(); if (queryString != null) { Map<String, String> parameters = HttpUtils.parseQueryString(queryString); if (parameters.containsKey("index")) { return parameters.get("index"); } else if (parameters.containsKey("file")) { String bamFile = parameters.get("file"); String bamIndexFile = bamFile + ".bai"; String newQueryString = queryString.replace(bamFile, bamIndexFile); return path.replace(queryString, newQueryString); } else { String ip = path.replace(url.getPath(), url.getPath() + ".bai"); return ip; } } } catch (MalformedURLException e) { log.error(e.getMessage(), e); } } return path + ".bai"; }
/** * Push all new objects from the specified {@link Ref} to the remote. * * @param ref the local ref that points to new commit data * @param refspec the remote branch to push to */ @Override public void pushNewData(Ref ref, String refspec, ProgressListener progress) throws SynchronizationException { Optional<Ref> remoteRef = HttpUtils.getRemoteRef(repositoryURL, refspec); checkPush(ref, remoteRef); beginPush(); progress.setDescription("Uploading objects to " + refspec); progress.setProgress(0); CommitTraverser traverser = getPushTraverser(remoteRef); traverser.traverse(ref.getObjectId()); List<ObjectId> toSend = new LinkedList<ObjectId>(traverser.commits); Collections.reverse(toSend); Set<ObjectId> have = new HashSet<ObjectId>(traverser.have); Deduplicator deduplicator = deduplicationService.createDeduplicator(); try { sendPackedObjects(toSend, have, deduplicator, progress); } finally { deduplicator.release(); } ObjectId originalRemoteRefValue = ObjectId.NULL; if (remoteRef.isPresent()) { originalRemoteRefValue = remoteRef.get().getObjectId(); } String nameToSet = remoteRef.isPresent() ? remoteRef.get().getName() : Ref.HEADS_PREFIX + refspec; endPush(nameToSet, ref.getObjectId(), originalRemoteRefValue.toString()); }
@Override public OutputStream get() { String expanded = repositoryURL.toString() + "/repo/sendobject"; try { HttpURLConnection connection = (HttpURLConnection) new URL(expanded).openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setChunkedStreamingMode(4096); connection.setRequestProperty("content-length", "-1"); connection.setRequestProperty("content-encoding", "gzip"); OutputStream out = connection.getOutputStream(); final ReportingOutputStream rout = HttpUtils.newReportingOutputStream(connection, out, true); return new FilterOutputStream(rout) { @Override public void close() throws IOException { super.close(); compressedSize += ((ReportingOutputStream) super.out).compressedSize(); uncompressedSize += ((ReportingOutputStream) super.out).unCompressedSize(); } }; } catch (Exception e) { throw Throwables.propagate(e); } }
public static AMapAddress getAddress(String addressStr, String city) { AMapAddress address = null; String url = MessageFormat.format(aMapGeoUrl2, addressStr, city); String str = HttpUtils.get(url); try { if (StringUtils.isNotBlank(str)) { JSONObject json = JSONObject.parseObject(str); if (null != json) { int status = json.getIntValue("status"); if (status == 1) { JSONArray geocodes = json.getJSONArray("geocodes"); if (null != geocodes && geocodes.size() > 0) { JSONObject jsonAddress = geocodes.getJSONObject(0); address = new AMapAddress(); address.setCity(jsonAddress.getString("city")); address.setCityCode(jsonAddress.getString("citycode")); address.setProvince(jsonAddress.getString("province")); } } } } } catch (Exception e) { e.printStackTrace(); } return address; }
private void updateBitcoinValue() { HttpUtils.get( "https://blockchain.info/ticker", null, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { // If the response is JSONObject instead of expected JSONArray try { currentBTCValue = response.getJSONObject(currencyName).getDouble("buy"); currencySymbol = response.getJSONObject(currencyName).getString("symbol"); tvBitcoinValue.setText(String.valueOf(currentBTCValue)); tvCurrencySymbol.setText(currencySymbol); String newCurrName = getString(R.string.currName, currencyName); tvCurrencyName.setText(newCurrName); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {} @Override public void onFailure(int i, Header[] head, Throwable e, JSONObject b) { Toast.makeText( getApplicationContext(), getString(R.string.noInternet), Toast.LENGTH_LONG) .show(); } }); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { boolean toLoginPage = true; Cookie loginCookie = HttpUtils.getLoginCookie(req); if (loginCookie != null) { LOG.debug("Request has a '{}' cookie", HttpUtils.getLoginCookieName()); String tokenStr = loginCookie.getValue(); if (tokenStr != null) { SSOPrincipal principal = getSsoService().validateUserToken(tokenStr); if (principal != null) { LOG.debug( "Request already has an authenticated user '{}', skipping login page", principal.getName()); res.setHeader(SSOConstants.X_USER_AUTH_TOKEN, tokenStr); String redirectUrl = req.getParameter(SSOConstants.REQUESTED_URL_PARAM); if (redirectUrl != null) { boolean repeatedRedirect = req.getParameter(SSOConstants.REPEATED_REDIRECT_PARAM) != null; if (repeatedRedirect) { LOG.warn("Request is a repeated redirect, invalidating token '{}'", tokenStr); getSsoService().invalidateUserToken(tokenStr); } else { LOG.debug("Redirecting back to '{}'", redirectUrl); redirectUrl = createRedirectionUrl(redirectUrl, tokenStr); res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); res.setHeader("Pragma", "no-cache"); res.setHeader("Expires", "0"); res.sendRedirect(redirectUrl); toLoginPage = false; } } else { res.setStatus(HttpServletResponse.SC_ACCEPTED); toLoginPage = false; } } else { LOG.debug( "Request has an invalid '{}' cookie '{}'", HttpUtils.getLoginCookieName(), tokenStr); } } } if (toLoginPage) { dispatchToLoginPage(req, res); } }
private void processRequest(final HttpServletRequest req, final HttpServletResponse resp) { final String uri = req.getRequestURI(); log.debug("Received URI: {}", uri); final Map<String, String> params = HttpUtils.toParamMap(req); log.debug("Params: {}", params); // Before redirecting to Google, we set up the proxy to proxy // access to accounts.google.com for the oauth exchange. That's just // temporary, though, and we now cancel it. try { this.proxifier.stopProxying(); } catch (final ProxyConfigurationError e) { log.warn("Could not stop proxy?", e); } // Redirect back to the dashboard right away to continue giving the // user feedback. The UI will fetch the current state doc. log.debug("Redirecting from oauth back to dashboard..."); final String code = params.get("code"); if (StringUtils.isBlank(code)) { // This will happen when the user cancels oauth. log.debug("Did not get authorization code in params: {}", params); final String error = params.get("error"); log.debug("Got error: {}", error); log.debug("Setting modal on model: {}", model); this.model.setModal(Modal.authorize); redirectToDashboard(resp); return; } // Theoretically this should actually be oauth connecting here, but // this should do. Make sure we set this before sending the user // back to the dashboard. We don't need to post an event because the // dashboard is about to get fully reloaded. modelUtils.syncConnectingStatus(Tr.tr(MessageKey.TALK_SERVERS)); log.debug("Setting modal to connecting..."); this.model.setModal(Modal.connecting); redirectToDashboard(resp); int port = this.googleOauth2CallbackServer.getPort(); // Kill our temporary oauth callback server. this.googleOauth2CallbackServer.stop(); final HttpClient client = this.httpClientFactory.newClient(); final Map<String, String> allToks; try { allToks = loadAllToks(code, port, client); } catch (final IOException e) { log.error("Could not load all oauth tokens!!", e); redirectToDashboard(resp); return; } connectToGoogleTalk(allToks); fetchEmail(allToks, client); }
/** 删除对象 */ public String delBatch() { for (int i = 0; i < items.length; i++) { Hashtable params = HttpUtils.parseQueryString(items[i]); java.lang.Integer id = new java.lang.Integer((String) params.get("id")); noteSendManager.removeById(id); } Flash.current().success(DELETE_SUCCESS); return LIST_ACTION; }
/** * Handle the response for various request, normally, a request was a short and low memory-usage * request, thus we can parse the response-content as byte[] in memory. However the {@link * com.duowan.mobile.netroid.request.FileDownloadRequest} itself was a large memory-usage case, * that's inadvisable for parse all response content to memory, so it had self-implement * mechanism. */ public byte[] handleResponse(HttpResponse response, Delivery delivery) throws IOException, ServerError { // Some responses such as 204s do not have content. if (response.getEntity() != null) { return HttpUtils.responseToBytes(response); } else { // Add 0 byte response as a way of honestly representing a no-content request. return new byte[0]; } }
/** * Upload files to pre-configured url. * * @param uploadLocation the location we are uploading to. * @param fileName the filename we use for the resulting filename we upload. * @param params the optional parameter names. * @param values the optional parameter values. */ static void uploadLogs(String uploadLocation, String fileName, String[] params, String[] values) { try { File tempDir = LoggingUtilsActivator.getFileAccessService().getTemporaryDirectory(); File newDest = new File(tempDir, fileName); File optionalFile = null; // if we have some description params // save them to file and add it to archive if (params != null) { optionalFile = new File( LoggingUtilsActivator.getFileAccessService().getTemporaryDirectory(), "description.txt"); OutputStream out = new FileOutputStream(optionalFile); for (int i = 0; i < params.length; i++) { out.write((params[i] + " : " + values[i] + "\r\n").getBytes("UTF-8")); } out.flush(); out.close(); } newDest = LogsCollector.collectLogs(newDest, optionalFile); // don't leave any unneeded information if (optionalFile != null) optionalFile.delete(); if (uploadLocation == null) return; if (HttpUtils.postFile(uploadLocation, "logs", newDest) != null) { NotificationService notificationService = LoggingUtilsActivator.getNotificationService(); if (notificationService != null) { ResourceManagementService resources = LoggingUtilsActivator.getResourceService(); String bodyMsgKey = "plugin.loggingutils.ARCHIVE_MESSAGE_OK"; notificationService.fireNotification( LOGFILES_ARCHIVED, resources.getI18NString("plugin.loggingutils.ARCHIVE_BUTTON"), resources.getI18NString(bodyMsgKey, new String[] {uploadLocation}), null); } } } catch (Throwable e) { logger.error("Cannot upload file", e); } }
/** * 判断token是否过期 * * @param token * @return */ public static boolean isTokenExpired(String token) { boolean rs = true; NameValuePair[] params = { new NameValuePair("access_token", token), }; try { JSONObject json = JSONObject.fromObject(HttpUtils.getMethod(GmailConstants.IS_AUTH_EXPIRED_URL, params)); rs = json.containsKey("error"); } catch (IOException e) { e.printStackTrace(); } return rs; }
/** Create the default HTTP protocol parameters. */ private static final HttpParams createHttpParams(Context mContext) { final HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); // 加入代理 HttpUtils.fillProxy(mContext, params); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); return params; }
protected void doCommon(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { try { if (log.isDebugEnabled()) log.debug(HttpUtils.fmtRequest(httpRequest)); // getRequestURL is the exact string used by the caller in the request. // Internally, it's the "request URI" that names the service // String requestURL = httpRequest.getRequestURL().toString() ; String uri = httpRequest.getRequestURI(); if (uri.length() > urlLimit) { httpResponse.setStatus(HttpServletResponse.SC_REQUEST_URI_TOO_LONG); return; } String serviceURI = chooseServiceURI(uri, httpRequest); serviceURI = Service.canonical(serviceURI); String sender = httpRequest.getRemoteAddr(); log.info("[" + sender + "] Service URI = <" + serviceURI + ">"); // MIME-Type String contentType = httpRequest.getContentType(); // if ( Joseki.contentSPARQLUpdate.equals(contentType) || // Joseki.contentSPARQLUpdate_X.equals(contentType) ) // {} Request request = setupRequest(serviceURI, httpRequest); request.setParam(Joseki.VERB, httpRequest.getMethod()); Response response = new ResponseHttp(request, httpRequest, httpResponse); Dispatcher.dispatch(serviceURI, request, response); } catch (Exception ex) { try { log.warn("Internal server error", ex); // httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) ; // httpResponse.flushBuffer() ; // httpResponse.getWriter().close() ; httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (Exception e) { } } }
/** * Return a string suitable for determining file type based on extension May or may not be a full, * readable path. txt and gz extensions are stripped * * @return */ public String getTypeString() { if (type != null) { return type; } else { String typeString = path.toLowerCase(); if (path.startsWith("http://") || path.startsWith("https://")) { try { URL url = new URL(path); typeString = url.getPath().toLowerCase(); String query = url.getQuery(); if (query != null) { Map<String, String> queryMap = HttpUtils.parseQueryString(query); // If type is set explicitly use it if (queryMap.containsKey("dataformat")) { String format = queryMap.get("dataformat"); if (format.contains("genomespace")) { typeString = GSUtils.parseDataFormatString(format); } else { typeString = format; } } else if (queryMap.containsKey("file")) { typeString = queryMap.get("file"); } } } catch (MalformedURLException e) { log.error("Error interpreting url: " + path, e); typeString = path; } } // Strip .txt, .gz, and .xls extensions. (So foo.cn.gz => a .cn file) if ((typeString.endsWith(".txt") || typeString.endsWith(".xls") || typeString.endsWith(".gz") || typeString.endsWith(".bgz"))) { typeString = typeString.substring(0, typeString.lastIndexOf(".")).trim(); } return typeString; } }
public static Document readAtomFeed(final String feed, final String user, final String password) throws FeedLoadException { Document document = null; try { InputStream is = HttpUtils.getWebRessourceAsStream(feed, user, password); SAXReader reader = new SAXReader(); // dom4j SAXReader document = reader.read(is); // dom4j Document } catch (ClientProtocolException e) { throw new FeedLoadException(e); } catch (IOException e) { throw new FeedLoadException(e); } catch (DocumentException e) { throw new FeedLoadException(e); } catch (Exception e) { throw new FeedLoadException(e); } return document; }
public static String performLoginGetPwToken(String username, String password) throws MessengerException, IOException { String cs = YahooMessengerConstants.pwTokenGetURL + "src=ymsgr&" + "login="******"&" + "passwd=" + password; String resultString = HttpUtils.performHttpGet(cs); String[] nameValuePairs = StringUtils.tokenize(resultString, '\n', true); if (nameValuePairs.length == 1) { try { if (Integer.parseInt(nameValuePairs[0]) == 100) // NO USERNAME GIVEN throw new MessengerException(MessengerException.NO_USERNAME_GIVEN); else if (Integer.parseInt(nameValuePairs[0]) == 1235) // UNKNOWN USERNAME throw new MessengerException(MessengerException.UNKNOWN_USERNAME, "Unknown username"); else if (Integer.parseInt(nameValuePairs[0]) == 1212) // INCORRECT PASSWORD throw new MessengerException(MessengerException.INCORRECT_PASSWORD, "Incorrect password"); else // UNKNOWN ERROR throw new MessengerException(MessengerException.UNKNOWN_ERROR, "Unknown error"); } catch (NumberFormatException e) { throw new MessengerException(MessengerException.UNKNOWN_ERROR, "Unknown error"); } } else if (nameValuePairs.length == 3) { String token = StringUtils.getValue(nameValuePairs[1], "ymsg"); return token; } else { throw new MessengerException(MessengerException.UNKNOWN_ERROR, "Unknown error"); } }
/** * @param refreshToken 重新获取token * @return */ public static String refreshAccessToken(String refreshToken) { String rs = ""; NameValuePair[] params = { new NameValuePair("client_id", GmailConstants.CONSUMER_KEY), new NameValuePair("client_secret", GmailConstants.CONSUMER_SECRET), new NameValuePair("refresh_token", refreshToken), new NameValuePair("grant_type", "refresh_token"), }; try { JSONObject json = JSONObject.fromObject(HttpUtils.postMethod(GmailConstants.GET_TOKEN_URL, params)); String accessToken = json.getString("access_token").trim(); // TODO: 更新token值 rs = accessToken; } catch (IOException e) { logger.error("get token failed. ", e); } return rs; }
/** * 为入库冲单生成入生成半成品 * * @throws IOException */ public void generateBom() throws IOException { List<ZgTstorageCanclebomEx> bomECancleList = (List<ZgTstorageCanclebomEx>) this.getSession().getAttribute("bomECancleList"); for (int i = 0; i < items.length; i++) { Hashtable params = HttpUtils.parseQueryString(items[i]); ZgTstorageCanclebomEx obj = new ZgTstorageCanclebomEx(); String cuid = zgTorderPlanbomExBo.getCUID(); obj.setCuid(cuid); obj.setAufnr((java.lang.String) params.get("aufnr")); obj.setArbpl((java.lang.String) params.get("arbpl")); obj.setStorageId((java.lang.String) params.get("storageId")); obj.setMatnr((java.lang.String) params.get("matnr")); obj.setIdnrk((java.lang.String) params.get("idnrk")); obj.setMsehl1((java.lang.String) params.get("msehl1")); obj.setAllNum(Double.parseDouble((java.lang.String) params.get("allNum"))); obj.setNum(Double.parseDouble((java.lang.String) params.get("allNum"))); obj.setOrderBomId((java.lang.String) params.get("orderBomId")); obj.setStorageCancleId((java.lang.String) params.get("storageCancleId")); obj.setLgort((String) params.get("lgort")); obj.setIsModity(true); bomECancleList.add(obj); } this.getSession().setAttribute("bomECancleList", bomECancleList); // 保存bomIds到session中,用于页面展示可选bom的时候过滤 String bomECancleIds = ""; for (ZgTstorageCanclebomEx obj : bomECancleList) { if (!obj.getIsDel()) { bomECancleIds = bomECancleIds + obj.getStorageId() + obj.getOrderBomId() + ","; } } this.getSession().setAttribute("bomECancleIds", bomECancleIds); returnMsgAndCloseWindow("操作成功"); }
/** * @param code 调用https://accounts.google.com/o/oauth2/auth授权接口获取的code * @return 存储获取的token 和 refresh_token 返回token值 */ public static UserToken getAccessTokenByCode(String code) { UserToken ut = null; NameValuePair[] params = { new NameValuePair("code", code), new NameValuePair("client_id", GmailConstants.CONSUMER_KEY), new NameValuePair("client_secret", GmailConstants.CONSUMER_SECRET), new NameValuePair("redirect_uri", GmailConstants.REDIRECT_URL), new NameValuePair("grant_type", "authorization_code"), }; try { JSONObject json = JSONObject.fromObject(HttpUtils.postMethod(GmailConstants.GET_TOKEN_URL, params)); String accessToken = json.getString("access_token").trim(); String refreshToken = json.getString("refresh_token").trim(); ut = new UserToken(); ut.setAccessToken(accessToken); ut.setRefreshToken(refreshToken); ut.setCode(code); } catch (IOException e) { logger.error("get token failed. ", e); } return ut; }