List of usage examples for java.net URLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:com.krawler.spring.mailIntegration.mailIntegrationController.java
public String addUserEntryForEmails(String loginid, User user, UserLogin userLogin, String pwdtext, boolean isPasswordText) throws ServiceException { String returnStr = ""; try {/*from w ww .j a va 2s . c om*/ String baseURLFormat = storageHandlerImpl.GetSOAPServerUrl(); String url = baseURLFormat + "defaultUserEntry.php"; URL u = new URL(url); URLConnection uc = u.openConnection(); uc.setDoOutput(true); uc.setUseCaches(false); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String userName = userLogin.getUserName() + "_" + user.getCompany().getSubDomain(); String strParam = "loginid=" + loginid + "&userid=" + user.getUserID() + "&username=" + userName + "&password=" + userLogin.getPassword() + "&pwdtext=" + pwdtext + "&fullname=" + (user.getFirstName() + user.getLastName()) + "&isadmin=0&ispwdtest=" + isPasswordText; PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.println(strParam); pw.close(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line = ""; while ((line = in.readLine()) != null) { returnStr += line; } in.close(); returnStr = returnStr.replaceAll("\\s+", " ").trim(); JSONObject emailresult = new JSONObject(returnStr); if (Boolean.parseBoolean(emailresult.getString("success"))) { user.setUser_hash(emailresult.getString("pwd")); } } catch (IOException e) { throw ServiceException.FAILURE(e.getMessage(), e); } catch (JSONException e) { throw ServiceException.FAILURE(e.getMessage(), e); } return returnStr; }
From source file:org.spoutcraft.launcher.api.util.Download.java
@SuppressWarnings("unused") public void run() { ReadableByteChannel rbc = null; FileOutputStream fos = null;// ww w . j a va2s. com try { URLConnection conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(false); System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); HttpURLConnection.setFollowRedirects(true); conn.setUseCaches(false); ((HttpURLConnection) conn).setInstanceFollowRedirects(true); int response = ((HttpURLConnection) conn).getResponseCode(); InputStream in = getConnectionInputStream(conn); size = conn.getContentLength(); outFile = new File(outPath); outFile.delete(); rbc = Channels.newChannel(in); fos = new FileOutputStream(outFile); stateChanged(); Thread progress = new MonitorThread(Thread.currentThread(), rbc); progress.start(); fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE); in.close(); rbc.close(); progress.interrupt(); if (size > 0) { if (size == outFile.length()) { result = Result.SUCCESS; } } else { result = Result.SUCCESS; } } catch (PermissionDeniedException e) { result = Result.PERMISSION_DENIED; } catch (DownloadException e) { result = Result.FAILURE; } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(rbc); } }
From source file:org.apache.xmlrpc.applet.SimpleXmlRpcClient.java
/** * Generate an XML-RPC request and send it to the server. Parse the result * and return the corresponding Java object. * * @exception XmlRpcException If the remote host returned a fault message. * @exception IOException If the call could not be made for lower level * problems.//from www .java 2 s . c om */ public Object execute(String method, Vector arguments) throws XmlRpcException, IOException { fault = false; long now = System.currentTimeMillis(); try { StringBuffer strbuf = new StringBuffer(); XmlWriter writer = new XmlWriter(strbuf); writeRequest(writer, method, arguments); byte[] request = strbuf.toString().getBytes(); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setAllowUserInteraction(false); con.setRequestProperty("Content-Length", Integer.toString(request.length)); con.setRequestProperty("Content-Type", "text/xml"); // con.connect (); OutputStream out = con.getOutputStream(); out.write(request); out.flush(); InputStream in = con.getInputStream(); parse(in); System.out.println("result = " + result); } catch (Exception x) { x.printStackTrace(); throw new IOException(x.getMessage()); } if (fault) { // generate an XmlRpcException XmlRpcException exception = null; try { Hashtable f = (Hashtable) result; String faultString = (String) f.get("faultString"); int faultCode = Integer.parseInt(f.get("faultCode").toString()); exception = new XmlRpcException(faultCode, faultString.trim()); } catch (Exception x) { throw new XmlRpcException(0, "Invalid fault response"); } throw exception; } System.out.println("Spent " + (System.currentTimeMillis() - now) + " in request"); return result; }
From source file:net.librec.conf.Configuration.java
private void loadProperty(Properties properties, Resource wrapper) { Object resource = wrapper.getResource(); try {/*from ww w. ja va 2 s . co m*/ InputStream fis; if (resource instanceof URL) { // an URL resource fis = ((URL) resource).openStream(); properties.load(fis); } else if (resource instanceof String) { // a CLASSPATH resource URL url = getResource((String) resource); if (url != null) { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { // Disable caching for JarURLConnection to avoid sharing // JarFile // with other users. connection.setUseCaches(false); } fis = connection.getInputStream(); properties.load(fis); } } else if (resource instanceof Path) { // a file resource fis = new FileInputStream(new File(((Path) resource).toUri().getPath())); properties.load(fis); } else if (resource instanceof InputStream) { fis = (InputStream) resource; properties.load(fis); } else if (resource instanceof Properties) { overlay(properties, (Properties) resource); } } catch (IOException e) { e.printStackTrace(); } }
From source file:org.spoutcraft.launcher.util.Download.java
@SuppressWarnings("unused") public void run() { ReadableByteChannel rbc = null; FileOutputStream fos = null;//from w w w . j a va2 s . c om try { URLConnection conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(false); System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); HttpURLConnection.setFollowRedirects(true); conn.setUseCaches(false); ((HttpURLConnection) conn).setInstanceFollowRedirects(true); int response = ((HttpURLConnection) conn).getResponseCode(); InputStream in = getConnectionInputStream(conn); size = conn.getContentLength(); outFile = new File(outPath); outFile.delete(); rbc = Channels.newChannel(in); fos = new FileOutputStream(outFile); stateChanged(); Thread progress = new MonitorThread(Thread.currentThread(), rbc); progress.start(); fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE); in.close(); rbc.close(); progress.interrupt(); if (size > 0) { if (size == outFile.length()) { result = Result.SUCCESS; } } else { result = Result.SUCCESS; } } catch (PermissionDeniedException e) { exception = e; result = Result.PERMISSION_DENIED; } catch (DownloadException e) { exception = e; result = Result.FAILURE; } catch (Exception e) { exception = e; e.printStackTrace(); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(rbc); } }
From source file:com.jeeframework.util.xml.XMLProperties.java
/** * Creates a new XMLPropertiesTest object. * * @param fileName the full path the file that properties should be read from * and written to./*from w w w.j a va 2 s .co m*/ * @throws IOException if an error occurs loading the properties. */ public XMLProperties(String fileName) throws IOException { Assert.notNull(fileName, "fileName must not be null"); ClassLoader clToUse = ClassUtils.getDefaultClassLoader(); URL url = clToUse.getResource(fileName); if (url == null) { throw new FileNotFoundException(fileName + " not found "); } InputStream is = null; try { URLConnection con = url.openConnection(); con.setUseCaches(false); is = con.getInputStream(); Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); buildDoc(reader); } finally { if (is != null) { is.close(); } } }
From source file:mfi.filejuggler.responsibles.BasicApplication.java
@Responsible(conditions = { Condition.VIEW_LICENCE_ATTRIBUTION }) public void fjLizenzbedingungenAnzeigen(StringBuilder sb, Map<String, String> parameters, Model model) throws Exception { Condition back;// w ww . j a v a 2 s .co m if (model.lookupConversation().getStepBackCondition() != null) { back = model.lookupConversation().getStepBackCondition(); } else { if (model.getUser() != null) { back = Condition.FS_NAVIGATE; } else { back = Condition.LOGIN; } } sb.append(HTMLUtils.buildMenuNar(model, "Lizenzen anzeigen / View Licence Attribution", back, null, true)); List<String> lines = null; try { String licence = ""; URL url = this.getClass().getClassLoader().getResource("licenseattribution.txt"); URLConnection resConn = url.openConnection(); resConn.setUseCaches(false); InputStream in = resConn.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); licence = writer.toString(); licence = StringUtils.remove(licence, "\r"); lines = Arrays.asList(StringUtils.split(licence, "\n")); } catch (IOException e) { logger.error("Error loading Resource licenseattribution.txt: ", e); } buildTextviewTable("Lizenzen anzeigen / View Licence Attribution", sb, model, lines, model.lookupConversation().isTextViewNumbers(), true, true); }
From source file:com.krawler.spring.mailIntegration.mailIntegrationController.java
public JSONObject getRecentEmailDetails(HttpServletRequest request, String recid, String emailadd) throws ServiceException { JSONObject jobj = new JSONObject(); try {/*from w ww.ja v a2s . com*/ DateFormat userdft = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT+00:00")); String dateFormatId = sessionHandlerImpl.getDateFormatID(request); String timeFormatId = sessionHandlerImpl.getUserTimeFormat(request); String timeZoneDiff = sessionHandlerImpl.getTimeZoneDifference(request); String userid = sessionHandlerImpl.getUserid(request); userdft = KwlCommonTablesDAOObj.getUserDateFormatter(dateFormatId, timeFormatId, timeZoneDiff); String url = StorageHandler.GetSOAPServerUrl(); String res = ""; String str = ""; String pass = ""; String currUser = sessionHandlerImplObj.getUserName(request) + "_"; String jsonStr = profileHandlerDAOObj.getUser_hash(userid); //String emailadd = request.getParameter("email"); JSONObject currUserAuthInfo = new JSONObject(jsonStr); if (currUserAuthInfo.has("userhash")) { currUser += currUserAuthInfo.getString("subdomain"); pass = currUserAuthInfo.getString("userhash"); } str = "username=" + currUser + "&user_hash=" + pass; str = str + "&action=EmailUIAjax&emailUIAction=rebuildShowAccount&krawler_body_only=true&module=Emails&to_pdf=true"; URL u = new URL(url + "krawlermails.php"); URLConnection uc = u.openConnection(); uc.setDoOutput(true); uc.setUseCaches(false); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.println(str); pw.close(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line = ""; while ((line = in.readLine()) != null) { res += line; } in.close(); boolean flag = true; try { JSONArray jarr = new JSONArray(res); } catch (JSONException ex) { flag = false; } if (flag) { String ieId = ""; JSONArray jarr = new JSONArray(res); for (int cnt = 0; cnt < jarr.length(); cnt++) { JSONObject tempObj = jarr.getJSONObject(cnt); if (!StringUtil.isNullOrEmpty(tempObj.getString("value"))) { ieId += tempObj.getString("value") + ","; } } if (ieId.length() > 0) { ieId = ieId.substring(0, ieId.length() - 1); str = "username=" + currUser + "&user_hash=" + pass; str = str + "&ieId=" + ieId + "&fromaddr=" + emailadd + "&mbox=INBOX"; res = StringUtil.makeExternalRequest(url + "getSendersMails.php", str); } else { res = "{\"count\":0,\"data\":{}}"; } JSONObject resJobj = new JSONObject(); try { resJobj = new JSONObject(res); } catch (Exception ex) { resJobj = new JSONObject("{\"count\":0,\"data\":{}}"); } JSONArray FinalArr = new JSONArray(); if (resJobj.optInt("count", 0) > 0) { JSONArray jArr = resJobj.getJSONArray("data"); for (int i = 0; i < jArr.length(); i++) { JSONObject tmpobj = jArr.getJSONObject(i); Date sendDateObj = sdf.parse(tmpobj.getString("senddate")); String senddate = userdft.format(sendDateObj); JSONObject obj = new JSONObject(); obj.put("docid", tmpobj.getString("imap_uid")); obj.put("subject", tmpobj.getString("subject")); obj.put("fromaddr", tmpobj.getString("fromaddr")); obj.put("toaddr", tmpobj.getString("toaddr")); obj.put("senddate", senddate); obj.put("ie_id", tmpobj.getString("ie_id")); obj.put("seen", tmpobj.getString("seen")); // obj.put("time", AuthHandler.getUserDateFormatter(request, session).format(sdf.parse(tmpobj.getString("senddate")))); obj.put("time", senddate); obj.put("timeobj", sendDateObj); obj.put("details", tmpobj.getString("subject")); obj.put("folder", "Inbox"); obj.put("imgsrc", "../../images/inbox.png"); FinalArr.put(obj); } } // fetched Sent Items // get sent folder id // String sentid = ""; // str = "username="+currUser+"&user_hash="+pass; // str = str + "&action=EmailUIAjax&emailUIAction=refreshKrawlerFolders&krawler_body_only=true&module=Emails&to_pdf=true"; // res = StringUtil.makeExternalRequest(url+"getSendersMails.php",str); // resJobj = new JSONObject(res); // if(resJobj.has("children")) { // JSONArray childArray = resJobj.getJSONArray("children"); // for(int cnt = 0; cnt< childArray.length(); cnt++) { // if(childArray.getJSONObject(cnt).getString("folder_type").equals("folder_type")) { // sentid = childArray.getJSONObject(cnt).getString("folder_type"); // } // } // } // // if(!StringUtil.isNullOrEmpty(sentid)) { // str = "username="+currUser+"&user_hash="+pass; // str = str + "&action=EmailUIAjax&emailUIAction=getMessageListKrawlerFoldersXML&module=Emails&to_pdf=true&start=0&limit=20&forceRefresh=false&mbox=Sent%20Emails&ieId="+sentid; // res = StringUtil.makeExternalRequest(url+"krawlermails.php",str); // } str = "userid=" + userid + "&username=" + currUser + "&user_hash=" + pass; str = str + "&fromaddr=" + emailadd + "&mbox=sent"; res = StringUtil.makeExternalRequest(url + "getSendersMails.php", str); try { resJobj = new JSONObject(res); } catch (Exception ex) { resJobj = new JSONObject("{\"count\":0,\"data\":{}}"); } if (resJobj.optInt("count", 0) > 0) { JSONArray jArr = resJobj.getJSONArray("data"); for (int i = 0; i < jArr.length(); i++) { JSONObject tmpobj = jArr.getJSONObject(i); Date sendDateObj = sdf.parse(tmpobj.getString("date_sent")); String senddate = userdft.format(sendDateObj); JSONObject obj = new JSONObject(); obj.put("docid", tmpobj.getString("id")); obj.put("subject", tmpobj.getString("name")); obj.put("fromaddr", tmpobj.getString("from_addr")); obj.put("toaddr", tmpobj.getString("to_addrs")); obj.put("senddate", senddate); // obj.put("ie_id", tmpobj.getString("ieId")); obj.put("seen", tmpobj.getString("status").equals("unread") ? 0 : 1); obj.put("time", senddate); obj.put("details", tmpobj.getString("name")); obj.put("timeobj", sendDateObj); obj.put("folder", "Sent Item"); obj.put("imgsrc", "../../images/outbox.png"); FinalArr.put(obj); } } for (int i = 0; i < FinalArr.length(); i++) { for (int j = 0; j < FinalArr.length(); j++) { if (((Date) (FinalArr.getJSONObject(i).get("timeobj"))) .after((Date) (FinalArr.getJSONObject(j).get("timeobj")))) { JSONObject jobj1 = FinalArr.getJSONObject(i); FinalArr.put(i, FinalArr.getJSONObject(j)); FinalArr.put(j, jobj1); } } } jobj.put("emailList", FinalArr); } else { jobj.put("emailList", new JSONArray()); } } catch (JSONException e) { throw ServiceException.FAILURE(e.getMessage(), e); } catch (SessionExpiredException e) { throw ServiceException.FAILURE(e.getMessage(), e); } catch (HibernateException e) { throw ServiceException.FAILURE(e.getMessage(), e); } catch (Exception e) { throw ServiceException.FAILURE(e.getMessage(), e); } return jobj; }
From source file:org.ixdhof.speechrecognizer.Recognizer.java
private void do_recognize(String waveString, String language) throws Exception { //"en-US"// w w w .j a v a2s .c o m URL url; URLConnection urlConn; OutputStream outputStream; BufferedReader br; File waveFile = new File(parent.sketchPath(waveString)); FlacEncoder flacEncoder = new FlacEncoder(); File flacFile = new File(waveFile + ".flac"); flacEncoder.convertWaveToFlac(waveFile, flacFile); // URL of Remote Script. url = new URL(GOOGLE_RECOGNIZER_URL_NO_LANG + language); // Open New URL connection channel. urlConn = url.openConnection(); // we want to do output. urlConn.setDoOutput(true); // No caching urlConn.setUseCaches(false); // Specify the header content type. urlConn.setRequestProperty("Content-Type", "audio/x-flac; rate=8000"); // Send POST output. outputStream = urlConn.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(flacFile.getAbsolutePath()); byte[] buffer = new byte[256]; while ((fileInputStream.read(buffer, 0, 256)) != -1) { outputStream.write(buffer, 0, 256); } fileInputStream.close(); outputStream.close(); // Get response data. br = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); response = br.readLine(); br.close(); flacFile.delete(); waveFile.delete(); try { JSONParser parser = new JSONParser(); Object obj = parser.parse(response); JSONObject jsonObject = (JSONObject) obj; HashMap returnValues = new HashMap(); if (response.contains("utterance")) { status = (int) (long) (Long) jsonObject.get("status"); id = (String) jsonObject.get("id"); JSONArray hypotheses_array = (JSONArray) jsonObject.get("hypotheses"); JSONObject hypotheses = (JSONObject) hypotheses_array.get(0); utterance = (String) hypotheses.get("utterance"); confidence = (float) (double) (Double) hypotheses.get("confidence"); } else { utterance = null; } if (recognizerEvent != null) { try { recognizerEvent.invoke(parent, new Object[] { utterance }); } catch (Exception e) { System.err.println("Disabling recognizerEvent()"); e.printStackTrace(); recognizerEvent = null; } } } catch (Exception e) { parent.println(e); } recognizing = false; }