label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: protected long getUrlSize(String location) { long returnValue = 0L; try { URL url = new URL(location); java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); returnValue = conn.getContentLength(); } catch (IOException ioe) { logger.error("Failed to find proper size for entity at " + location, ioe); } return returnValue; } Code Sample 2: public static void copyFile(File from, File to) { try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024 * 16]; int read = 0; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public void initGet() throws Exception { cl = new FTPClient(); URL url = new URL(getURL()); cl.setRemoteHost(url.getHost()); cl.connect(); cl.login(user, pass); cl.setType(FTPTransferType.BINARY); cl.setConnectMode(FTPConnectMode.PASV); cl.restart(getPosition()); }
11
Code Sample 1: private static void replaceEntityMappings(File signserverearpath, File entityMappingXML) throws ZipException, IOException { ZipInputStream earFile = new ZipInputStream(new FileInputStream(signserverearpath)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream tempZip = new ZipOutputStream(baos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("signserver-ejb.jar")) { content = replaceEntityMappings(content, entityMappingXML); next = new ZipEntry("signserver-ejb.jar"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); FileOutputStream fos = new FileOutputStream(signserverearpath); fos.write(baos.toByteArray()); fos.close(); } Code Sample 2: public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; }
11
Code Sample 1: public List<SuspectFileProcessingStatus> retrieve() throws Exception { BufferedOutputStream bos = null; try { String listFilePath = GeneralUtils.generateAbsolutePath(getDownloadDirectoryPath(), getListName(), "/"); listFilePath = listFilePath.concat(".xml"); if (!new File(getDownloadDirectoryPath()).exists()) { FileUtils.forceMkdir(new File(getDownloadDirectoryPath())); } FileOutputStream listFileOutputStream = new FileOutputStream(listFilePath); bos = new BufferedOutputStream(listFileOutputStream); InputStream is = null; if (getUseProxy()) { is = URLUtils.getResponse(getUrl(), getUserName(), getPassword(), URLUtils.HTTP_GET_METHOD, getProxyHost(), getProxyPort()); IOUtils.copyLarge(is, bos); } else { URLUtils.getResponse(getUrl(), getUserName(), getPassword(), bos, null); } bos.flush(); bos.close(); File listFile = new File(listFilePath); if (!listFile.exists()) { throw new IllegalStateException("The list file did not get created"); } if (isLoggingInfo()) { logInfo("Downloaded list file : " + listFile); } List<SuspectFileProcessingStatus> sfpsList = new ArrayList<SuspectFileProcessingStatus>(); String loadType = GeneralConstants.LOAD_TYPE_FULL; String feedType = GeneralConstants.EMPTY_TOKEN; String listName = getListName(); String errorCode = ""; String description = ""; SuspectFileProcessingStatus sfps = getSuspectsLoaderService().storeFileIntoListIncomingDir(listFile, loadType, feedType, listName, errorCode, description); sfpsList.add(sfps); if (isLoggingInfo()) { logInfo("Retrieved list file with SuspectFileProcessingStatus: " + sfps); } return sfpsList; } finally { if (null != bos) { bos.close(); } } } Code Sample 2: protected void writeToResponse(InputStream stream, HttpServletResponse response) throws IOException { OutputStream output = response.getOutputStream(); try { IOUtils.copy(stream, output); } finally { try { stream.close(); } finally { output.close(); } } }
00
Code Sample 1: public static String getTextFromUrl(final String url) throws IOException { final String lineSeparator = System.getProperty("line.separator"); InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(line).append(lineSeparator); } return result.toString(); } finally { InputOutputUtil.close(bufferedReader, inputStreamReader); } } Code Sample 2: public static String shaEncrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] shahash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } shahash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < shahash.length; i++) { if (Integer.toHexString(0xFF & shahash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & shahash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & shahash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; }
00
Code Sample 1: public HttpURLConnection getURLConnection() throws IOException { String url_str = getServerURL(); URL url = new URL(url_str); HttpURLConnection urlConnection; if (url_str.toLowerCase().startsWith("https")) { HttpsURLConnection urlSConnection = (HttpsURLConnection) url.openConnection(); urlSConnection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); urlConnection = urlSConnection; } else urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); if (useHTTPProxy && getProxyLogin() != null) { String authString = getProxyLogin() + ":" + getProxyPassword(); String auth = "Basic " + new sun.misc.BASE64Encoder().encode(authString.getBytes()); urlConnection.setRequestProperty("Proxy-Authorization", auth); } urlConnection.setDoOutput(true); if (useHTTPProxy) { System.getProperties().put("proxySet", "true"); System.getProperties().put("proxyHost", proxyHost); System.getProperties().put("proxyPort", String.valueOf(proxyPort)); } return urlConnection; } Code Sample 2: public void addGames(List<Game> games) throws StadiumException, SQLException { Connection conn = ConnectionManager.getManager().getConnection(); conn.setAutoCommit(false); PreparedStatement stm = null; ResultSet rs = null; try { for (Game game : games) { stm = conn.prepareStatement(Statements.SELECT_STADIUM); stm.setString(1, game.getStadiumName()); stm.setString(2, game.getStadiumCity()); rs = stm.executeQuery(); int stadiumId = -1; while (rs.next()) { stadiumId = rs.getInt("stadiumID"); } if (stadiumId == -1) throw new StadiumException("No such stadium"); stm = conn.prepareStatement(Statements.INSERT_GAME); stm.setInt(1, stadiumId); stm.setDate(2, game.getGameDate()); stm.setTime(3, game.getGameTime()); stm.setString(4, game.getTeamA()); stm.setString(5, game.getTeamB()); stm.executeUpdate(); int gameId = getMaxId(); List<SectorPrice> sectorPrices = game.getSectorPrices(); for (SectorPrice price : sectorPrices) { stm = conn.prepareStatement(Statements.INSERT_TICKET_PRICE); stm.setInt(1, gameId); stm.setInt(2, price.getSectorId()); stm.setInt(3, price.getPrice()); stm.executeUpdate(); } } } catch (SQLException e) { conn.rollback(); throw e; } finally { rs.close(); stm.close(); } conn.commit(); conn.setAutoCommit(true); }
00
Code Sample 1: public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { if (list[i].lastIndexOf(SVN) != -1) { if (!SVN.equalsIgnoreCase(list[i].substring(list[i].length() - 4, list[i].length()))) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } else { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } } Code Sample 2: private String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } }
11
Code Sample 1: private void deleteProject(String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception { String project = request.getParameter("project"); String line; response.setContentType("text/html"); PrintWriter out = response.getWriter(); htmlHeader(out, "Project Status", ""); try { synchronized (Class.forName("com.sun.gep.SunTCP")) { Vector list = new Vector(); String directory = home; Runtime.getRuntime().exec("/usr/bin/rm -rf " + directory + project); FilePermission perm = new FilePermission(directory + SUNTCP_LIST, "read,write,execute"); File listfile = new File(directory + SUNTCP_LIST); BufferedReader read = new BufferedReader(new FileReader(listfile)); while ((line = read.readLine()) != null) { if (!((new StringTokenizer(line, "\t")).nextToken().equals(project))) { list.addElement(line); } } read.close(); if (list.size() > 0) { PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(listfile))); for (int i = 0; i < list.size(); i++) { write.println((String) list.get(i)); } write.close(); } else { listfile.delete(); } out.println("The project was successfully deleted."); } } catch (Exception e) { out.println("Error accessing this project."); } out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>"); htmlFooter(out); } Code Sample 2: public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
11
Code Sample 1: public static boolean dumpFile(String from, File to, String lineBreak) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(from))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to))); String line = null; while ((line = in.readLine()) != null) out.write(Main.getInstance().resolve(line) + lineBreak); in.close(); out.close(); } catch (Exception e) { Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e)); return false; } return true; } Code Sample 2: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); }
00
Code Sample 1: public void SendFile(File testfile) { try { SocketChannel sock = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1234)); sock.configureBlocking(true); while (!sock.finishConnect()) { System.out.println("NOT connected!"); } System.out.println("CONNECTED!"); FileInputStream fis = new FileInputStream(testfile); FileChannel fic = fis.getChannel(); long len = fic.size(); Buffer.clear(); Buffer.putLong(len); Buffer.flip(); sock.write(Buffer); long cnt = 0; while (cnt < len) { Buffer.clear(); int add = fic.read(Buffer); cnt += add; Buffer.flip(); while (Buffer.hasRemaining()) { sock.write(Buffer); } } fic.close(); File tmpfile = getTmp().createNewFile("tmp", "tmp"); FileOutputStream fos = new FileOutputStream(tmpfile); FileChannel foc = fos.getChannel(); int mlen = -1; do { Buffer.clear(); mlen = sock.read(Buffer); Buffer.flip(); if (mlen > 0) { foc.write(Buffer); } } while (mlen > 0); foc.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public DataSetInfo(String request) throws AddeURLException { URLConnection urlc; BufferedReader reader; debug = debug || request.indexOf("debug=true") >= 0; try { URL url = new URL(request); urlc = url.openConnection(); reader = new BufferedReader(new InputStreamReader(urlc.getInputStream())); } catch (AddeURLException ae) { status = -1; throw new AddeURLException("No datasets found"); } catch (Exception e) { status = -1; throw new AddeURLException("Error opening connection: " + e); } int numBytes = ((AddeURLConnection) urlc).getInitialRecordSize(); if (debug) System.out.println("DataSetInfo: numBytes = " + numBytes); if (numBytes == 0) { status = -1; throw new AddeURLException("No datasets found"); } else { data = new char[numBytes]; try { int start = 0; while (start < numBytes) { int numRead = reader.read(data, start, (numBytes - start)); if (debug) System.out.println("bytes read = " + numRead); start += numRead; } } catch (IOException e) { status = -1; throw new AddeURLException("Error reading dataset info:" + e); } int numNames = data.length / 80; descriptorTable = new Hashtable(numNames); if (debug) System.out.println("Number of descriptors = " + numNames); for (int i = 0; i < numNames; i++) { String temp = new String(data, i * 80, 80); if (debug) System.out.println("Parsing: >" + temp + "<"); if (temp.trim().equals("")) continue; String descriptor = temp.substring(0, 12).trim(); if (debug) System.out.println("Descriptor = " + descriptor); String comment = descriptor; int pos = temp.indexOf('"'); if (debug) System.out.println("Found quote at " + pos); if (pos >= 23) { comment = temp.substring(pos + 1).trim(); if (comment.equals("")) comment = descriptor; } if (debug) System.out.println("Comment = " + comment); descriptorTable.put(comment, descriptor); } } }
00
Code Sample 1: String fetch_m3u(String m3u) { InputStream pstream = null; if (m3u.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), m3u); else url = new URL(m3u); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + m3u); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; return line; } return null; } Code Sample 2: public void run() { if (software == null) return; Jvm.hashtable(HKEY).put(software, this); try { software.setException(null); software.setDownloaded(false); software.setDownloadStartTime(System.currentTimeMillis()); try { software.downloadStarted(); } catch (Exception dsx) { } if (software.getDownloadDir() == null) { software.setException(new Exception("The DownloadDir is null.")); software.setDownloadStartTime(0); software.setDownloaded(false); throw software.getException(); } URL url = new URL(software.getURL()); URLConnection con = url.openConnection(); software.setDownloadLength(con.getContentLength()); inputStream = con.getInputStream(); File file = new File(software.getDownloadDir(), software.getURLFilename()); outputStream = new FileOutputStream(file); int totalBytes = 0; byte[] buffer = new byte[8192]; while (!cancelled) { int bytesRead = Jvm.copyPartialStream(inputStream, outputStream, buffer); if (bytesRead == -1) break; totalBytes += bytesRead; try { software.downloadProgress(totalBytes); } catch (Exception dx) { } } if (!cancelled) software.setDownloaded(true); } catch (Exception x) { software.setException(x); software.setDownloadStartTime(0); software.setDownloaded(false); } try { software.downloadComplete(); } catch (Exception dcx) { } Jvm.hashtable(HKEY).remove(software); closeStreams(); }
11
Code Sample 1: public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; } Code Sample 2: protected static void copyFile(File in, File out) throws IOException { java.io.FileWriter filewriter = null; java.io.FileReader filereader = null; try { filewriter = new java.io.FileWriter(out); filereader = new java.io.FileReader(in); char[] buf = new char[4096]; int nread = filereader.read(buf, 0, 4096); while (nread >= 0) { filewriter.write(buf, 0, nread); nread = filereader.read(buf, 0, 4096); } buf = null; } finally { try { filereader.close(); } catch (Throwable t) { } try { filewriter.close(); } catch (Throwable t) { } } }
00
Code Sample 1: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: public static void replaceAll(File file, String substitute, String substituteReplacement) throws IOException { log.debug("Replace " + substitute + " by " + substituteReplacement); Pattern pattern = Pattern.compile(substitute); FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); int sz = (int) fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); Charset charset = Charset.forName("ISO-8859-15"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer cb = decoder.decode(bb); Matcher matcher = pattern.matcher(cb); String outString = matcher.replaceAll(substituteReplacement); log.debug(outString); FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); PrintStream ps = new PrintStream(fos); ps.print(outString); ps.close(); fos.close(); }
00
Code Sample 1: public void authenticate(final ConnectionHandler ch, final AuthenticationCriteria ac) throws NamingException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(this.passwordScheme); md.update(((String) ac.getCredential()).getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new NamingException(e.getMessage()); } ch.connect(this.config.getBindDn(), this.config.getBindCredential()); NamingEnumeration<SearchResult> en = null; try { en = ch.getLdapContext().search(ac.getDn(), "userPassword={0}", new Object[] { String.format("{%s}%s", this.passwordScheme, LdapUtil.base64Encode(hash)).getBytes() }, LdapConfig.getCompareSearchControls()); if (!en.hasMore()) { throw new AuthenticationException("Compare authentication failed."); } } finally { if (en != null) { en.close(); } } } Code Sample 2: public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); String username = "test"; String password = "test"; int providerId = 1; if (request.getParameter("providerId") != null) providerId = Integer.parseInt(request.getParameter("providerId")); String thisPageContextAddress = "http://localhost:8080" + request.getContextPath(); String thisPageServingAddress = thisPageContextAddress + "/index.jsp"; String token = ""; String token_timeout = (String) request.getParameter("token_timeout"); String referer = request.getHeader("Referer"); if (token_timeout != null && token_timeout.equals("true")) { System.out.println("token timeout for referer" + referer); if (referer != null) { if (request.getSession().getServletContext().getAttribute("token_timeout_processing_lock") == null) { request.getSession().getServletContext().setAttribute("token_timeout_processing_lock", true); byte[] buff = null; BufferedInputStream bis = null; URL url = new URL(thisPageContextAddress + "/ServerAdminServlet?action=login&username=" + username + "&password=" + password); URLConnection urlc = url.openConnection(); int length = urlc.getContentLength(); InputStream in = urlc.getInputStream(); buff = new byte[length]; int bytesRead = 0; while (bytesRead < length) { bytesRead += in.read(buff, bytesRead, in.available()); } token = new String(buff); token = token.replaceAll("[\\r\\f]", ""); token = token.trim(); request.getSession().getServletContext().setAttribute("token", token); out.println(token); request.getSession().getServletContext().removeAttribute("token_timeout_processing_lock"); } else out.println("token_timeout_processing_lock"); } } else { if (request.getSession().getServletContext().getAttribute("token") == null || request.getSession().getServletContext().getAttribute("token").equals("")) { byte[] buff = null; BufferedInputStream bis = null; URL url = new URL(thisPageContextAddress + "/ServerAdminServlet?action=login&username=" + username + "&password=" + password); URLConnection urlc = url.openConnection(); int length = urlc.getContentLength(); InputStream in = urlc.getInputStream(); buff = new byte[length]; int bytesRead = 0; while (bytesRead < length) { bytesRead += in.read(buff, bytesRead, in.available()); } token = new String(buff); token = token.replaceAll("[\\r\\f]", ""); token = token.trim(); request.getSession().getServletContext().setAttribute("token", token); } out.write("\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <title>AJAX test </title>\n"); out.write(" <link rel=\"stylesheet\" href=\"css/default.css\" type=\"text/css\" />\n"); out.write("\n"); out.write(" <script type=\"text/javascript\" src=\"../OpenLayers-2.8/OpenLayers.js\"></script>\n"); out.write(" <script type=\"text/javascript\">\n"); out.write("\n"); out.write(" var map, layer;\n"); out.write("\n"); out.write(" var token = \""); out.print(request.getSession().getServletContext().getAttribute("token")); out.write("\";\n"); out.write("\n"); out.write("\n"); out.write(" function init(){\n"); out.write("\n"); out.write(" OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;\n"); out.write("\n"); out.write(" var options = {\n"); out.write(" maxExtent: new OpenLayers.Bounds(0, 0, 3000000, 9000000),\n"); out.write(" tileSize :new OpenLayers.Size(250, 250),\n"); out.write(" units: 'm',\n"); out.write(" projection: 'EPSG:3006',\n"); out.write(" resolutions : [1.3,2.6,4,6.6,13.2,26.5,66.1,132.3,264.6,793.8,1322.9,2645.8,13229.2,26458.3]\n"); out.write(" }\n"); out.write("\n"); out.write(" map = new OpenLayers.Map('swedenMap', options);\n"); out.write("\n"); out.write(" layer = new OpenLayers.Layer.TMS(\"TMS\", \"http://localhost:8080/WebGISTileServer/TMSServletProxy/\",\n"); out.write(" { layername: token + '/7', type: 'png' });\n"); out.write("\n"); out.write(" map.addLayer(layer);\n"); out.write("\n"); out.write(" map.addControl( new OpenLayers.Control.PanZoom() );\n"); out.write(" map.addControl( new OpenLayers.Control.PanZoomBar() );\n"); out.write(" map.addControl( new OpenLayers.Control.MouseDefaults());\n"); out.write(" map.addControl( new OpenLayers.Control.MousePosition());\n"); out.write("\n"); out.write(" map.setCenter(new OpenLayers.LonLat(555555, 6846027), 2);\n"); out.write(" }\n"); out.write(" </script>\n"); out.write(" </head>\n"); out.write(" <body onload=\"init()\">\n"); out.write("\n"); out.write(" <div id=\"container\">\n"); out.write("\n"); out.write(" <div id=\"header\">\n"); out.write(" <h1 id=\"logo\">\n"); out.write(" <span>ASP</span> MapServices\n"); out.write(" <small>Web mapping. <span>EASY</span></small>\n"); out.write(" </h1>\n"); out.write("\n"); out.write(" <ul id=\"menu\">\n"); out.write(" <li><a href=\"default.html\">Home</a></li>\n"); out.write(" <li><a href=\"demo_world.jsp\">Demonstration</a></li>\n"); out.write(" <li style=\"border-right: none;\"><a href=\"contact.html\">Contact</a></li>\n"); out.write(" </ul>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div id=\"body\">\n"); out.write(" <ul id=\"maps-menu\">\n"); out.write(" <li><a href=\"demo_world.jsp\">World</a></li>\n"); out.write(" <li><a href=\"demo_sweden_rt90.jsp\">Sweden RT90</a></li>\n"); out.write(" <li><a href=\"demo_sweden_sweref99.jsp\">Sweden SWEREF99</a></li>\n"); out.write(" </ul>\n"); out.write("\n"); out.write(" <div id=\"swedenMap\" style=\"height:600px\"></div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </body>\n"); out.write("\n"); out.write("\n"); out.write(" </head>\n"); out.write("\n"); out.write("</html>"); } out.write('\n'); out.write('\n'); } catch (Throwable t) { if (!(t instanceof SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
11
Code Sample 1: private void post(String title, Document content, Set<String> tags) throws HttpException, IOException, TransformerException { PostMethod method = null; try { method = new PostMethod("http://www.blogger.com/feeds/" + this.blogId + "/posts/default"); method.addRequestHeader("GData-Version", String.valueOf(GDataVersion)); method.addRequestHeader("Authorization", "GoogleLogin auth=" + this.AuthToken); Document dom = this.domBuilder.newDocument(); Element entry = dom.createElementNS(Atom.NS, "entry"); dom.appendChild(entry); entry.setAttribute("xmlns", Atom.NS); Element titleNode = dom.createElementNS(Atom.NS, "title"); entry.appendChild(titleNode); titleNode.setAttribute("type", "text"); titleNode.appendChild(dom.createTextNode(title)); Element contentNode = dom.createElementNS(Atom.NS, "content"); entry.appendChild(contentNode); contentNode.setAttribute("type", "xhtml"); contentNode.appendChild(dom.importNode(content.getDocumentElement(), true)); for (String tag : tags) { Element category = dom.createElementNS(Atom.NS, "category"); category.setAttribute("scheme", "http://www.blogger.com/atom/ns#"); category.setAttribute("term", tag); entry.appendChild(category); } StringWriter out = new StringWriter(); this.xml2ascii.transform(new DOMSource(dom), new StreamResult(out)); method.setRequestEntity(new StringRequestEntity(out.toString(), "application/atom+xml", "UTF-8")); int status = getHttpClient().executeMethod(method); if (status == 201) { IOUtils.copyTo(method.getResponseBodyAsStream(), System.out); } else { throw new HttpException("post returned http-code=" + status + " expected 201 (CREATE)"); } } catch (TransformerException err) { throw err; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } } Code Sample 2: public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel srcChannel = new FileInputStream(inputFile).getChannel(); FileChannel dstChannel = new FileOutputStream(outputFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } } Code Sample 2: public void writeFile(String resource, InputStream is) throws IOException { File f = prepareFsReferenceAsFile(resource); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); try { IOUtils.copy(is, bos); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(bos); } }
11
Code Sample 1: protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; } Code Sample 2: public static File writeInternalFile(Context cx, URL url, String dir, String filename) { FileOutputStream fos = null; File fi = null; try { fi = newInternalFile(cx, dir, filename); fos = FileUtils.openOutputStream(fi); int length = IOUtils.copy(url.openStream(), fos); log(length + " bytes copyed."); } catch (IOException e) { AIOUtils.log("", e); } finally { try { fos.close(); } catch (IOException e) { AIOUtils.log("", e); } } return fi; }
00
Code Sample 1: public InputSource resolveEntity(String pPublicId, String pSystemId) throws SAXException, IOException { getCisUtils().debug("Resolving entity publicId=" + pPublicId + ", systemId=" + pSystemId); final String res; if ("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN".equals(pPublicId)) { res = "resources/web-app_2_3.dtd"; } else { return null; } URL url = getClass().getResource(res); if (url == null) { throw new SAXException("Failed to locate resource: " + res); } InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toExternalForm()); return isource; } Code Sample 2: public static InputStream getResourceAsStream(final String fileName) { if ((fileName.indexOf("file:") >= 0) || (fileName.indexOf(":/") > 0)) { try { URL url = new URL(fileName); return new BufferedInputStream(url.openStream()); } catch (Exception e) { return null; } } return new ByteArrayInputStream(getResource(fileName).getData()); }
11
Code Sample 1: public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { } return ""; } Code Sample 2: private final String encryptPassword(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.log(Level.WARNING, "Error while obtaining decript algorithm", e); throw new RuntimeException("AccountData.encryptPassword()"); } try { md.update(pass.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { log.log(Level.WARNING, "Problem with decript algorithm occured.", e); throw new RuntimeException("AccountData.encryptPassword()"); } return new BASE64Encoder().encode(md.digest()); }
00
Code Sample 1: public void run() { String s; s = ""; try { URL url = new URL("http://www.askoxford.com/concise_oed/" + word.toLowerCase() + "?view=uk"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("<h2>" + word.toLowerCase() + "(.+?)<p><a href", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } button.setEnabled(true); } Code Sample 2: @SuppressWarnings("static-access") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { filename = URLDecoder.decode(filename, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { is = request.getInputStream(); File newFile = new File(realPath + filename); if (!newFile.exists()) { fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true,detailMsg}"); } else { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false,detailMsg:'文件已经存在!请重命名后上传!'}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + filename + " has existed!"); } } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
00
Code Sample 1: public void run() { try { System.out.println("Setting page on Cobra"); SimpleHtmlRendererContext rendererContext = new SimpleHtmlRendererContext(htmlPanel, new SimpleUserAgentContext()); int nodeBaseEnd = furl.indexOf("/", 10); if (nodeBaseEnd == -1) nodeBaseEnd = furl.length(); String nodeBase = furl.substring(0, nodeBaseEnd); InputStream pageStream = new URL(furl).openStream(); BufferedReader pageStreamReader = new BufferedReader(new InputStreamReader(pageStream)); String pageContent = ""; String line; while ((line = pageStreamReader.readLine()) != null) pageContent += line; pageContent = borderImages(pageContent, nodeBase); htmlPanel.setHtml(pageContent, furl, rendererContext); } catch (Exception e) { System.out.println("Error loading page " + furl + " : " + e); } } Code Sample 2: public static Map<String, List<String>> getResponseHeader(String address) { System.out.println(address); URLConnection conn = null; Map<String, List<String>> responseHeader = null; try { URL url = new URL(address); conn = url.openConnection(); responseHeader = conn.getHeaderFields(); } catch (Exception e) { e.printStackTrace(); } return responseHeader; }
00
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: private String _doPost(final String urlStr, final Map<String, String> params) { String paramsStr = ""; for (String key : params.keySet()) { try { paramsStr += URLEncoder.encode(key, ENCODING) + "=" + URLEncoder.encode(params.get(key), ENCODING) + "&"; } catch (UnsupportedEncodingException e) { s_logger.debug("UnsupportedEncodingException caught. Trying to encode: " + key + " and " + params.get(key)); return null; } } if (paramsStr.length() == 0) { s_logger.debug("POST will not complete, no parameters specified."); return null; } s_logger.debug("POST to server will be done with the following parameters: " + paramsStr); HttpURLConnection connection = null; String responseStr = null; try { connection = (HttpURLConnection) (new URL(urlStr)).openConnection(); connection.setRequestMethod(REQUEST_METHOD); connection.setDoOutput(true); DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); dos.write(paramsStr.getBytes()); dos.flush(); dos.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); responseStr = response.toString(); } catch (ProtocolException e) { s_logger.debug("ProtocolException caught. Unable to execute POST."); } catch (MalformedURLException e) { s_logger.debug("MalformedURLException caught. Unexpected. Url is: " + urlStr); } catch (IOException e) { s_logger.debug("IOException caught. Unable to execute POST."); } return responseStr; }
00
Code Sample 1: public void loginMD5() throws Exception { GetMethod get = new GetMethod("http://login.yahoo.com/config/login?.src=www&.done=http://www.yahoo.com"); get.setRequestHeader("user-agent", "Mozilla/5.0 (Macintosh; U; PPC MacOS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1"); client.executeMethod(get); parseResponse(get.getResponseBodyAsStream()); MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes("US-ASCII")); String hash1 = new String(digest.digest(), "US-ASCII"); String hash2 = hash1 + challenge; digest.update(hash2.getBytes("US-ASCII")); String hash = new String(digest.digest(), "US-ASCII"); NameValuePair[] pairs = { new NameValuePair("login", login), new NameValuePair("password", hash), new NameValuePair(".save", "1"), new NameValuePair(".tries", "1"), new NameValuePair(".src", "www"), new NameValuePair(".md5", "1"), new NameValuePair(".hash", "1"), new NameValuePair(".js", "1"), new NameValuePair(".last", ""), new NameValuePair(".promo", ""), new NameValuePair(".intl", "us"), new NameValuePair(".bypass", ""), new NameValuePair(".u", u), new NameValuePair(".v", "0"), new NameValuePair(".challenge", challenge), new NameValuePair(".yplus", ""), new NameValuePair(".emailCode", ""), new NameValuePair("pkg", ""), new NameValuePair("stepid", ""), new NameValuePair(".ev", ""), new NameValuePair("hasMsgr", "0"), new NameValuePair(".chkP", "Y"), new NameValuePair(".done", "http://www.yahoo.com"), new NameValuePair(".persistent", "y") }; get = new GetMethod("http://login.yahoo.com/config/login"); get.setRequestHeader("user-agent", "Mozilla/5.0 (Macintosh; U; PPC MacOS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1"); get.addRequestHeader("Accept", "*/*"); get.addRequestHeader("Accept-Language", "en-us, ja;q=0.21, de-de;q=0.86, de;q=0.79, fr-fr;q=0.71, fr;q=0.64, nl-nl;q=0.57, nl;q=0.50, it-it;q=0.43, it;q=0.36, ja-jp;q=0.29, en;q=0.93, es-es;q=0.14, es;q=0.07"); get.setQueryString(pairs); client.executeMethod(get); get.getResponseBodyAsString(); } Code Sample 2: private void dumpFile(File repository, File copy) { try { if (copy.exists() && !copy.delete()) { throw new RuntimeException("can't delete copy: " + copy); } printFile("Real Archive File", repository); new ZipArchive(repository.getPath()); IOUtils.copyFiles(repository, copy); printFile("Copy Archive File", copy); new ZipArchive(copy.getPath()); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public void testResponseTimeout() throws Exception { server.enqueue(new MockResponse().setBody("ABC").clearHeaders().addHeader("Content-Length: 4")); server.enqueue(new MockResponse().setBody("DEF")); server.play(); URLConnection urlConnection = server.getUrl("/").openConnection(); urlConnection.setReadTimeout(1000); InputStream in = urlConnection.getInputStream(); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); try { in.read(); fail(); } catch (SocketTimeoutException expected) { } URLConnection urlConnection2 = server.getUrl("/").openConnection(); InputStream in2 = urlConnection2.getInputStream(); assertEquals('D', in2.read()); assertEquals('E', in2.read()); assertEquals('F', in2.read()); assertEquals(-1, in2.read()); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(0, server.takeRequest().getSequenceNumber()); } Code Sample 2: @Test public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null, "UTF16"); fail(); } catch (NullPointerException ex) { } }
00
Code Sample 1: public void initGet() throws Exception { cl = new FTPClient(); cl.connect(getHostName()); Authentication auth = AuthManager.getAuth(getSite()); if (auth == null) auth = new FTPAuthentication(getSite()); while (!cl.login(auth.getUser(), auth.getPassword())) { ap.setSite(getSite()); auth = ap.promptAuthentication(); if (auth == null) throw new Exception("User Cancelled Auth Operation"); } cl.connect(getHostName()); cl.login(auth.getUser(), auth.getPassword()); cl.enterLocalPassiveMode(); cl.setFileType(FTP.BINARY_FILE_TYPE); cl.setRestartOffset(getPosition()); setInputStream(cl.retrieveFileStream(new URL(getURL()).getFile())); } Code Sample 2: public static String md5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
11
Code Sample 1: private void externalizeFiles(Document doc, File out) throws IOException { File[] files = doc.getImages(); if (files.length > 0) { File dir = new File(out.getParentFile(), out.getName() + ".images"); if (!dir.mkdirs()) throw new IOException("cannot create directory " + dir); if (dir.exists()) { for (int i = 0; i < files.length; i++) { File file = files[i]; File copy = new File(dir, file.getName()); FileChannel from = null, to = null; long count = -1; try { from = new FileInputStream(file).getChannel(); count = from.size(); to = new FileOutputStream(copy).getChannel(); from.transferTo(0, count, to); doc.setImage(file, dir.getName() + "/" + copy.getName()); } catch (Throwable t) { LOG.log(Level.WARNING, "Copying '" + file + "' to '" + copy + "' failed (size=" + count + ")", t); } finally { try { to.close(); } catch (Throwable t) { } try { from.close(); } catch (Throwable t) { } } } } } } Code Sample 2: private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
00
Code Sample 1: private boolean importTablesData(Connection conn) { try { boolean status = true; boolean autoCommit = conn.getAutoCommit(); conn.setAutoCommit(false); String dbType = this.getFromSession("database"); List statements = ParseDBDumpFile.parse(SystemGlobals.getValue(ConfigKeys.CONFIG_DIR) + "/database/" + dbType + "/" + dbType + "_data_dump.sql"); for (Iterator iter = statements.iterator(); iter.hasNext(); ) { String query = (String) iter.next(); if (query == null || "".equals(query.trim())) { continue; } query = query.trim(); Statement s = conn.createStatement(); try { if (query.startsWith("UPDATE") || query.startsWith("INSERT") || query.startsWith("SET")) { s.executeUpdate(query); } else if (query.startsWith("SELECT")) { s.executeQuery(query); } else { throw new SQLException("Invalid query: " + query); } } catch (SQLException ex) { status = false; conn.rollback(); logger.error("Error importing data for " + query + ": " + ex, ex); this.context.put("exceptionMessage", ex.getMessage() + "\n" + query); break; } finally { s.close(); } } conn.setAutoCommit(autoCommit); return status; } catch (Exception e) { throw new ForumException(e); } } Code Sample 2: public static DBData resolveDBasURL(java.net.URL url) throws Exception { DBData data = null; InputStream fi = null; EnhancedStreamTokenizer tokenizer = null; try { fi = url.openStream(); tokenizer = new EnhancedStreamTokenizer(new BufferedReader(new InputStreamReader(fi))); initializeTokenizer(tokenizer); } catch (Exception e) { Console.getInstance().println("\nError occured while opening URL '" + url.toString() + "'"); Console.getInstance().println(e); return null; } if (tokenizer != null) { try { } finally { System.gc(); } } return data; }
00
Code Sample 1: protected static void copyDeleting(File source, File dest) throws ErrorCodeException { byte[] buf = new byte[8 * 1024]; FileInputStream in = null; try { in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { int count; while ((count = in.read(buf)) >= 0) out.write(buf, 0, count); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new ErrorCodeException(e); } } Code Sample 2: public static String getFurigana(String sentence) throws Exception { Log.d("--VOA--", "getFurigana START"); sbFurigana = new StringBuffer(); String urlStr = getYahooApiURL(); urlStr = addSentence(urlStr, sentence); URL url = new URL(urlStr); URLConnection uc = url.openConnection(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Log.d("--VOA--", uc.getURL().toString()); InputStream is = uc.getInputStream(); doc = db.parse(is); walkThrough(); Log.d("--VOA--", "getFurigana END"); return sbFurigana.toString(); }
11
Code Sample 1: public static void main(String[] argv) throws IOException { int i; for (i = 0; i < argv.length; i++) { if (argv[i].charAt(0) != '-') break; ++i; switch(argv[i - 1].charAt(1)) { case 'b': try { flag_predict_probability = (atoi(argv[i]) != 0); } catch (NumberFormatException e) { exit_with_help(); } break; default: System.err.printf("unknown option: -%d%n", argv[i - 1].charAt(1)); exit_with_help(); break; } } if (i >= argv.length || argv.length <= i + 2) { exit_with_help(); } BufferedReader reader = null; Writer writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(argv[i]), Linear.FILE_CHARSET)); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(argv[i + 2]), Linear.FILE_CHARSET)); Model model = Linear.loadModel(new File(argv[i + 1])); doPredict(reader, writer, model); } finally { closeQuietly(reader); closeQuietly(writer); } } Code Sample 2: public static void copyFile(File source, String target) throws FileNotFoundException, IOException { File fout = new File(target); fout.mkdirs(); fout.delete(); fout = new File(target); FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); }
00
Code Sample 1: public static InputStream call(String serviceUrl, Map parameters) throws IOException, RestException { StringBuffer urlString = new StringBuffer(serviceUrl); String query = RestClient.buildQueryString(parameters); HttpURLConnection conn; if ((urlString.length() + query.length() + 1) > MAX_URI_LENGTH_FOR_GET) { URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.getOutputStream().write(query.getBytes()); } else { if (query.length() > 0) { urlString.append("?").append(query); } URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("GET"); } int responseCode = conn.getResponseCode(); if (HttpURLConnection.HTTP_OK != responseCode) { ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream(); int read; byte[] readBuffer = new byte[ERROR_READ_BUFFER_SIZE]; InputStream errorStream = conn.getErrorStream(); while (-1 != (read = errorStream.read(readBuffer))) { errorBuffer.write(readBuffer, 0, read); } throw new RestException("Request failed, HTTP " + responseCode + ": " + conn.getResponseMessage(), errorBuffer.toByteArray()); } return conn.getInputStream(); } Code Sample 2: private void copyFileNFS(String sSource, String sTarget) throws Exception { FileInputStream fis = new FileInputStream(sSource); FileOutputStream fos = new FileOutputStream(sTarget); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buf = new byte[2048]; int i = 0; while ((i = bis.read(buf)) != -1) bos.write(buf, 0, i); bis.close(); bos.close(); fis.close(); fos.close(); }
11
Code Sample 1: private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public static File createTempFile(InputStream contentStream, String ext) throws IOException { ExceptionUtils.throwIfNull(contentStream, "contentStream"); File file = File.createTempFile("test", ext); FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copy(contentStream, fos, false); } finally { fos.close(); } return file; }
00
Code Sample 1: @Override public URLConnection openConnection(URL url, Proxy proxy) throws IOException { if (null == url) { throw new IllegalArgumentException(Messages.getString("luni.1B")); } String host = url.getHost(); if (host == null || host.length() == 0 || host.equalsIgnoreCase("localhost")) { return new FileURLConnection(url); } URL ftpURL = new URL("ftp", host, url.getFile()); return (proxy == null) ? ftpURL.openConnection() : ftpURL.openConnection(proxy); } Code Sample 2: public static void copy(FileInputStream in, File destination) throws IOException { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = in.getChannel(); dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (dstChannel != null) { dstChannel.close(); } } }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: static JSONObject executeMethod(HttpClient httpClient, HttpMethod method, int timeout) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; JSONObject result = null; for (int i = 0; i < RETRY; i++) { System.out.println("Execute method[" + method.getURI() + "](try " + (i + 1) + ")"); status = httpClient.executeMethod(method); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); result = JSONObject.fromString(response); if (result.has("status")) { String lingrStatus = result.getString("status"); if ("ok".equals(lingrStatus)) { break; } else { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } else { throw new HttpRequestFailureException(status); } } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } } Code Sample 2: private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } }
11
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public static void main(String argv[]) { try { if (argv.length != 1 && argv.length != 3) { usage(); System.exit(1); } URL url = new URL(argv[0]); URLConnection conn; conn = url.openConnection(); if (conn.getHeaderField("WWW-Authenticate") != null) { auth(conn, argv[1], argv[2]); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) System.out.println(line); } } catch (Exception ex) { ex.printStackTrace(); } }
00
Code Sample 1: private static void salvarObra(Artista artista, Obra obra) throws Exception { Connection conn = null; PreparedStatement ps = null; int categoria; System.out.println("Migracao.salvarObra() obra: " + obra.toString2()); if (obra.getCategoria() != null) { categoria = getCategoria(obra.getCategoria().getNome()).getCodigo(); } else { categoria = getCategoria("Sem Categoria").getCodigo(); } try { conn = C3P0Pool.getConnection(); String sql = "insert into obra VALUES (?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setNull(1, Types.INTEGER); ps.setString(2, obra.getTitulo()); ps.setInt(3, obra.getSelec()); ps.setInt(4, categoria); ps.setInt(5, artista.getNumeroInscricao()); ps.setInt(6, obra.getCodigo()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } Code Sample 2: public static Reader createReader(TreeLogger logger, URL url) throws UnableToCompleteException { try { return new InputStreamReader(url.openStream()); } catch (IOException e) { logger.log(TreeLogger.ERROR, "Unable to open resource: " + url, e); throw new UnableToCompleteException(); } }
11
Code Sample 1: public static void fileCopy(String src, String dst) { try { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst); int read = -1; byte[] buf = new byte[8192]; while ((read = fis.read(buf)) != -1) { fos.write(buf, 0, read); } fos.flush(); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void copyFileByNIO(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static Boolean decompress(File source, File destination) { FileOutputStream outputStream; ZipInputStream inputStream; try { outputStream = null; inputStream = new ZipInputStream(new FileInputStream(source)); int read; byte buffer[] = new byte[BUFFER_SIZE]; ZipEntry zipEntry; while ((zipEntry = inputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) new File(destination, zipEntry.getName()).mkdirs(); else { File fileEntry = new File(destination, zipEntry.getName()); fileEntry.getParentFile().mkdirs(); outputStream = new FileOutputStream(fileEntry); while ((read = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) { outputStream.write(buffer, 0, read); } outputStream.flush(); outputStream.close(); } } inputStream.close(); } catch (Exception oException) { return false; } return true; } Code Sample 2: public void createZip(String baseDir, String objFileName) throws Exception { logger.info("createZip: [ " + baseDir + "] [" + objFileName + "]"); baseDir = baseDir + "/" + timesmpt; File folderObject = new File(baseDir); if (folderObject.exists()) { List<?> fileList = getSubFiles(new File(baseDir)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFileName)); ZipEntry ze = null; byte[] buf = new byte[1024]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File f = (File) fileList.get(i); ze = new ZipEntry(getAbsFileName(baseDir, f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); while ((readLen = is.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } is.close(); } zos.close(); } else { throw new Exception("this folder isnot exist!"); } }
00
Code Sample 1: private void initClientConfigurationFromURL(String urlStr) throws Exception { try { URL url = ProxyURLFactory.createHttpUrl(urlStr); initClientConfiguration(url.openStream()); } catch (Exception e) { throw new Exception("Could not initialize from Client Configuration URL:" + urlStr, e); } } Code Sample 2: public static InputStream openStream(URL url) { try { URLConnection connection = url.openConnection(); connection.setUseCaches(false); return connection.getInputStream(); } catch (IOException e) { throw new IORuntimeException(e); } }
00
Code Sample 1: void copyTo(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { if (shouldMock()) { return; } assert httpRequest != null; assert httpResponse != null; final long start = System.currentTimeMillis(); try { final URLConnection connection = openConnection(url, headers); connection.setRequestProperty("Accept-Language", httpRequest.getHeader("Accept-Language")); connection.connect(); try { InputStream input = connection.getInputStream(); if ("gzip".equals(connection.getContentEncoding())) { input = new GZIPInputStream(input); } httpResponse.setContentType(connection.getContentType()); TransportFormat.pump(input, httpResponse.getOutputStream()); } finally { close(connection); } } finally { LOGGER.info("http call done in " + (System.currentTimeMillis() - start) + " ms for " + url); } } Code Sample 2: public void deleteDomain(final List<Integer> domainIds) { try { connection.setAutoCommit(false); final int defaultDomainId = ((DomainDb) cmDB.getDefaultDomain()).getDomainId(); boolean defaultDomainDeleted = (Boolean) new ProcessEnvelope().executeObject(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public Object executeProcessReturnObject() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("domain.delete")); Iterator<Integer> iter = domainIds.iterator(); int domainId; boolean defaultDomainDeleted = false; while (iter.hasNext()) { domainId = iter.next(); if (!defaultDomainDeleted) defaultDomainDeleted = defaultDomainId == domainId; psImpl.setInt(1, domainId); psImpl.executeUpdate(); } return defaultDomainDeleted; } }); if (defaultDomainDeleted) { new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("domain.setDefaultDomainId")); psImpl.setInt(1, -1); psImpl.executeUpdate(); } }); } connection.commit(); cmDB.updateDomains(null, null); if (defaultDomainDeleted) { cm.updateDefaultDomain(); } } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
11
Code Sample 1: public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); } Code Sample 2: private List<Document> storeDocuments(List<Document> documents) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); List<Document> newDocuments = new ArrayList<Document>(); try { session.beginTransaction(); Preference preference = new PreferenceModel(); preference = (Preference) preference.doList(preference).get(0); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); if (documents != null && !documents.isEmpty()) { for (Iterator<Document> iter = documents.iterator(); iter.hasNext(); ) { Document document = iter.next(); if (AppConstants.STATUS_ACTIVE.equals(document.getStatus())) { try { document = (Document) preAdd(document, getParams()); File fileIn = new File(preference.getScanLocation() + File.separator + document.getName()); File fileOut = new File(preference.getStoreLocation() + File.separator + document.getName()); FileInputStream in = new FileInputStream(fileIn); FileOutputStream out = new FileOutputStream(fileOut); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); document.doAdd(document); boolean isDeleted = fileIn.delete(); System.out.println("Deleted scan folder file: " + document.getName() + ":" + isDeleted); if (isDeleted) { document.setStatus(AppConstants.STATUS_PROCESSING); int uploadCount = 0; if (document.getUploadCount() != null) { uploadCount = document.getUploadCount(); } uploadCount++; document.setUploadCount(uploadCount); newDocuments.add(document); } } catch (Exception add_ex) { add_ex.printStackTrace(); } } else if (AppConstants.STATUS_PROCESSING.equals(document.getStatus())) { int uploadCount = document.getUploadCount(); if (uploadCount < 5) { uploadCount++; document.setUploadCount(uploadCount); System.out.println("increase upload count: " + document.getName() + ":" + uploadCount); newDocuments.add(document); } else { System.out.println("delete from documents list: " + document.getName()); } } else if (AppConstants.STATUS_INACTIVE.equals(document.getStatus())) { document.setFixFlag(AppConstants.FLAG_NO); newDocuments.add(document); } } } } catch (Exception ex) { ex.printStackTrace(); } return newDocuments; }
11
Code Sample 1: public void gzip(File from, File to) { OutputStream out_zip = null; ArchiveOutputStream os = null; try { try { out_zip = new FileOutputStream(to); os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out_zip); os.putArchiveEntry(new ZipArchiveEntry(from.getName())); IOUtils.copy(new FileInputStream(from), os); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } } out_zip.close(); } catch (IOException ex) { fatal("IOException", ex); } catch (ArchiveException ex) { fatal("ArchiveException", ex); } } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
11
Code Sample 1: private void copy(File source, File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { close(in); close(out); } } Code Sample 2: @BeforeClass public static void setUpOnce() throws OWLOntologyCreationException { dbManager = (OWLDBOntologyManager) OWLDBManager.createOWLOntologyManager(OWLDataFactoryImpl.getInstance()); dbIRI = IRI.create(ontoUri); System.out.println("copying ontology to work folder..."); try { final File directory = new File("./resources/LUBM10-DB-forUpdate/"); final File[] filesToDelete = directory.listFiles(); if (filesToDelete != null && filesToDelete.length > 0) { for (final File file : filesToDelete) { if (!file.getName().endsWith(".svn")) Assert.assertTrue(file.delete()); } } final File original = new File("./resources/LUBM10-DB/LUBM10.h2.db"); final File copy = new File("./resources/LUBM10-DB-forUpdate/LUBM10.h2.db"); final FileChannel inChannel = new FileInputStream(original).getChannel(); final FileChannel outChannel = new FileOutputStream(copy).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException ioe) { System.err.println(ioe.getMessage()); Assert.fail(); } onto = (OWLMutableOntology) dbManager.loadOntology(dbIRI); factory = dbManager.getOWLDataFactory(); }
11
Code Sample 1: static void createCompleteXML(File file) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(errorFile); fos = new FileOutputStream(file); byte[] data = new byte[Integer.parseInt(BlueXStatics.prop.getProperty("allocationUnit"))]; int offset; while ((offset = fis.read(data)) != -1) fos.write(data, 0, offset); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } FileWriter fw = null; try { fw = new FileWriter(file, true); fw.append("</detail>"); fw.append("\n</exception>"); fw.append("\n</log>"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); } catch (Exception e) { } } } Code Sample 2: public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
00
Code Sample 1: private Document post(String location, String content) throws ApplicationException { Document doc = null; try { URL url = new URL(location); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setRequestMethod("POST"); uc.setRequestProperty("Content-Type", "application/xml"); uc.setRequestProperty("X-POST_DATA_FORMAT", "xml"); uc.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream()); out.write("<request>"); out.write("<token>" + configuration.getBackpackPassword() + "</token>"); if (content != null) { out.write("<item><content>" + content + "</content></item>"); } out.write("</request>"); out.close(); doc = XmlUtils.readDocumentFromInputStream(uc.getInputStream()); System.out.println(XmlUtils.toString(doc)); } catch (IOException e) { e.printStackTrace(); throw new ApplicationException(e); } return doc; } Code Sample 2: public static String encodeString(String encodeType, String str) { if (encodeType.equals("md5of16")) { MD5 m = new MD5(); return m.getMD5ofStr16(str); } else if (encodeType.equals("md5of32")) { MD5 m = new MD5(); return m.getMD5ofStr(str); } else { try { MessageDigest gv = MessageDigest.getInstance(encodeType); gv.update(str.getBytes()); return new BASE64Encoder().encode(gv.digest()); } catch (java.security.NoSuchAlgorithmException e) { logger.error("BASE64加密失败", e); return null; } } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public void run() { if (saveAsDialog == null) { saveAsDialog = new FileDialog(window.getShell(), SWT.SAVE); saveAsDialog.setFilterExtensions(saveAsTypes); } String outputFile = saveAsDialog.open(); if (outputFile != null) { Object inputFile = DataSourceSingleton.getInstance().getContainer().getWrapped(); InputStream in; try { if (inputFile instanceof URL) in = ((URL) inputFile).openStream(); else in = new FileInputStream((File) inputFile); OutputStream out = new FileOutputStream(outputFile); if (outputFile.endsWith("xml")) { int c; while ((c = in.read()) != -1) out.write(c); } else { PrintWriter pw = new PrintWriter(out); Element data = DataSourceSingleton.getInstance().getRawData(); writeTextFile(data, pw, -1); pw.close(); } in.close(); out.close(); } catch (MalformedURLException e1) { } catch (IOException e) { } } }
00
Code Sample 1: private boolean request(URI uri, Controller controller, String login, String password) { SSLHttpClient client = new SSLHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(login, password)); HttpGet get = new HttpGet(uri); get.addHeader("Accept", "application/xml"); try { HttpResponse response = client.execute(get); int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { final InputStream is = response.getEntity().getContent(); final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); final XmlPullParser parser = factory.newPullParser(); parser.setInput(is, null); while (parser.next() != XmlPullParser.END_DOCUMENT && !controller.stopped()) { if (parser.getEventType() == XmlPullParser.START_TAG) { String name = parser.getName(); if (mEntity.equals(name)) { String id = parser.getAttributeValue(null, "id"); if (id != null) { Item item = new Item(id, parser.nextText()); controller.receiveItem(item); } } } } } } catch (Exception e) { controller.error(); return false; } return true; } Code Sample 2: public void unlock(String oid, String key) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = NULL, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setLong(1, System.currentTimeMillis()); ps.setString(2, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to unlock object: OID = " + oid + ", KEY = " + key, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
00
Code Sample 1: public DatabaseDefinitionFactory(final DBIf db, final String adapter) throws IOException { _db = db; LOG.debug("Loading adapter: " + adapter); final URL url = getClass().getClassLoader().getResource("adapter/" + adapter + ".properties"); _props = new Properties(); _props.load(url.openStream()); if (adapter.equals("mysql")) { _modifier = new MySQLModifier(this); } else if (adapter.equals("postgresql")) { _modifier = new PostgresModifier(this); } else if (adapter.equals("hypersonic")) { _modifier = new HSQLModifier(this); } else if (adapter.equals("oracle")) { _modifier = new OracleModifier(this); } else if (adapter.equals("mssql")) { _modifier = new MSSQLModifier(this); } else { _modifier = null; } } Code Sample 2: public static void extract(final File destDir, final ZipInfo zipInfo, final IProgressMonitor monitor) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (String key : zipInfo.getEntryKeys()) { ZipEntry entry = zipInfo.getEntry(key); InputStream in = zipInfo.getInputStream(entry); File entryDest = new File(destDir, entry.getName()); entryDest.getParentFile().mkdirs(); if (!entry.isDirectory()) { OutputStream out = new FileOutputStream(new File(destDir, entry.getName())); try { IOUtils.copy(in, out); out.flush(); if (monitor != null) monitor.worked(1); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } if (monitor != null) monitor.done(); }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public Constructor run() throws Exception { String path = "META-INF/services/" + ComponentApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = ComponentApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (ComponentApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new ComponentApplicationException("No " + "ComponentApplicationContext implementation " + "found."); }
11
Code Sample 1: public static void zip(File srcDir, File destFile, FileFilter filter) throws IOException { ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(destFile)); Collection<File> files = FileUtils.listFiles(srcDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE); for (File f : files) { if (filter == null || filter.accept(f)) { FileInputStream in = FileUtils.openInputStream(f); out.putNextEntry(new ZipEntry(Util.relativePath(srcDir, f).replace('\\', '/'))); IOUtils.copyLarge(in, out); out.closeEntry(); IOUtils.closeQuietly(in); } } IOUtils.closeQuietly(out); } catch (Throwable t) { throw new IOException("Failed to create zip file", t); } finally { if (out != null) { out.flush(); IOUtils.closeQuietly(out); } } } Code Sample 2: public static final void zip(final ZipOutputStream out, final File f, String base) throws Exception { if (f.isDirectory()) { final File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (final File element : fl) { zip(out, element, base + element.getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); final FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); }
00
Code Sample 1: public void testSendMessage() throws ClientProtocolException, IOException { String textMessage = "La%20sua%20prenotazione%20e60%20andata%20a%20buon%20fine"; String customerPhoneNumber = "+393345730726"; DefaultHttpClient httpclient = new DefaultHttpClient(); String other = "http://smswizard.globalitalia.it/smsgateway/send.asp"; String urlProva = other + "?" + "Account=sardricerche" + "&Password=v8LomdZT" + "&PhoneNumbers=+393345730726" + "&SMSData=" + textMessage + "&Recipients=1" + "&Sender=+393337589951" + "&ID=11762"; HttpPost httpPost = new HttpPost(urlProva); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); String txt = EntityUtils.toString(entity); } Code Sample 2: private List<Intrebare> citesteIntrebari() throws IOException { ArrayList<Intrebare> intrebari = new ArrayList<Intrebare>(); try { URL url = new URL(getCodeBase(), "../intrebari.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader((url.openStream()))); String intrebare; while ((intrebare = reader.readLine()) != null) { Collection<String> raspunsuri = new ArrayList<String>(); Collection<String> predicate = new ArrayList<String>(); String raspuns = ""; while (!"".equals(raspuns = reader.readLine())) { raspunsuri.add(raspuns); predicate.add(reader.readLine()); } Intrebare i = new Intrebare(intrebare, raspunsuri.toArray(new String[raspunsuri.size()]), predicate.toArray(new String[predicate.size()])); intrebari.add(i); } } catch (ArgumentExcetpion e) { e.printStackTrace(); } return intrebari; }
00
Code Sample 1: public static byte[] excutePostRaw(String targetURL, byte[] postdata) { URL url; HttpURLConnection connection = null; try { url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(postdata.length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(postdata); wr.flush(); wr.close(); int amt = connection.getContentLength(); InputStream in = connection.getInputStream(); MojasiWriter writer = new MojasiWriter(); byte[] buff = new byte[256]; while (writer.size() < amt) { int got = in.read(buff); if (got < 0) break; writer.pushBytes(buff, got); if (writer.size() > 1) System.out.println(); } in.close(); connection.disconnect(); return writer.getBytes(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } } } Code Sample 2: public static void copyFile(String inName, String otName) throws Exception { File inFile = null; File otFile = null; try { inFile = new File(inName); otFile = new File(otName); } catch (Exception e) { e.printStackTrace(); } if (inFile == null || otFile == null) return; FileChannel sourceChannel = new FileInputStream(inFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(otFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: public static void proxyRequest(IPageContext context, Writer writer, String proxyPath) throws IOException { URLConnection connection = new URL(proxyPath).openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "text/html; charset=UTF-8"); connection.setReadTimeout(30000); connection.setConnectTimeout(5000); Enumeration<String> e = context.httpRequest().getHeaderNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (name.equalsIgnoreCase("HOST") || name.equalsIgnoreCase("Accept-Encoding") || name.equalsIgnoreCase("Authorization")) continue; Enumeration<String> headers = context.httpRequest().getHeaders(name); while (headers.hasMoreElements()) { String header = headers.nextElement(); connection.setRequestProperty(name, header); } } if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod(context.httpRequest().getMethod()); if ("POST".equalsIgnoreCase(context.httpRequest().getMethod()) || "PUT".equalsIgnoreCase(context.httpRequest().getMethod())) { Enumeration<String> names = context.httpRequest().getParameterNames(); StringBuilder body = new StringBuilder(); while (names.hasMoreElements()) { String key = names.nextElement(); for (String value : context.parameters(key)) { if (body.length() > 0) { body.append('&'); } try { body.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")); } catch (UnsupportedEncodingException ex) { } } } if (body.length() > 0) { connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(body.toString()); out.close(); } } } try { IOUtils.copy(connection.getInputStream(), writer); } catch (IOException ex) { writer.write("<span>SSI Error: " + ex.getMessage() + "</span>"); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public void overwriteFileTest() throws Exception { File filefrom = new File("/tmp/from.txt"); File fileto = new File("/tmp/to.txt"); InputStream from = null; OutputStream to = null; try { from = new FileInputStream(filefrom); to = new FileOutputStream(fileto); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { from.close(); } if (to != null) { to.close(); } } } Code Sample 2: public MemoryBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
00
Code Sample 1: public static String getSHA1(String s) { try { MessageDigest sha1 = MessageDigest.getInstance("SHA1"); sha1.update(s.toLowerCase().getBytes()); return HexString.bufferToHex(sha1.digest()); } catch (NoSuchAlgorithmException e) { System.err.println("Error grave al inicializar SHA1"); e.printStackTrace(); return "!!"; } } Code Sample 2: protected static void clearTables() throws SQLException { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); ClearData.clearTables(stmt); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (2, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (3, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (4, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (5, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (6, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (7, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (8, '')"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public String getpage(String leurl) throws Exception { int data; StringBuffer lapage = new StringBuffer(); URL myurl = new URL(leurl); URLConnection conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return lapage.toString(); } InputStream in = conn.getInputStream(); for (data = in.read(); data != -1; data = in.read()) lapage.append((char) data); return lapage.toString(); }
11
Code Sample 1: public static void copy(String sourceName, String destName) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath()); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } } Code Sample 2: public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); }
11
Code Sample 1: private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } Code Sample 2: private void encryptChkFile(ProjectMember member, File chkFile) throws Exception { final java.io.FileReader reader = new java.io.FileReader(chkFile); final File encryptedChkFile = new File(member.createOutputFileName(outputPath, "chk")); FileOutputStream outfile = null; ObjectOutputStream outstream = null; Utilities.discardBooleanResult(encryptedChkFile.getParentFile().mkdirs()); outfile = new FileOutputStream(encryptedChkFile); outstream = new ObjectOutputStream(outfile); outstream.writeObject(new Format().parse(reader)); reader.close(); outfile.close(); outstream.close(); }
11
Code Sample 1: private void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
11
Code Sample 1: public static void copyFile(File src, File dest) throws IOException { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dest); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } Code Sample 2: private void copyMerge(Path[] sources, OutputStream out) throws IOException { Configuration conf = getConf(); for (int i = 0; i < sources.length; ++i) { FileSystem fs = sources[i].getFileSystem(conf); InputStream in = fs.open(sources[i]); try { IOUtils.copyBytes(in, out, conf, false); } finally { in.close(); } } }
00
Code Sample 1: @Override public void run() { try { if (!Util.isSufficienDataForUpload(recordedGeoPoints)) return; final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes()); final HttpClient httpClient = new DefaultHttpClient(); final HttpPost request = new HttpPost(UPLOADSCRIPT_URL); final MultipartEntity requestEntity = new MultipartEntity(); requestEntity.addPart("gpxfile", new InputStreamBody(gpxInputStream, "" + System.currentTimeMillis() + ".gpx")); httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false); request.setEntity(requestEntity); final HttpResponse response = httpClient.execute(request); final int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { logger.error("GPXUploader", "status != HttpStatus.SC_OK"); } else { final Reader r = new InputStreamReader(new BufferedInputStream(response.getEntity().getContent())); final char[] buf = new char[8 * 1024]; int read; final StringBuilder sb = new StringBuilder(); while ((read = r.read(buf)) != -1) sb.append(buf, 0, read); logger.debug("GPXUploader", "Response: " + sb.toString()); } } catch (final Exception e) { } } Code Sample 2: public static void download(URL url, File file, String userAgent) throws IOException { URLConnection conn = url.openConnection(); if (userAgent != null) { conn.setRequestProperty("User-Agent", userAgent); } InputStream in = conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); StreamUtil.copyThenClose(in, out); }
11
Code Sample 1: public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void copyFile(File sourceFile, File targetFile) throws IOException { if (sourceFile == null || targetFile == null) { throw new NullPointerException("Source file and target file must not be null"); } File directory = targetFile.getParentFile(); if (!directory.exists() && !directory.mkdirs()) { throw new IOException("Could not create directory '" + directory + "'"); } InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); try { byte[] buffer = new byte[32768]; for (int readBytes = inputStream.read(buffer); readBytes > 0; readBytes = inputStream.read(buffer)) { outputStream.write(buffer, 0, readBytes); } } catch (IOException ex) { targetFile.delete(); throw ex; } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } }
11
Code Sample 1: private Image retrievePdsImage(double lat, double lon) { imageDone = false; try { StringBuffer urlBuff = new StringBuffer(psdUrl + psdCgi + "?"); urlBuff.append("DATA_SET_NAME=" + dataSet); urlBuff.append("&VERSION=" + version); urlBuff.append("&PIXEL_TYPE=" + pixelType); urlBuff.append("&PROJECTION=" + projection); urlBuff.append("&STRETCH=" + stretch); urlBuff.append("&GRIDLINE_FREQUENCY=" + gridlineFrequency); urlBuff.append("&SCALE=" + URLEncoder.encode(scale)); urlBuff.append("&RESOLUTION=" + resolution); urlBuff.append("&LATBOX=" + latbox); urlBuff.append("&LONBOX=" + lonbox); urlBuff.append("&BANDS_SELECTED=" + bandsSelected); urlBuff.append("&LAT=" + lat); urlBuff.append("&LON=" + lon); URL url = new URL(urlBuff.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String result = null; String line; String imageSrc; int count = 0; while ((line = in.readLine()) != null) { if (count == 6) result = line; count++; } int startIndex = result.indexOf("<TH COLSPAN=2 ROWSPAN=2><IMG SRC = \"") + 36; int endIndex = result.indexOf("\"", startIndex); imageSrc = result.substring(startIndex, endIndex); URL imageUrl = new URL(imageSrc); return (Toolkit.getDefaultToolkit().getImage(imageUrl)); } catch (MalformedURLException e) { } catch (IOException e) { } return null; } Code Sample 2: public static String get(String strUrl) { if (NoMuleRuntime.DEBUG) System.out.println("GET : " + strUrl); try { URL url = new URL(strUrl); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += s; } NoMuleRuntime.showDebug("ANSWER: " + sRet); return sRet; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; }
00
Code Sample 1: public static void assertEquals(String xmlpath, Object actualObject) throws Exception { InputStreamReader isr; try { isr = new FileReader(xmlpath); } catch (FileNotFoundException e) { URL url = AssertHelper.class.getClassLoader().getResource(xmlpath); if (null != url) { try { isr = new InputStreamReader(url.openStream()); } catch (Exception e1) { throw new AssertionFailedError("Unable to find output xml : " + xmlpath); } } else { throw new AssertionFailedError("Could not read output xml : " + xmlpath); } } DOMParser parser = new DOMParser(); parser.parse(new InputSource(isr)); Document document = parser.getDocument(); try { assertEqual(document.getDocumentElement(), actualObject); } catch (AssertionFailedError e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } AssertionFailedError a = new AssertionFailedError(sbf.toString()); a.setStackTrace(e.getStackTrace()); throw a; } catch (Exception e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } Exception ex = new Exception(sbf.toString()); ex.setStackTrace(e.getStackTrace()); throw ex; } } Code Sample 2: public static boolean isMatchingAsPassword(final String password, final String amd5Password) { boolean response = false; try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); final byte[] md5Byte = algorithm.digest(); final StringBuffer buffer = new StringBuffer(); for (final byte b : md5Byte) { if ((b <= 15) && (b >= 0)) { buffer.append("0"); } buffer.append(Integer.toHexString(0xFF & b)); } response = (amd5Password != null) && amd5Password.equals(buffer.toString()); } catch (final NoSuchAlgorithmException e) { ProjektUtil.LOG.error("No digester MD5 found in classpath!", e); } return response; }
11
Code Sample 1: @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType(req.getContentType()); IOUtils.copy(req.getReader(), resp.getWriter()); } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: protected URLConnection openConnection(URL url) throws IOException { if (bundleEntry != null) return (new BundleURLConnection(url, bundleEntry)); String bidString = url.getHost(); if (bidString == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_ID, url.toExternalForm())); } AbstractBundle bundle = null; long bundleID; try { bundleID = Long.parseLong(bidString); } catch (NumberFormatException nfe) { throw new MalformedURLException(NLS.bind(AdaptorMsg.URL_INVALID_BUNDLE_ID, bidString)); } bundle = (AbstractBundle) context.getBundle(bundleID); if (!url.getAuthority().equals(SECURITY_AUTHORIZED)) { checkAdminPermission(bundle); } if (bundle == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_FOUND, url.toExternalForm())); } return (new BundleURLConnection(url, findBundleEntry(url, bundle))); }
00
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: private long getNextHighValue() throws Exception { Connection con = null; PreparedStatement psGetHighValue = null; PreparedStatement psUpdateHighValue = null; ResultSet rs = null; long high = -1L; int isolation = -1; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { con = dbo.getConnection(); psGetHighValue = con.prepareStatement(strGetHighValue); psGetHighValue.setString(1, this.name); for (rs = psGetHighValue.executeQuery(); rs.next(); ) { high = rs.getLong("high"); } psUpdateHighValue = con.prepareStatement(strUpdateHighValue); psUpdateHighValue.setLong(1, high + 1L); psUpdateHighValue.setString(2, this.name); psUpdateHighValue.executeUpdate(); } catch (SQLException e) { if (con != null) { con.rollback(); } throw e; } finally { if (psUpdateHighValue != null) { psUpdateHighValue.close(); } close(dbo, psGetHighValue, rs); } return high; }
11
Code Sample 1: public String upload() throws IOException { int idx = docIndex.incrementAndGet(); String tmpName = "namefinder/doc_" + idx + "__" + fileFileName; File tmpFile = tmpFile(tmpName); if (tmpFile.exists()) { org.apache.commons.io.FileUtils.deleteQuietly(tmpFile); } org.apache.commons.io.FileUtils.touch(tmpFile); InputStream fileStream = new FileInputStream(file); OutputStream bos = new FileOutputStream(tmpFile); IOUtils.copy(fileStream, bos); bos.close(); fileStream.close(); return tmpUrl(tmpName); } Code Sample 2: public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
11
Code Sample 1: private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: @Test public void testWriteAndRead() throws Exception { JCFS.configureLoopback(dir); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); }
11
Code Sample 1: public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; } Code Sample 2: public static Debugger getDebugger(InetAddress host, int port, String password) throws IOException { try { Socket s = new Socket(host, port); try { ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream()); ObjectInputStream in = new ObjectInputStream(s.getInputStream()); int protocolVersion = in.readInt(); if (protocolVersion > 220) { throw new IOException("Incompatible protocol version " + protocolVersion + ". At most 220 was expected."); } byte[] challenge = (byte[]) in.readObject(); MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); md.update(challenge); out.writeObject(md.digest()); return new LocalDebuggerProxy((Debugger) in.readObject()); } finally { s.close(); } } catch (IOException e) { throw e; } catch (Exception e) { throw new UndeclaredThrowableException(e); } }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { log.debug("Copy from {} to {}", source.getAbsoluteFile(), dest.getAbsoluteFile()); FileInputStream fi = new FileInputStream(source); FileChannel fic = fi.getChannel(); MappedByteBuffer mbuf = fic.map(FileChannel.MapMode.READ_ONLY, 0, source.length()); fic.close(); fi.close(); fi = null; if (!dest.exists()) { String destPath = dest.getPath(); log.debug("Destination path: {}", destPath); String destDir = destPath.substring(0, destPath.lastIndexOf(File.separatorChar)); log.debug("Destination dir: {}", destDir); File dir = new File(destDir); if (!dir.exists()) { if (dir.mkdirs()) { log.debug("Directory created"); } else { log.warn("Directory not created"); } } dir = null; } FileOutputStream fo = new FileOutputStream(dest); FileChannel foc = fo.getChannel(); foc.write(mbuf); foc.close(); fo.close(); fo = null; mbuf.clear(); mbuf = null; } Code Sample 2: public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = dest.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: public FileOutputStream transfer(File from, File to, long mark) throws IOException, InterruptedException { if (out != null) { close(); } FileChannel fch = new FileInputStream(from).getChannel(); FileChannel rollch = new FileOutputStream(to).getChannel(); long size = mark; int count = 0; try { while ((count += rollch.transferFrom(fch, count, size - count)) < size) { } } finally { fch.close(); rollch.close(); } out = create(to); return out; } Code Sample 2: public static void main(String[] argv) { if (1 < argv.length) { File[] sources = Source(argv[0]); if (null != sources) { for (File src : sources) { File[] targets = Target(src, argv); if (null != targets) { final long srclen = src.length(); try { FileChannel source = new FileInputStream(src).getChannel(); try { for (File tgt : targets) { FileChannel target = new FileOutputStream(tgt).getChannel(); try { source.transferTo(0L, srclen, target); } finally { target.close(); } System.out.printf("Updated %s\n", tgt.getPath()); File[] deletes = Delete(src, tgt); if (null != deletes) { for (File del : deletes) { if (SVN) { if (SvnDelete(del)) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } else if (del.delete()) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } } if (SVN) SvnAdd(tgt); } } finally { source.close(); } } catch (Exception exc) { exc.printStackTrace(); System.exit(1); } } } System.exit(0); } else { System.err.printf("Source file(s) not found in '%s'\n", argv[0]); System.exit(1); } } else { usage(); System.exit(1); } }
00
Code Sample 1: protected void channelConnected() throws IOException { MessageDigest md = null; String digest = ""; try { String userid = nateon.getUserId(); if (userid.endsWith("@nate.com")) userid = userid.substring(0, userid.lastIndexOf('@')); md = MessageDigest.getInstance("MD5"); md.update(nateon.getPassword().getBytes()); md.update(userid.getBytes()); byte[] bData = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bData) { int v = (int) b; v = v < 0 ? v + 0x100 : v; String s = Integer.toHexString(v); if (s.length() == 1) sb.append('0'); sb.append(s); } digest = sb.toString(); } catch (Exception e) { e.printStackTrace(); } NateOnMessage out = new NateOnMessage("LSIN"); out.add(nateon.getUserId()).add(digest).add("MD5").add("3.615"); out.setCallback("processAuth"); writeMessage(out); } Code Sample 2: public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = null; ServletOutputStream outstream = null; try { String action = req.getParameter("nmrshiftdbaction"); String relativepath = ServletUtils.expandRelative(this.getServletConfig(), "/WEB-INF"); TurbineConfig tc = new TurbineConfig(relativepath + "..", relativepath + getServletConfig().getInitParameter("properties")); tc.init(); int spectrumId = -1; DBSpectrum spectrum = null; Export export = null; String format = req.getParameter("format"); if (action.equals("test")) { try { res.setContentType("text/plain"); out = res.getWriter(); List l = DBSpectrumPeer.executeQuery("select SPECTRUM_ID from SPECTRUM limit 1"); if (l.size() > 0) spectrumId = ((Record) l.get(0)).getValue(1).asInt(); out.write("success"); } catch (Exception ex) { out.write("failure"); } } else if (action.equals("rss")) { int numbertoexport = 10; out = res.getWriter(); if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } res.setContentType("text/xml"); RssWriter rssWriter = new RssWriter(); rssWriter.setWriter(res.getWriter()); AtomContainerSet soac = new AtomContainerSet(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" order by MOLECULE.DATE desc;"; List l = NmrshiftdbUserPeer.executeQuery(query); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); IMolecule cdkmol = mol.getAsCDKMoleculeAsEntered(1); soac.addAtomContainer(cdkmol); rssWriter.getLinkmap().put(cdkmol, mol.getEasylink(req)); rssWriter.getDatemap().put(cdkmol, mol.getDate()); rssWriter.getTitlemap().put(cdkmol, mol.getChemicalNamesAsOneStringWithFallback()); rssWriter.getCreatormap().put(cdkmol, mol.getNmrshiftdbUser().getUserName()); rssWriter.setCreator(GeneralUtils.getAdminEmail(getServletConfig())); Vector v = mol.getDBCanonicalNames(); for (int k = 0; k < v.size(); k++) { DBCanonicalName canonName = (DBCanonicalName) v.get(k); if (canonName.getDBCanonicalNameType().getCanonicalNameType() == "INChI") { rssWriter.getInchimap().put(cdkmol, canonName.getName()); break; } } rssWriter.setTitle("NMRShiftDB"); rssWriter.setLink("http://www.nmrshiftdb.org"); rssWriter.setDescription("NMRShiftDB is an open-source, open-access, open-submission, open-content web database for chemical structures and their nuclear magnetic resonance data"); rssWriter.setPublisher("NMRShiftDB.org"); rssWriter.setImagelink("http://www.nmrshiftdb.org/images/nmrshift-logo.gif"); rssWriter.setAbout("http://www.nmrshiftdb.org/NmrshiftdbServlet?nmrshiftdbaction=rss"); Collection coll = new ArrayList(); Vector spectra = mol.selectSpectra(null); for (int k = 0; k < spectra.size(); k++) { Element el = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Element el2 = el.getChildElements().get(0); el.removeChild(el2); coll.add(el2); } rssWriter.getMultiMap().put(cdkmol, coll); } rssWriter.write(soac); } else if (action.equals("getattachment")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); DBSample sample = DBSamplePeer.retrieveByPK(new NumberKey(req.getParameter("sampleid"))); outstream.write(sample.getAttachment()); } else if (action.equals("createreport")) { res.setContentType("application/pdf"); outstream = res.getOutputStream(); boolean yearly = req.getParameter("style").equals("yearly"); int yearstart = Integer.parseInt(req.getParameter("yearstart")); int yearend = Integer.parseInt(req.getParameter("yearend")); int monthstart = 0; int monthend = 0; if (!yearly) { monthstart = Integer.parseInt(req.getParameter("monthstart")); monthend = Integer.parseInt(req.getParameter("monthend")); } int type = Integer.parseInt(req.getParameter("type")); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(relativepath + "/reports/" + (yearly ? "yearly" : "monthly") + "_report_" + type + ".jasper"); Map parameters = new HashMap(); if (yearly) parameters.put("HEADER", "Report for years " + yearstart + " - " + yearend); else parameters.put("HEADER", "Report for " + monthstart + "/" + yearstart + " - " + monthend + "/" + yearend); DBConnection dbconn = TurbineDB.getConnection(); Connection conn = dbconn.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = null; if (type == 1) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE where YEAR(DATE)>=" + yearstart + " and YEAR(DATE)<=" + yearend + " and LOGIN_NAME<>'testuser' group by YEAR, " + (yearly ? "" : "MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME"); } else if (type == 2) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE group by YEAR, " + (yearly ? "" : "MONTH, ") + "MACHINE.NAME"); } JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRResultSetDataSource(rs)); JasperExportManager.exportReportToPdfStream(jasperPrint, outstream); dbconn.close(); } else if (action.equals("exportcmlbyinchi")) { res.setContentType("text/xml"); out = res.getWriter(); String inchi = req.getParameter("inchi"); String spectrumtype = req.getParameter("spectrumtype"); Criteria crit = new Criteria(); crit.add(DBCanonicalNamePeer.NAME, inchi); crit.addJoin(DBCanonicalNamePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.addJoin(DBSpectrumPeer.SPECTRUM_TYPE_ID, DBSpectrumTypePeer.SPECTRUM_TYPE_ID); crit.add(DBSpectrumTypePeer.NAME, spectrumtype); try { GeneralUtils.logToSql(crit.toString(), null); } catch (Exception ex) { } Vector spectra = DBSpectrumPeer.doSelect(crit); if (spectra.size() == 0) { out.write("No such molecule or spectrum"); } else { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = ((DBSpectrum) spectra.get(0)).getDBMolecule().getCML(1); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); for (int k = 0; k < spectra.size(); k++) { Element parentspec = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); } out.write(cmlElement.toXML()); } } else if (action.equals("namelist")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); Criteria crit = new Criteria(); crit.addJoin(DBMoleculePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.add(DBSpectrumPeer.REVIEW_FLAG, "true"); Vector v = DBMoleculePeer.doSelect(crit); for (int i = 0; i < v.size(); i++) { if (i % 500 == 0) { if (i != 0) { zipout.write(new String("<p>The list is continued <a href=\"nmrshiftdb.names." + i + ".html\">here</a></p></body></html>").getBytes()); zipout.closeEntry(); } zipout.putNextEntry(new ZipEntry("nmrshiftdb.names." + i + ".html")); zipout.write(new String("<html><body><h1>This is a list of strcutures in <a href=\"http://www.nmrshiftdb.org\">NMRShiftDB</a>, starting at " + i + ", Its main purpose is to be found by search engines</h1>").getBytes()); } DBMolecule mol = (DBMolecule) v.get(i); zipout.write(new String("<p><a href=\"" + mol.getEasylink(req) + "\">").getBytes()); Vector cannames = mol.getDBCanonicalNames(); for (int k = 0; k < cannames.size(); k++) { zipout.write(new String(((DBCanonicalName) cannames.get(k)).getName() + " ").getBytes()); } Vector chemnames = mol.getDBChemicalNames(); for (int k = 0; k < chemnames.size(); k++) { zipout.write(new String(((DBChemicalName) chemnames.get(k)).getName() + " ").getBytes()); } zipout.write(new String("</a>. Information we have got: NMR spectra").getBytes()); Vector spectra = mol.selectSpectra(); for (int k = 0; k < spectra.size(); k++) { zipout.write(new String(((DBSpectrum) spectra.get(k)).getDBSpectrumType().getName() + ", ").getBytes()); } if (mol.hasAny3d()) zipout.write(new String("3D coordinates, ").getBytes()); zipout.write(new String("File formats: CML, mol, png, jpeg").getBytes()); zipout.write(new String("</p>").getBytes()); } zipout.write(new String("</body></html>").getBytes()); zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("predictor")) { if (req.getParameter("symbol") == null) { res.setContentType("text/plain"); out = res.getWriter(); out.write("please give the symbol to create the predictor for in the request with symbol=X (e. g. symbol=C"); } res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); String filename = "org/openscience/nmrshiftdb/PredictionTool.class"; zipout.putNextEntry(new ZipEntry(filename)); JarInputStream jip = new JarInputStream(new FileInputStream(ServletUtils.expandRelative(getServletConfig(), "/WEB-INF/lib/nmrshiftdb-lib.jar"))); JarEntry entry = jip.getNextJarEntry(); while (entry.getName().indexOf("PredictionTool.class") == -1) { entry = jip.getNextJarEntry(); } for (int i = 0; i < entry.getSize(); i++) { zipout.write(jip.read()); } zipout.closeEntry(); zipout.putNextEntry(new ZipEntry("nmrshiftdb.csv")); int i = 0; org.apache.turbine.util.db.pool.DBConnection conn = TurbineDB.getConnection(); HashMap mapsmap = new HashMap(); while (true) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select HOSE_CODE, VALUE, SYMBOL from HOSE_CODES where CONDITION_TYPE='m' and WITH_RINGS=0 and SYMBOL='" + req.getParameter("symbol") + "' limit " + (i * 1000) + ", 1000"); int m = 0; while (rs.next()) { String code = rs.getString(1); Double value = new Double(rs.getString(2)); String symbol = rs.getString(3); if (mapsmap.get(symbol) == null) { mapsmap.put(symbol, new HashMap()); } for (int spheres = 6; spheres > 0; spheres--) { StringBuffer hoseCodeBuffer = new StringBuffer(); StringTokenizer st = new StringTokenizer(code, "()/"); for (int k = 0; k < spheres; k++) { if (st.hasMoreTokens()) { String partcode = st.nextToken(); hoseCodeBuffer.append(partcode); } if (k == 0) { hoseCodeBuffer.append("("); } else if (k == 3) { hoseCodeBuffer.append(")"); } else { hoseCodeBuffer.append("/"); } } String hoseCode = hoseCodeBuffer.toString(); if (((HashMap) mapsmap.get(symbol)).get(hoseCode) == null) { ((HashMap) mapsmap.get(symbol)).put(hoseCode, new ArrayList()); } ((ArrayList) ((HashMap) mapsmap.get(symbol)).get(hoseCode)).add(value); } m++; } i++; stmt.close(); if (m == 0) break; } Set keySet = mapsmap.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String symbol = (String) it.next(); HashMap hosemap = ((HashMap) mapsmap.get(symbol)); Set keySet2 = hosemap.keySet(); Iterator it2 = keySet2.iterator(); while (it2.hasNext()) { String hoseCode = (String) it2.next(); ArrayList list = ((ArrayList) hosemap.get(hoseCode)); double[] values = new double[list.size()]; for (int k = 0; k < list.size(); k++) { values[k] = ((Double) list.get(k)).doubleValue(); } zipout.write(new String(symbol + "|" + hoseCode + "|" + Statistics.minimum(values) + "|" + Statistics.average(values) + "|" + Statistics.maximum(values) + "\r\n").getBytes()); } } zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; i = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("exportspec") || action.equals("exportmol")) { if (spectrumId > -1) spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(spectrumId)); else spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(req.getParameter("spectrumid"))); export = new Export(spectrum); } else if (action.equals("exportmdl")) { res.setContentType("text/plain"); outstream = res.getOutputStream(); DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(req.getParameter("moleculeid"))); outstream.write(mol.getStructureFile(Integer.parseInt(req.getParameter("coordsetid")), false).getBytes()); } else if (action.equals("exportlastinputs")) { format = action; } else if (action.equals("printpredict")) { res.setContentType("text/html"); out = res.getWriter(); HttpSession session = req.getSession(); VelocityContext context = PredictPortlet.getContext(session, true, true, new StringBuffer(), getServletConfig(), req, true); StringWriter w = new StringWriter(); Velocity.mergeTemplate("predictprint.vm", "ISO-8859-1", context, w); out.println(w.toString()); } else { res.setContentType("text/html"); out = res.getWriter(); out.println("No valid action"); } if (format == null) format = ""; if (format.equals("pdf") || format.equals("rtf")) { res.setContentType("application/" + format); out = res.getWriter(); } if (format.equals("docbook")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); } if (format.equals("svg")) { res.setContentType("image/x-svg"); out = res.getWriter(); } if (format.equals("tiff")) { res.setContentType("image/tiff"); outstream = res.getOutputStream(); } if (format.equals("jpeg")) { res.setContentType("image/jpeg"); outstream = res.getOutputStream(); } if (format.equals("png")) { res.setContentType("image/png"); outstream = res.getOutputStream(); } if (format.equals("mdl") || format.equals("txt") || format.equals("cml") || format.equals("cmlboth") || format.indexOf("exsection") == 0) { res.setContentType("text/plain"); out = res.getWriter(); } if (format.equals("simplehtml") || format.equals("exportlastinputs")) { res.setContentType("text/html"); out = res.getWriter(); } if (action.equals("exportlastinputs")) { int numbertoexport = 4; if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } NmrshiftdbUser user = null; try { user = NmrshiftdbUserPeer.getByName(req.getParameter("username")); } catch (NmrshiftdbException ex) { out.println("Seems <code>username</code> is not OK: " + ex.getMessage()); } if (user != null) { List l = NmrshiftdbUserPeer.executeQuery("SELECT LAST_DOWNLOAD_DATE FROM TURBINE_USER where LOGIN_NAME=\"" + user.getUserName() + "\";"); Date lastDownloadDate = ((Record) l.get(0)).getValue(1).asDate(); if (((new Date().getTime() - lastDownloadDate.getTime()) / 3600000) < 24) { out.println("Your last download was at " + lastDownloadDate + ". You may download your last inputs only once a day. Sorry for this, but we need to be carefull with resources. If you want to put your last inputs on your homepage best use some sort of cache (e. g. use wget for downlaod with crond and link to this static resource))!"); } else { NmrshiftdbUserPeer.executeStatement("UPDATE TURBINE_USER SET LAST_DOWNLOAD_DATE=NOW() where LOGIN_NAME=\"" + user.getUserName() + "\";"); Vector<String> parameters = new Vector<String>(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" and SPECTRUM.USER_ID=" + user.getUserId() + " order by MOLECULE.DATE desc;"; l = NmrshiftdbUserPeer.executeQuery(query); String url = javax.servlet.http.HttpUtils.getRequestURL(req).toString(); url = url.substring(0, url.length() - 17); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); parameters.add(new String("<a href=\"" + url + "/portal/pane0/Results?nmrshiftdbaction=showDetailsFromHome&molNumber=" + mol.getMoleculeId() + "\"><img src=\"" + javax.servlet.http.HttpUtils.getRequestURL(req).toString() + "?nmrshiftdbaction=exportmol&spectrumid=" + ((DBSpectrum) mol.getDBSpectrums().get(0)).getSpectrumId() + "&format=jpeg&size=150x150&backcolor=12632256\"></a>")); } VelocityContext context = new VelocityContext(); context.put("results", parameters); StringWriter w = new StringWriter(); Velocity.mergeTemplate("lateststructures.vm", "ISO-8859-1", context, w); out.println(w.toString()); } } } if (action.equals("exportspec")) { if (format.equals("txt")) { String lastsearchtype = req.getParameter("lastsearchtype"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { List l = ParseUtils.parseSpectrumFromSpecFile(req.getParameter("lastsearchvalues")); spectrum.initSimilarity(l, lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)); } Vector v = spectrum.getOptions(); DBMolecule mol = spectrum.getDBMolecule(); out.print(mol.getChemicalNamesAsOneString(false) + mol.getMolecularFormula(false) + "; " + mol.getMolecularWeight() + " Dalton\n\r"); out.print("\n\rAtom\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("Mult.\t"); out.print("Meas."); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tInput\tDiff"); } out.print("\n\r"); out.print("No.\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("\t"); out.print("Shift"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tShift\tM-I"); } out.print("\n\r"); for (int i = 0; i < v.size(); i++) { out.print(((ValuesForVelocityBean) v.get(i)).getDisplayText() + "\t" + ((ValuesForVelocityBean) v.get(i)).getRange()); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\t" + ((ValuesForVelocityBean) v.get(i)).getNameForElements() + "\t" + ((ValuesForVelocityBean) v.get(i)).getDelta()); } out.print("\n\r"); } } if (format.equals("simplehtml")) { String i1 = export.getImage(false, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[0] = new File(i1).getName(); String i2 = export.getImage(true, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[1] = new File(i2).getName(); String docbook = export.getHtml(); out.print(docbook); } if (format.equals("pdf") || format.equals("rtf")) { String svgSpec = export.getSpecSvg(400, 200); String svgspecfile = relativepath + "/tmp/" + System.currentTimeMillis() + "s.svg"; new FileOutputStream(svgspecfile).write(svgSpec.getBytes()); export.pictures[1] = svgspecfile; String molSvg = export.getMolSvg(true); String svgmolfile = relativepath + "/tmp/" + System.currentTimeMillis() + "m.svg"; new FileOutputStream(svgmolfile).write(molSvg.getBytes()); export.pictures[0] = svgmolfile; String docbook = export.getDocbook("pdf", "SVG"); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource("file:" + GeneralUtils.getNmrshiftdbProperty("docbookxslpath", getServletConfig()) + "/fo/docbook.xsl")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); transformer.transform(new StreamSource(new StringReader(docbook)), new StreamResult(baos)); FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); OutputStream out2 = new ByteArrayOutputStream(); Fop fop = fopFactory.newFop(format.equals("rtf") ? MimeConstants.MIME_RTF : MimeConstants.MIME_PDF, foUserAgent, out2); TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer(); Source src = new StreamSource(new StringReader(baos.toString())); Result res2 = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res2); out.print(out2.toString()); } if (format.equals("docbook")) { String i1 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i1).write(export.getSpecSvg(300, 200).getBytes()); export.pictures[0] = new File(i1).getName(); String i2 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i2).write(export.getMolSvg(true).getBytes()); export.pictures[1] = new File(i2).getName(); String docbook = export.getDocbook("pdf", "SVG"); String docbookfile = relativepath + "/tmp/" + System.currentTimeMillis() + ".xml"; new FileOutputStream(docbookfile).write(docbook.getBytes()); ByteArrayOutputStream baos = export.makeZip(new String[] { docbookfile, i1, i2 }); outstream.write(baos.toByteArray()); } if (format.equals("svg")) { out.print(export.getSpecSvg(400, 200)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(false, format, relativepath + "/tmp/" + System.currentTimeMillis(), true)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("cml")) { out.print(spectrum.getCmlSpect().toXML()); } if (format.equals("cmlboth")) { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = spectrum.getDBMolecule().getCML(1, spectrum.getDBSpectrumType().getName().equals("1H")); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); Element parentspec = spectrum.getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); out.write(cmlElement.toXML()); } if (format.indexOf("exsection") == 0) { StringTokenizer st = new StringTokenizer(format, "-"); st.nextToken(); String template = st.nextToken(); Criteria crit = new Criteria(); crit.add(DBSpectrumPeer.USER_ID, spectrum.getUserId()); Vector v = spectrum.getDBMolecule().getDBSpectrums(crit); VelocityContext context = new VelocityContext(); context.put("spectra", v); context.put("molecule", spectrum.getDBMolecule()); StringWriter w = new StringWriter(); Velocity.mergeTemplate("exporttemplates/" + template, "ISO-8859-1", context, w); out.write(w.toString()); } } if (action.equals("exportmol")) { int width = -1; int height = -1; if (req.getParameter("size") != null) { StringTokenizer st = new StringTokenizer(req.getParameter("size"), "x"); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } boolean shownumbers = true; if (req.getParameter("shownumbers") != null && req.getParameter("shownumbers").equals("false")) { shownumbers = false; } if (req.getParameter("backcolor") != null) { export.backColor = new Color(Integer.parseInt(req.getParameter("backcolor"))); } if (req.getParameter("markatom") != null) { export.selected = Integer.parseInt(req.getParameter("markatom")) - 1; } if (format.equals("svg")) { out.print(export.getMolSvg(true)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(true, format, relativepath + "/tmp/" + System.currentTimeMillis(), width, height, shownumbers, null)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("mdl")) { out.println(spectrum.getDBMolecule().getStructureFile(1, false)); } if (format.equals("cml")) { out.println(spectrum.getDBMolecule().getCMLString(1)); } } if (out != null) out.flush(); else outstream.flush(); } catch (Exception ex) { ex.printStackTrace(); out.print(GeneralUtils.logError(ex, "NmrshiftdbServlet", null, true)); out.flush(); } }
00
Code Sample 1: public TVRageShowInfo(String xmlShowName) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime")) airTime = tmp[1]; } if (airTime.length() != 0) { tmp = airTime.split(","); airTimeHour = tmp[1]; } in.close(); url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } } Code Sample 2: public DDS getDDS() throws MalformedURLException, IOException, ParseException, DDSException, DODSException { InputStream is; if (fileStream != null) is = parseMime(fileStream); else { URL url = new URL(urlString + ".dds" + projString + selString); is = openConnection(url); } DDS dds = new DDS(); try { dds.parse(is); } finally { is.close(); if (connection instanceof HttpURLConnection) ((HttpURLConnection) connection).disconnect(); } return dds; }
00
Code Sample 1: public synchronized void checkout() throws SQLException, InterruptedException { Connection con = this.session.open(); con.setAutoCommit(false); String sql_stmt = DB2SQLStatements.shopping_cart_getAll(this.customer_id); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet res = stmt.executeQuery(sql_stmt); res.last(); int rowcount = res.getRow(); res.beforeFirst(); ShoppingCartItem[] resArray = new ShoppingCartItem[rowcount]; int i = 0; while (res.next()) { resArray[i] = new ShoppingCartItem(); resArray[i].setCustomer_id(res.getInt("customer_id")); resArray[i].setDate_start(res.getDate("date_start")); resArray[i].setDate_stop(res.getDate("date_stop")); resArray[i].setRoom_type_id(res.getInt("room_type_id")); resArray[i].setNumtaken(res.getInt("numtaken")); resArray[i].setTotal_price(res.getInt("total_price")); i++; } this.wait(4000); try { for (int j = 0; j < rowcount; j++) { sql_stmt = DB2SQLStatements.room_date_update(resArray[j]); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); } } catch (SQLException e) { e.printStackTrace(); con.rollback(); } for (int j = 0; j < rowcount; j++) { System.out.println(j); sql_stmt = DB2SQLStatements.booked_insert(resArray[j], 2); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); } sql_stmt = DB2SQLStatements.shopping_cart_deleteAll(this.customer_id); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); con.commit(); this.session.close(con); } Code Sample 2: @Override public DownloadObject download() throws IOException { final HttpGet findLink = new HttpGet(url.toString()); final HttpResponse response = this.client.execute(findLink); final String body = IOUtil.getString(response); LinkTag linkTag = null; try { linkTag = HtmlParserUtil.findLink(MegaUploadDownloader.DOWNLOAD_LINK_PATTERN, body); } catch (ParserException e) { } if (linkTag != null) { String link = linkTag.extractLink(); final String filename = IOUtil.getBaseName(link).trim(); link = link.replaceAll("&#[0-9]*;", "_"); final URL url = new URL(link); final String newLink = link.replaceAll(Pattern.quote(IOUtil.getBaseName(url.getPath())), URLEncoder.encode(IOUtil.getBaseName(url.getPath()), "UTF-8")); final HttpGet download = new HttpGet(newLink); final HttpResponse downloadResponse = this.client.execute(download); final HttpEntity downloadEntity = downloadResponse.getEntity(); final long filesize = downloadEntity.getContentLength(); return createObject(downloadEntity.getContent(), filename, filesize); } else { throw new RuntimeException("No download link."); } }
11
Code Sample 1: public void executaAlteracoes() { Album album = Album.getAlbum(); Photo[] fotos = album.getFotos(); Photo f; int ultimoFotoID = -1; int albumID = album.getAlbumID(); sucesso = true; PainelWebFotos.setCursorWait(true); albumID = recordAlbumData(album, albumID); sucesso = recordFotoData(fotos, ultimoFotoID, albumID); String caminhoAlbum = Util.getFolder("albunsRoot").getPath() + File.separator + albumID; File diretorioAlbum = new File(caminhoAlbum); if (!diretorioAlbum.isDirectory()) { if (!diretorioAlbum.mkdir()) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.7]/ERRO: diretorio " + caminhoAlbum + " n�o pode ser criado. abortando"); return; } } for (int i = 0; i < fotos.length; i++) { f = fotos[i]; if (f.getCaminhoArquivo().length() > 0) { try { FileChannel canalOrigem = new FileInputStream(f.getCaminhoArquivo()).getChannel(); FileChannel canalDestino = new FileOutputStream(caminhoAlbum + File.separator + f.getFotoID() + ".jpg").getChannel(); canalDestino.transferFrom(canalOrigem, 0, canalOrigem.size()); canalOrigem = null; canalDestino = null; } catch (Exception e) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.8]/ERRO: " + e); sucesso = false; } } } prepareThumbsAndFTP(fotos, albumID, caminhoAlbum); prepareExtraFiles(album, caminhoAlbum); fireChangesToGUI(fotos); dispatchAlbum(); PainelWebFotos.setCursorWait(false); } Code Sample 2: public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String slopeOneDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); System.out.println(movieDiffStats.size()); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public void save(File selectedFile) throws IOException { if (storeEntriesInFiles) { boolean moved = false; for (int i = 0; i < tempFiles.size(); i++) { File newFile = new File(selectedFile.getAbsolutePath() + "_" + Integer.toString(i) + ".zettmp"); moved = tempFiles.get(i).renameTo(newFile); if (!moved) { BufferedReader read = new BufferedReader(new FileReader(tempFiles.get(i))); PrintWriter write = new PrintWriter(newFile); String s; while ((s = read.readLine()) != null) write.print(s); read.close(); write.flush(); write.close(); tempFiles.get(i).delete(); } tempFiles.set(i, newFile); } } GZIPOutputStream output = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(selectedFile))); XStream xml_convert = new XStream(); xml_convert.setMode(XStream.ID_REFERENCES); xml_convert.toXML(this, output); output.flush(); output.close(); }
11
Code Sample 1: public static void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) { FileOutputStream os = null; DataOutputStream dos = null; try { LPKTable[] fileTable = new LPKTable[srcFilePath.length]; long fileOffset = outputOffset(header); for (int i = 0; i < srcFilePath.length; i++) { String sourceFileName = FileUtils.getFileName(srcFilePath[i]); long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]); LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset); fileOffset = outputNextOffset(sourceFileSize, fileOffset); fileTable[i] = ft; } File file = new File(makeFilePath); if (!file.exists()) { FileUtils.makedirs(file); } os = new FileOutputStream(file); dos = new DataOutputStream(os); dos.writeInt(header.getPAKIdentity()); writeByteArray(header.getPassword(), dos); dos.writeFloat(header.getVersion()); dos.writeLong(header.getTables()); for (int i = 0; i < fileTable.length; i++) { writeByteArray(fileTable[i].getFileName(), dos); dos.writeLong(fileTable[i].getFileSize()); dos.writeLong(fileTable[i].getOffSet()); } for (int i = 0; i < fileTable.length; i++) { File ftFile = new File(srcFilePath[i]); FileInputStream ftFis = new FileInputStream(ftFile); DataInputStream ftDis = new DataInputStream(ftFis); byte[] buff = new byte[256]; int readLength = 0; while ((readLength = ftDis.read(buff)) != -1) { makeBuffer(buff, readLength); dos.write(buff, 0, readLength); } ftDis.close(); ftFis.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (dos != null) { try { dos.close(); dos = null; } catch (IOException e) { } } } } Code Sample 2: public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } }
11
Code Sample 1: public static void main(String arg[]) { try { String readFile = arg[0]; String writeFile = arg[1]; java.io.FileInputStream ss = new java.io.FileInputStream(readFile); ManagedMemoryDataSource ms = new ManagedMemoryDataSource(ss, 1024 * 1024, "foo/data", true); javax.activation.DataHandler dh = new javax.activation.DataHandler(ms); java.io.InputStream is = dh.getInputStream(); java.io.FileOutputStream fo = new java.io.FileOutputStream(writeFile); byte[] buf = new byte[512]; int read = 0; do { read = is.read(buf); if (read > 0) { fo.write(buf, 0, read); } } while (read > -1); fo.close(); is.close(); } catch (java.lang.Exception e) { log.error(Messages.getMessage("exception00"), e); } } Code Sample 2: public static void loadConfig(DeviceEntry defaultDevice, EmulatorContext emulatorContext) { Config.defaultDevice = defaultDevice; Config.emulatorContext = emulatorContext; File configFile = new File(getConfigPath(), "config2.xml"); try { if (configFile.exists()) { loadConfigFile("config2.xml"); } else { configFile = new File(getConfigPath(), "config.xml"); if (configFile.exists()) { loadConfigFile("config.xml"); for (Enumeration e = getDeviceEntries().elements(); e.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) e.nextElement(); if (!entry.canRemove()) { continue; } removeDeviceEntry(entry); File src = new File(getConfigPath(), entry.getFileName()); File dst = File.createTempFile("dev", ".jar", getConfigPath()); IOUtils.copyFile(src, dst); entry.setFileName(dst.getName()); addDeviceEntry(entry); } } else { createDefaultConfigXml(); } saveConfig(); } } catch (IOException ex) { Logger.error(ex); createDefaultConfigXml(); } finally { if (configXml == null) { createDefaultConfigXml(); } } urlsMRU.read(configXml.getChildOrNew("files").getChildOrNew("recent")); initSystemProperties(); }
11
Code Sample 1: @Override protected Object transform(Row inputs) throws FunctionException { StringBuffer buffer = new StringBuffer(); for (IColumn c : inputs.getColumns()) { buffer.append(c.getValueAsString() + "|"); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(buffer.toString().getBytes()); byte[] hash = digest.digest(); return getHex(hash); } catch (Exception e) { throw new FunctionException(e); } } Code Sample 2: @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); EntityManager em = EMF.get().createEntityManager(); String url = req.getRequestURL().toString(); String key = req.getParameter("key"); String format = req.getParameter("format"); if (key == null || !key.equals(Keys.APPREGKEY)) { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (format != null && format.equals("xml")) resp.getWriter().print(Error.notAuthorised("").toXML(em)); else resp.getWriter().print(Error.notAuthorised("").toJSON(em)); em.close(); return; } String appname = req.getParameter("name"); if (appname == null || appname.equals("")) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.noAppId(null).toXML(em)); else resp.getWriter().print(Error.noAppId(null).toJSON(em)); em.close(); return; } StringBuffer appkey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + appname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { appkey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } ClientApp app = new ClientApp(); app.setName(appname); app.setKey(appkey.toString()); app.setNumreceipts(0L); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(app); tx.commit(); } catch (Throwable t) { log.severe("Error persisting application " + app.getName() + ": " + t.getMessage()); tx.rollback(); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); em.close(); return; } resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(app.toXML(em)); else resp.getWriter().print(app.toJSON(em)); em.close(); }
11
Code Sample 1: public synchronized String getEncryptedPassword(String plaintext, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; try { md = MessageDigest.getInstance(algorithm); md.update(plaintext.getBytes("UTF-8")); } catch (NoSuchAlgorithmException nsae) { throw nsae; } catch (UnsupportedEncodingException uee) { throw uee; } return (new BigInteger(1, md.digest())).toString(16); } Code Sample 2: private String getEncryptedPassword() { String encrypted; char[] pwd = password.getPassword(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(new String(pwd).getBytes("UTF-8")); byte[] digested = md.digest(); encrypted = new String(Base64Coder.encode(digested)); } catch (Exception e) { encrypted = new String(pwd); } for (int i = 0; i < pwd.length; i++) pwd[i] = 0; return encrypted; }
11
Code Sample 1: public void run() { if (saveAsDialog == null) { saveAsDialog = new FileDialog(window.getShell(), SWT.SAVE); saveAsDialog.setFilterExtensions(saveAsTypes); } String outputFile = saveAsDialog.open(); if (outputFile != null) { Object inputFile = DataSourceSingleton.getInstance().getContainer().getWrapped(); InputStream in; try { if (inputFile instanceof URL) in = ((URL) inputFile).openStream(); else in = new FileInputStream((File) inputFile); OutputStream out = new FileOutputStream(outputFile); if (outputFile.endsWith("xml")) { int c; while ((c = in.read()) != -1) out.write(c); } else { PrintWriter pw = new PrintWriter(out); Element data = DataSourceSingleton.getInstance().getRawData(); writeTextFile(data, pw, -1); pw.close(); } in.close(); out.close(); } catch (MalformedURLException e1) { } catch (IOException e) { } } } Code Sample 2: private static void copier(FichierElectronique source, FichierElectronique cible) throws IOException { cible.setNom(source.getNom()); cible.setTaille(source.getTaille()); cible.setTypeMime(source.getTypeMime()); cible.setSoumetteur(source.getSoumetteur()); cible.setDateDerniereModification(source.getDateDerniereModification()); cible.setEmprunteur(source.getEmprunteur()); cible.setDateEmprunt(source.getDateEmprunt()); cible.setNumeroVersion(source.getNumeroVersion()); InputStream inputStream = source.getInputStream(); OutputStream outputStream = cible.getOutputStream(); try { IOUtils.copy(inputStream, outputStream); } finally { try { inputStream.close(); } finally { outputStream.close(); } if (source instanceof FichierElectroniqueDefaut) { FichierElectroniqueDefaut fichierElectroniqueTemporaire = (FichierElectroniqueDefaut) source; fichierElectroniqueTemporaire.deleteTemp(); } } }
11
Code Sample 1: public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); } Code Sample 2: void copyFile(File src, File dst) throws IOException { FileInputStream fis = new FileInputStream(src); byte[] buf = new byte[10000]; int n; FileOutputStream fos = new FileOutputStream(dst); while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); copied++; }
00
Code Sample 1: public void testSimpleHttpPostsWithContentLength() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } Code Sample 2: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
11
Code Sample 1: private boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { System.out.println("Copy Error: IOException during copy\r\n" + ioe.getMessage()); return false; } } Code Sample 2: private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } }
00
Code Sample 1: public FileInputStream execute() { FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); String pdfPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf"); try { FileOutputStream outputStream = new FileOutputStream(pdfPath + "/driveTogether.pdf"); PdfWriter writer = PdfWriter.getInstance(doc, outputStream); doc.open(); String pfad = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf/template.pdf"); logger.info("Loading PDF-Template: " + pfad); PdfReader reader = new PdfReader(pfad); PdfImportedPage page = writer.getImportedPage(reader, 1); PdfContentByte cb = writer.getDirectContent(); cb.addTemplate(page, 0, 0); doHeader(); doParagraph(trip, forUser); doc.close(); fis = new FileInputStream(pdfPath + "/driveTogether.pdf"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fis; } Code Sample 2: public static byte[] sendRequestV1(String url, Map<String, Object> params, String secretCode, String method, Map<String, String> files, String encoding, String signMethod, Map<String, String> headers, String contentType) { HttpClient client = new HttpClient(); byte[] result = null; if (method.equalsIgnoreCase("get")) { GetMethod getMethod = new GetMethod(url); if (contentType == null || contentType.equals("")) getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); else getMethod.setRequestHeader("Content-Type", contentType); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); getMethod.setRequestHeader(key, headers.get(key)); } } try { NameValuePair[] getData; if (params != null) { if (secretCode == null) getData = new NameValuePair[params.size()]; else getData = new NameValuePair[params.size() + 1]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); getData[i] = new NameValuePair(key, params.get(key).toString()); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature2(params, secretCode, "md5".equalsIgnoreCase(signMethod), isHMac, PARAMETER_SIGN); getData[i] = new NameValuePair(PARAMETER_SIGN, sign); } getMethod.setQueryString(getData); } client.executeMethod(getMethod); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = getMethod.getResponseBodyAsStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (bout != null) bout.close(); } } catch (Exception ex) { logger.error(ex, ex); } finally { if (getMethod != null) getMethod.releaseConnection(); } } if (method.equalsIgnoreCase("post")) { PostMethod postMethod = new PostMethod(url); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); postMethod.setRequestHeader(key, headers.get(key)); } } try { if (contentType == null) { if (files != null && files.size() > 0) { Part[] parts; if (secretCode == null) parts = new Part[params.size() + files.size()]; else parts = new Part[params.size() + 1 + files.size()]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); parts[i] = new StringPart(key, params.get(key).toString(), "UTF-8"); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature(params, secretCode, isHMac, PARAMETER_SIGN); parts[i] = new StringPart(PARAMETER_SIGN, sign); i++; } iters = files.keySet().iterator(); while (iters.hasNext()) { String key = (String) iters.next(); if (files.get(key).toString().startsWith("http://")) { InputStream bin = null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { URL fileurl = new URL(files.get(key).toString()); bin = fileurl.openStream(); byte[] buf = new byte[500]; int count = 0; while ((count = bin.read(buf)) > 0) { bout.write(buf, 0, count); } parts[i] = new FilePart(key, new ByteArrayPartSource(fileurl.getFile().substring(fileurl.getFile().lastIndexOf("/") + 1), bout.toByteArray())); } catch (Exception ex) { logger.error(ex, ex); } finally { if (bin != null) bin.close(); if (bout != null) bout.close(); } } else parts[i] = new FilePart(key, new File(files.get(key).toString())); i++; } postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else { NameValuePair[] postData; if (params != null) { if (secretCode == null) postData = new NameValuePair[params.size()]; else postData = new NameValuePair[params.size() + 1]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); postData[i] = new NameValuePair(key, params.get(key).toString()); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature(params, secretCode, isHMac, PARAMETER_SIGN); postData[i] = new NameValuePair(PARAMETER_SIGN, sign); } postMethod.setRequestBody(postData); } if (contentType == null || contentType.equals("")) postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); } } else { String content = (String) params.get(params.keySet().iterator().next()); RequestEntity entiry = new StringRequestEntity(content, contentType, "UTF-8"); postMethod.setRequestEntity(entiry); } client.executeMethod(postMethod); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = postMethod.getResponseBodyAsStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { logger.error(ex, ex); } finally { if (bout != null) bout.close(); } } catch (Exception e) { logger.error(e, e); } finally { if (postMethod != null) postMethod.releaseConnection(); } } return result; }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private void fileCopy(File filename) throws IOException { if (this.stdOut) { this.fileDump(filename); return; } File source_file = new File(spoolPath + "/" + filename); File destination_file = new File(copyPath + "/" + filename); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file); if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file); if (destination_file.exists()) { if (destination_file.isFile()) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file); if (!this.overwrite) { System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): "); System.out.flush(); if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled."); } } else throw new FileCopyException("destination is not a file: " + destination_file); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file); if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while ((bytes_read = source.read(buffer)) != -1) { destination.write(buffer, 0, bytes_read); } System.out.println("File " + filename + " successfull copied to " + destination_file); if (this.keep == false && source_file.isFile()) { try { source.close(); } catch (Exception e) { } if (source_file.delete()) { new File(this.spoolPath + "/info/" + filename + ".desc").delete(); } } } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.flush(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } }
00
Code Sample 1: protected void writeGZippedBytes(byte array[], TupleOutput out) { if (array == null || array.length == 0) { out.writeBoolean(false); writeBytes(array, out); return; } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); GZIPOutputStream gzout = new GZIPOutputStream(baos); ByteArrayInputStream bais = new ByteArrayInputStream(array); IOUtils.copyTo(bais, gzout); gzout.finish(); gzout.close(); bais.close(); byte compressed[] = baos.toByteArray(); if (compressed.length < array.length) { out.writeBoolean(true); writeBytes(compressed, out); } else { out.writeBoolean(false); writeBytes(array, out); } } catch (IOException err) { throw new RuntimeException(err); } } Code Sample 2: static void xmlRpcCall(String method, String[] params) throws LastFMError { try { XmlPullParserFactory fac = XmlPullParserFactory.newInstance(); XmlSerializer serializer = fac.newSerializer(); URL url; url = new URL(XMLRPC_URL); URLConnection conn; conn = url.openConnection(); conn.setRequestProperty("Content-Type", "text/xml"); conn.setDoOutput(true); serializer.setOutput(conn.getOutputStream(), "UTF-8"); serializer.startDocument("UTF-8", true); serializer.startTag(null, "methodCall"); serializer.startTag(null, "methodName"); serializer.text(method); serializer.endTag(null, "methodName"); serializer.startTag(null, "params"); for (String s : params) { serializer.startTag(null, "param"); serializer.startTag(null, "value"); serializer.startTag(null, "string"); serializer.text(s); serializer.endTag(null, "string"); serializer.endTag(null, "value"); serializer.endTag(null, "param"); } serializer.endTag(null, "params"); serializer.endTag(null, "methodCall"); serializer.flush(); InputStream is = conn.getInputStream(); DocumentBuilderFactory dbFac = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbFac.newDocumentBuilder(); Document doc = db.parse(is); try { String res = Utils.getChildElement(doc.getDocumentElement(), new String[] { "params", "param", "value", "string" }); if (!res.equals("OK")) { Log.e(TAG, "while xmlrpc got " + res); throw new LastFMXmlRpcError("XMLRPC Call failed: " + res); } } catch (ParseException e) { String faultString = Utils.getChildElement(doc.getDocumentElement(), new String[] { "params", "param", "value", "struct", "member[1]", "value", "string" }); throw new LastFMXmlRpcError(faultString); } } catch (LastFMXmlRpcError e) { throw e; } catch (Exception e) { Log.e(TAG, "while xmlrpc", e); throw new LastFMError(e.toString()); } }
00
Code Sample 1: public EFaxResult sendFax(ototype.SendFaxWrapper parameters) { EFaxResult efr = new EFaxResult(); if (!validFaxUser(parameters.getUserID(), parameters.getPassWord())) { efr.setResultCode(211); return efr; } Connection conn = null; String faxKey = getSegquence("t_fax_send") + ""; String sql = "insert into t_fax_send(faxKey,userID,appcode,sendername," + "sendernumber,sendercompany,sendtime,accountId, userId2, PID, moduleId, CDRType) values(?,?,?,?,?,?,?,?,?,?,?,?)"; Fax fax = parameters.getFax(); FaxContactor sender = fax.getSender(); FaxContactor[] receiver = fax.getReceiver(); try { conn = this.getJdbcTemplate().getDataSource().getConnection(); conn.setAutoCommit(false); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, faxKey); pstmt.setString(2, parameters.getUserID()); pstmt.setString(3, parameters.getAppCode()); pstmt.setString(4, sender.getContactor()); pstmt.setString(5, sender.getFaxNumber()); pstmt.setString(6, sender.getCompany()); pstmt.setString(7, fax.getSendTime()); pstmt.setString(8, parameters.getAccountId()); pstmt.setString(9, parameters.getUserId()); pstmt.setString(10, parameters.getPID()); pstmt.setInt(11, parameters.getModuleId()); pstmt.setInt(12, parameters.getCDRType()); pstmt.executeUpdate(); sql = "insert into t_fax_contactor(faxKey,contactorID,contactor,faxnumber,company) values(?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); for (int k = 0; k < receiver.length; k++) { pstmt.setString(1, faxKey); pstmt.setString(2, receiver[k].getContactorID()); pstmt.setString(3, receiver[k].getContactor()); pstmt.setString(4, receiver[k].getFaxNumber()); pstmt.setString(5, receiver[k].getCompany()); pstmt.addBatch(); } pstmt.executeBatch(); sql = "insert into t_fax_file(faxKey,fileID,filename,filetype,fileurl,faxpages) values(?,?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); FaxFile[] files = fax.getFiles(); for (int h = 0; h < files.length; h++) { String fileID = getSegquence("t_Fax_file") + ""; pstmt.setString(1, faxKey); pstmt.setString(2, fileID); pstmt.setString(3, files[h].getFileName()); pstmt.setString(4, files[h].getFileType()); pstmt.setString(5, files[h].getFileURL()); pstmt.setInt(6, files[h].getFaxPages()); Service.writeByteFile(files[h].getFile(), fileID); pstmt.addBatch(); } pstmt.executeBatch(); conn.commit(); efr.setResultCode(100); efr.setResultInfo(faxKey); } catch (SQLException e) { efr.setResultCode(200); try { conn.rollback(); } catch (Exception e1) { logger.error("Error validFaxUser", e1); } logger.error("Error validFaxUser", e); } catch (IOException e) { efr.setResultCode(200); logger.error("Error write file on sendfax", e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { logger.error("Error sendFax on close conn", e); } } } return efr; } Code Sample 2: public static InputStream getUrlInputStream(final java.net.URL url) throws java.io.IOException, java.lang.InstantiationException { final java.net.URLConnection conn = url.openConnection(); conn.connect(); final InputStream input = url.openStream(); if (input == null) { throw new java.lang.InstantiationException("Url " + url + " does not provide data."); } return input; }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
11
Code Sample 1: public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); } Code Sample 2: public void addForwardAddress(final List<NewUser> forwardAddresses) { try { final List<Integer> usersToRemoveFromCache = new ArrayList<Integer>(); connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("userForwardAddresses.add")); Iterator<NewUser> iter = forwardAddresses.iterator(); Iterator<String> iter2; NewUser newUser; while (iter.hasNext()) { newUser = iter.next(); psImpl.setInt(1, newUser.userId); iter2 = newUser.forwardAddresses.iterator(); while (iter2.hasNext()) { psImpl.setString(2, iter2.next()); psImpl.executeUpdate(); } usersToRemoveFromCache.add(newUser.userId); } } }); connection.commit(); cmDB.removeUsers(usersToRemoveFromCache); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
11
Code Sample 1: public static int gunzipFile(File file_input, File dir_output) { GZIPInputStream gzip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); gzip_in_stream = new GZIPInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } String file_input_name = file_input.getName(); String file_output_name = file_input_name.substring(0, file_input_name.length() - 3); File output_file = new File(dir_output, file_output_name); byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = gzip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } try { gzip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: public void testIsVersioned() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); assertTrue(emptySource.isVersioned()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } assertTrue(emptySource.isVersioned()); }
00
Code Sample 1: private void trySend(Primitive p) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { mSerializer.serialize(p, out); } catch (SerializerException e) { mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.SERIALIZER_ERROR, "Internal serializer error, primitive: " + p.getType()); out.close(); return; } HttpPost req = new HttpPost(mPostUri); req.addHeader(mContentTypeHeader); if (mMsisdnHeader != null) { req.addHeader(mMsisdnHeader); } ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); req.setEntity(entity); mLastActive = SystemClock.elapsedRealtime(); if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) { long sendBytes = entity.getContentLength() + 176; ImpsLog.log(mConnection.getLoginUserName() + " >> " + p.getType() + " HTTP payload approx. " + sendBytes + " bytes"); } if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) { ImpsLog.dumpRawPacket(out.toByteArray()); ImpsLog.dumpPrimitive(p); } HttpResponse res = mHttpClient.execute(req); StatusLine statusLine = res.getStatusLine(); HttpEntity resEntity = res.getEntity(); InputStream in = resEntity.getContent(); if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) { Log.d(ImpsLog.PACKET_TAG, statusLine.toString()); Header[] headers = res.getAllHeaders(); for (Header h : headers) { Log.d(ImpsLog.PACKET_TAG, h.toString()); } int len = (int) resEntity.getContentLength(); if (len > 0) { byte[] content = new byte[len]; int offset = 0; int bytesRead = 0; do { bytesRead = in.read(content, offset, len); offset += bytesRead; len -= bytesRead; } while (bytesRead > 0); in.close(); ImpsLog.dumpRawPacket(content); in = new ByteArrayInputStream(content); } } try { if (statusLine.getStatusCode() != HttpURLConnection.HTTP_OK) { mTxManager.notifyErrorResponse(p.getTransactionID(), statusLine.getStatusCode(), statusLine.getReasonPhrase()); return; } if (resEntity.getContentLength() == 0) { if ((p.getTransactionMode() != TransactionMode.Response) && !p.getType().equals(ImpsTags.Polling_Request)) { mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.ILLEGAL_SERVER_RESPONSE, "bad response from server"); } return; } Primitive response = mParser.parse(in); if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) { ImpsLog.dumpPrimitive(response); } if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) { long len = 2 + resEntity.getContentLength() + statusLine.toString().length() + 2; Header[] headers = res.getAllHeaders(); for (Header header : headers) { len += header.getName().length() + header.getValue().length() + 4; } ImpsLog.log(mConnection.getLoginUserName() + " << " + response.getType() + " HTTP payload approx. " + len + "bytes"); } if (!mReceiveQueue.offer(response)) { mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.UNKNOWN_ERROR, "receiving queue full"); } } catch (ParserException e) { ImpsLog.logError(e); mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.PARSER_ERROR, "Parser error, received a bad response from server"); } finally { resEntity.consumeContent(); } } Code Sample 2: private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
11
Code Sample 1: public void run() { long starttime = (new Date()).getTime(); Matcher m = Pattern.compile("(\\S+);(\\d+)").matcher(Destination); boolean completed = false; if (OutFile.length() > IncommingProcessor.MaxPayload) { logger.warn("Payload is too large!"); close(); } else { if (m.find()) { Runnable cl = new Runnable() { public void run() { WaitToClose(); } }; Thread t = new Thread(cl); t.start(); S = null; try { String ip = m.group(1); int port = Integer.valueOf(m.group(2)); SerpentEngine eng = new SerpentEngine(); byte[] keybytes = new byte[eng.getBlockSize()]; byte[] ivbytes = new byte[eng.getBlockSize()]; Random.nextBytes(keybytes); Random.nextBytes(ivbytes); KeyParameter keyparm = new KeyParameter(keybytes); ParametersWithIV keyivparm = new ParametersWithIV(keyparm, ivbytes); byte[] parmbytes = BCUtils.writeParametersWithIV(keyivparm); OAEPEncoding enc = new OAEPEncoding(new ElGamalEngine(), new RIPEMD128Digest()); enc.init(true, PublicKey); byte[] encbytes = enc.encodeBlock(parmbytes, 0, parmbytes.length); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SerpentEngine())); cipher.init(true, keyivparm); byte[] inbuffer = new byte[128]; byte[] outbuffer = new byte[256]; int readlen = 0; int cryptlen = 0; FileInputStream fis = new FileInputStream(OutFile); FileOutputStream fos = new FileOutputStream(TmpFile); readlen = fis.read(inbuffer); while (readlen >= 0) { if (readlen > 0) { cryptlen = cipher.processBytes(inbuffer, 0, readlen, outbuffer, 0); fos.write(outbuffer, 0, cryptlen); } readlen = fis.read(inbuffer); } cryptlen = cipher.doFinal(outbuffer, 0); if (cryptlen > 0) { fos.write(outbuffer, 0, cryptlen); } fos.close(); fis.close(); S = new Socket(ip, port); DataOutputStream dos = new DataOutputStream(S.getOutputStream()); dos.writeInt(encbytes.length); dos.write(encbytes); dos.writeLong(TmpFile.length()); fis = new FileInputStream(TmpFile); readlen = fis.read(inbuffer); while (readlen >= 0) { dos.write(inbuffer, 0, readlen); readlen = fis.read(inbuffer); } DataInputStream dis = new DataInputStream(S.getInputStream()); byte[] encipbytes = StreamUtils.readBytes(dis); cipher.init(false, keyivparm); byte[] decipbytes = new byte[encipbytes.length]; int len = cipher.processBytes(encipbytes, 0, encipbytes.length, decipbytes, 0); len += cipher.doFinal(decipbytes, len); byte[] realbytes = new byte[len]; System.arraycopy(decipbytes, 0, realbytes, 0, len); String ipstr = new String(realbytes, "ISO-8859-1"); Callback.Success(ipstr); completed = true; dos.write(0); dos.flush(); close(); } catch (Exception e) { close(); if (!completed) { e.printStackTrace(); Callback.Fail(e.getMessage()); } } } else { close(); logger.warn("Improper destination string. " + Destination); Callback.Fail("Improper destination string. " + Destination); } } CloseWait(); long newtime = (new Date()).getTime(); long timediff = newtime - starttime; logger.debug("Outgoing processor took: " + timediff); } Code Sample 2: private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } }
11
Code Sample 1: public static Shader loadShader(String vspath, String fspath, int textureUnits, boolean separateCam, boolean fog) throws ShaderProgramProcessException { if (vspath == "" || fspath == "") return null; BufferedReader in; String vert = "", frag = ""; try { URL v_url = Graphics.class.getClass().getResource("/eu/cherrytree/paj/graphics/shaders/" + vspath); String v_path = AppDefinition.getDefaultDataPackagePath() + "/shaders/" + vspath; if (v_url != null) in = new BufferedReader(new InputStreamReader(v_url.openStream())); else in = new BufferedReader(new InputStreamReader(new FileReader(v_path).getInputStream())); boolean run = true; String str; while (run) { str = in.readLine(); if (str != null) vert += str + "\n"; else run = false; } in.close(); } catch (Exception e) { System.err.println("Couldn't read in vertex shader \"" + vspath + "\"."); throw new ShaderNotLoadedException(vspath, fspath); } try { URL f_url = Graphics.class.getClass().getResource("/eu/cherrytree/paj/graphics/shaders/" + fspath); String f_path = AppDefinition.getDefaultDataPackagePath() + "/shaders/" + fspath; if (f_url != null) in = new BufferedReader(new InputStreamReader(f_url.openStream())); else in = new BufferedReader(new InputStreamReader(new FileReader(f_path).getInputStream())); boolean run = true; String str; while (run) { str = in.readLine(); if (str != null) frag += str + "\n"; else run = false; } in.close(); } catch (Exception e) { System.err.println("Couldn't read in fragment shader \"" + fspath + "\"."); throw new ShaderNotLoadedException(vspath, fspath); } return loadShaderFromSource(vert, frag, textureUnits, separateCam, fog); } Code Sample 2: public String htmlContentSimple(String urlStr, String charset) { StringBuffer html = new StringBuffer(); URL url = null; BufferedReader reader = null; try { url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream(), charset)); String line; while ((line = reader.readLine()) != null) { html.append(line).append("\r\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return html.toString(); }
11
Code Sample 1: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } Code Sample 2: private static void copyFile(File source, File dest, boolean visibleFilesOnly) throws IOException { if (visibleFilesOnly && isHiddenOrDotFile(source)) { return; } if (dest.exists()) { System.err.println("Destination File Already Exists: " + dest); } FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
11
Code Sample 1: public static void copy(File file, File dir, boolean overwrite) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); File out = new File(dir, file.getName()); if (out.exists() && !overwrite) { throw new IOException("File: " + out + " already exists."); } FileOutputStream fos = new FileOutputStream(out, false); byte[] block = new byte[4096]; int read = bis.read(block); while (read != -1) { fos.write(block, 0, read); read = bis.read(block); } } Code Sample 2: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; }
00
Code Sample 1: private String getShaderIncludeSource(String path) throws Exception { URL url = this.getClass().getResource(path); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); boolean run = true; String str; String ret = new String(); while (run) { str = in.readLine(); if (str != null) ret += str + "\n"; else run = false; } in.close(); return ret; } Code Sample 2: public synchronized void downloadTile(TileNumber tn) { try { Bitmap tile = getMapFromSdCache(tn); if (tile == null) { URL url = new URL("http://tile.openstreetmap.org/" + tn.getZoom() + "/" + tn.getX() + "/" + tn.getY() + ".png"); tile = BitmapFactory.decodeStream(url.openStream()); File sdCardPath = Environment.getExternalStorageDirectory(); Log.d(ctx.getResources().getString(open.gps.gopens.R.string.TEST), "Path to SD :: " + sdCardPath.getAbsolutePath()); File dir = new File(sdCardPath + ctx.getResources().getString(open.gps.gopens.R.string.CACHE_PATH) + tn.getZoom() + "/" + tn.getX() + "/"); dir.mkdirs(); File imgFile = new File(dir.getAbsolutePath() + "/" + tn.getY() + ".png"); imgFile.createNewFile(); FileOutputStream fOut = new FileOutputStream(imgFile); tile.compress(Bitmap.CompressFormat.PNG, 100, fOut); } cacheManager.put(tn.toString(), tile); setChanged(); notifyObservers(); Log.d("OBS", "OBS : Notify"); } catch (MalformedURLException e) { Log.e("Error", e.getMessage()); } catch (IOException e) { Log.e("Error", e.getMessage()); } }
11
Code Sample 1: public static String hash(String value) { MessageDigest md = null; try { md = MessageDigest.getInstance(HASH_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } try { md.update(value.getBytes(INPUT_ENCODING)); } catch (UnsupportedEncodingException e) { throw new CryptoException(e); } return new BASE64Encoder().encode(md.digest()); } Code Sample 2: @SuppressWarnings("unchecked") private int syncCustomers() throws RemoteException, BasicException { dlintegration.syncCustomersBefore(); ArrayList<String> notToSync = new ArrayList<String>(); int step = 0; User[] remoteUsers; int cpt = 0; do { remoteUsers = externalsales.getUsersBySteps(step); step++; if (remoteUsers == null) { throw new BasicException(AppLocal.getIntString("message.returnnull") + " > Customers null"); } if (remoteUsers.length > 0) { String perms; for (User remoteUser : remoteUsers) { if (notToSync.contains(remoteUser.getLogin())) continue; cpt++; String name = externalsales.encodeString((remoteUser.getFirstname().trim() + " " + remoteUser.getLastname()).trim()); String firstname = externalsales.encodeString(remoteUser.getFirstname()); String lastname = externalsales.encodeString(remoteUser.getLastname()); String description = externalsales.encodeString(remoteUser.getDescription()); String address = externalsales.encodeString(remoteUser.getAddress()); String address2 = externalsales.encodeString(remoteUser.getAddress2()); String city = externalsales.encodeString(remoteUser.getCity()); String country = externalsales.encodeString(remoteUser.getCountry()); String phone = externalsales.encodeString(remoteUser.getPhone()); String mobile = externalsales.encodeString(remoteUser.getMobile()); String zipcode = externalsales.encodeString(remoteUser.getZipcode()); CustomerSync copyCustomer = new CustomerSync(remoteUser.getId()); if (firstname == null || firstname.equals("")) firstname = " "; copyCustomer.setFirstname(firstname.toUpperCase()); if (lastname == null || lastname.equals("")) lastname = " "; copyCustomer.setLastname(lastname.toUpperCase()); copyCustomer.setTaxid(remoteUser.getLogin()); copyCustomer.setSearchkey(remoteUser.getLogin() + name.toUpperCase()); if (name == null || name.equals("")) name = " "; copyCustomer.setName(name.toUpperCase()); if (description == null || description.equals("")) description = " "; copyCustomer.setNotes(description); copyCustomer.setEmail(remoteUser.getEmail()); if (address == null || address.equals("")) address = " "; copyCustomer.setAddress(address); if (address2 == null || address2.equals("")) address2 = " "; copyCustomer.setAddress2(address2); if (city == null || city.equals("")) city = "Brussels"; copyCustomer.setCity(city); if (country == null || country.equals("")) country = "Belgium"; copyCustomer.setCountry(country); copyCustomer.setMaxdebt(10000.0); if (phone == null || phone.equals("")) phone = " "; copyCustomer.setPhone(phone); if (mobile == null || mobile.equals("")) mobile = " "; copyCustomer.setPhone2(mobile); if (zipcode == null || zipcode.equals("")) zipcode = " "; copyCustomer.setPostal(zipcode); if (TicketInfo.isWS() && TicketInfo.getPayID() == 2 && remoteUser.getEmail().contains("@DONOTSENDME")) { notToSync.add(copyCustomer.getTaxid()); continue; } dlintegration.syncCustomer(copyCustomer); notToSync.add(copyCustomer.getTaxid()); } } } while (remoteUsers.length > 0); List<CustomerSync> localList = dlintegration.getCustomers(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (CustomerSync localCustomer : localList) { Date now = new Date(); if (notToSync.contains(localCustomer.getTaxid())) { continue; } cpt++; User userAdd = new User(); userAdd.setLogin(localCustomer.getTaxid()); userAdd.setId(localCustomer.getTaxid()); userAdd.setFirstname(" "); String tmpName = localCustomer.getName().trim(); tmpName = tmpName.replace("'", ""); while (tmpName.charAt(0) == ' ') { tmpName = tmpName.substring(1); } userAdd.setLastname(tmpName); char[] pw = new char[8]; int c = 'A'; int r1 = 0; for (int i = 0; i < 8; i++) { r1 = (int) (Math.random() * 3); switch(r1) { case 0: c = '0' + (int) (Math.random() * 10); break; case 1: c = 'a' + (int) (Math.random() * 26); break; case 2: c = 'A' + (int) (Math.random() * 26); break; } pw[i] = (char) c; } String clave = new String(pw); byte[] password = { 00 }; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(clave.getBytes()); password = md5.digest(); userAdd.setPassword(password.toString()); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UsersSync.class.getName()).log(Level.SEVERE, null, ex); userAdd.setPassword(clave); } userAdd.setTitle("M"); if (localCustomer.getEmail() == null || localCustomer.getEmail().trim().equals("") || localCustomer.getEmail().indexOf('@') <= 0) userAdd.setEmail(localCustomer.getTaxid() + defaultEmail); else userAdd.setEmail(localCustomer.getEmail()); userAdd.setDescription(localCustomer.getNotes() + ""); userAdd.setAddress(localCustomer.getAddress() + ""); userAdd.setAddress2(localCustomer.getAddress2() + ""); userAdd.setState_region(localCustomer.getRegion() + ""); userAdd.setCity(localCustomer.getCity() + ""); userAdd.setCountry(localCustomer.getCountry() + ""); userAdd.setZipcode(localCustomer.getPostal() + ""); userAdd.setPhone(localCustomer.getPhone() + ""); userAdd.setMobile(localCustomer.getPhone2() + ""); userAdd.setFax(" "); try { userAdd.setCdate(df.format(localCustomer.getCurdate())); } catch (NullPointerException nu) { userAdd.setCdate(df.format(now)); } userAdd.setPerms("shopper"); userAdd.setBank_account_nr(""); userAdd.setBank_account_holder(""); userAdd.setBank_account_type(""); userAdd.setBank_iban(""); userAdd.setBank_name(""); userAdd.setBank_sort_code(""); userAdd.setMdate(df.format(now)); userAdd.setShopper_group_id("1"); externalsales.addUser(userAdd); } return cpt; }