label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static void parseSohuStock(ArrayList<String> dataSource, final ArrayList<SohuStockBean> sohuStockBeanList) throws IOReactorException, InterruptedException { HttpAsyncClient httpclient = new DefaultHttpAsyncClient(); httpclient.start(); if (dataSource != null && dataSource.size() > 0) { final CountDownLatch latch = new CountDownLatch(dataSource.size()); for (int i = 0; i < dataSource.size(); i++) { final HttpGet request = new HttpGet(dataSource.get(i)); httpclient.execute(request, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { System.out.println(" Request completed " + count + " " + request.getRequestLine() + " " + response.getStatusLine()); try { HttpEntity he = response.getEntity(); try { String resp = EntityUtils.toString(he, "gb2312"); if (resp != null && resp.length() > 0) { SohuStockBean shstBean = SohuStockPostProcess.postSohuStockBeanProcess(resp); sohuStockBeanList.add(shstBean); } count++; } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } latch.countDown(); } catch (RuntimeException re) { latch.countDown(); } } public void failed(final Exception ex) { latch.countDown(); } public void cancelled() { latch.countDown(); } }); } latch.await(); System.out.println("done"); } if (httpclient != null) { httpclient.shutdown(); } System.out.println(sohuStockBeanList.size()); } Code Sample 2: private void onOKAction() { if (url == null) { optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); JOptionPane.showMessageDialog(this, "URL field cannot be empty", "Empty URL", JOptionPane.ERROR_MESSAGE); } else { try { URLConnection sourceConnection = url.openConnection(); sourceConnection.setConnectTimeout(10); if (sourceConnection.getContentLength() == -1) { throw new IOException("Can't connect to " + url.toString()); } exit_status = OK; setVisible(false); dispose(); } catch (IOException e) { optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); JOptionPane.showMessageDialog(this, "Please enter valid, resolvable source and target URLs...\n " + e.getMessage(), "Invalid URL", JOptionPane.ERROR_MESSAGE); } } }
00
Code Sample 1: private byte[] rawHttpPost(URL serverTimeStamp, Hashtable reqProperties, byte[] postData) { logger.info("[rawHttpPost.in]:: " + Arrays.asList(new Object[] { serverTimeStamp, reqProperties, postData })); URLConnection urlConn; DataOutputStream printout; DataInputStream input; byte[] responseBody = null; try { urlConn = serverTimeStamp.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); Iterator iter = reqProperties.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); urlConn.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } logger.debug("POSTing to: " + serverTimeStamp + " ..."); printout = new DataOutputStream(urlConn.getOutputStream()); printout.write(postData); printout.flush(); printout.close(); input = new DataInputStream(urlConn.getInputStream()); byte[] buffer = new byte[1024]; int bytesRead = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { baos.write(buffer, 0, bytesRead); } input.close(); responseBody = baos.toByteArray(); } catch (MalformedURLException me) { logger.warn("[rawHttpPost]:: ", me); } catch (IOException ioe) { logger.warn("[rawHttpPost]:: ", ioe); } return responseBody; } Code Sample 2: private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
11
Code Sample 1: public static String sendScripts(Session session) { Channel channel = null; String tempDirectory = ""; Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "Start sendScripts."); try { { channel = session.openChannel("exec"); final String command = "mktemp -d /tmp/scipionXXXXXXXX"; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); tempDirectory = result[1]; tempDirectory = tempDirectory.replaceAll("\n", ""); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + tempDirectory); IOUtils.closeQuietly(in); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream rsyncHelperContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_HELPER_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(rsyncHelperContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream askPassContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_ASKPASS_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(askPassContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } } catch (IOException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (JSchException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "End sendScripts."); return tempDirectory; } Code Sample 2: public static Image loadImage(String path) { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = mainFrame.getClass().getResourceAsStream(path); if (in == null) throw new RuntimeException("Ressource " + path + " not found"); try { IOUtils.copy(in, out); in.close(); out.flush(); } catch (IOException e) { e.printStackTrace(); new RuntimeException("Error reading ressource " + path, e); } return Toolkit.getDefaultToolkit().createImage(out.toByteArray()); }
11
Code Sample 1: public void run() { StringBuffer xml; String tabName; Element guiElement; setBold(monitor.getReading()); setBold(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Working"); HttpMethod method = null; xml = new StringBuffer(); File tempfile = new File(url); if (tempfile.exists()) { try { InputStream in = new FileInputStream(tempfile); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading XML file from local file"); e.printStackTrace(System.err); return; } } else { try { HttpClient client = new HttpClient(); method = new GetMethod(url); int response = client.executeMethod(method); if (response == 200) { InputStream in = method.getResponseBodyAsStream(); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } else { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed. Incorrect response from HTTP Server " + response); return; } } catch (IOException e) { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed, error while reading XML file from HTTP Server"); e.printStackTrace(System.err); return; } } setPlain(monitor.getReading()); setPlain(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Done"); setBold(monitor.getValidating()); setBold(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Working"); DocumentBuilderFactoryImpl factory = new DocumentBuilderFactoryImpl(); try { DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(new ByteArrayInputStream(xml.toString().getBytes())); if (method != null) { method.releaseConnection(); } Element root = document.getDocumentElement(); NodeList temp = root.getElementsByTagName("resource"); for (int j = 0; j < temp.getLength(); j++) { Element resource = (Element) temp.item(j); resources.add(new URL(resource.getAttribute("url"))); } NodeList connections = root.getElementsByTagName("jmxserver"); for (int j = 0; j < connections.getLength(); j++) { Element connection = (Element) connections.item(j); String name = connection.getAttribute("name"); String tempUrl = connection.getAttribute("url"); String auth = connection.getAttribute("auth"); if (tempUrl.indexOf("${host}") != -1) { HostDialog dialog = new HostDialog(Config.getHosts()); String host = dialog.showDialog(); if (host == null) { System.out.println("Host can not be null, unable to create panel."); return; } tempUrl = tempUrl.replaceAll("\\$\\{host\\}", host); Config.addHost(host); } JMXServiceURL jmxUrl = new JMXServiceURL(tempUrl); JmxServerGraph server = new JmxServerGraph(name, jmxUrl, new JmxWorker(false)); if (auth != null && auth.equalsIgnoreCase("true")) { LoginTrueService loginService = new LoginTrueService(); JXLoginPanel.Status status = JXLoginPanel.showLoginDialog(null, loginService); if (status != JXLoginPanel.Status.SUCCEEDED) { return; } server.setUsername(loginService.getName()); server.setPassword(loginService.getPassword()); } servers.put(name, server); NodeList listeners = connection.getElementsByTagName("listener"); for (int i = 0; i < listeners.getLength(); i++) { Element attribute = (Element) listeners.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String filtertype = attribute.getAttribute("filterType"); TaskNotificationListener listener = new TaskNotificationListener(); NotificationFilterSupport filter = new NotificationFilterSupport(); if (filtertype == null || "".equals(filtertype)) { filter = null; } else { filter.enableType(filtertype); } Task task = new Task(-1, Task.LISTEN, server); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); } NodeList attributes = connection.getElementsByTagName("attribute"); for (int i = 0; i < attributes.getLength(); i++) { Element attribute = (Element) attributes.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String attributename = attribute.getAttribute("attributename"); String frequency = attribute.getAttribute("frequency"); String onEvent = attribute.getAttribute("onEvent"); if (frequency.equalsIgnoreCase("onchange")) { TaskNotificationListener listener = new TaskNotificationListener(); AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter(); filter.enableAttribute(attributename); Task task = new Task(-1, Task.LISTEN, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } Task task2 = new Task(-1, Task.GET_ATTRIBUTE, server); task2.setAttribute(att); task2.setMbean(mbean); server.getWorker().addTask(task2); List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); hashTempList.add(task2); tasks.put(taskname, hashTempList); } else { int frequency2 = Integer.parseInt(frequency); Task task = new Task(frequency2, Task.GET_ATTRIBUTE, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); TaskNotificationListener listener = null; if (onEvent != null && !"".equals(onEvent)) { Task tempTask = tasks.get(onEvent).get(0); if (tempTask == null) { System.out.println(onEvent + " was not found."); return; } else { listener = (TaskNotificationListener) tempTask.getListener(); } } if (listener == null) { server.getWorker().addTask(task); } else { listener.addTask(task); } } } } NodeList guiTemp = root.getElementsByTagName("gui"); guiElement = (Element) guiTemp.item(0); tabName = guiElement.getAttribute("name"); if (MonitorServer.contains(tabName)) { JOptionPane.showMessageDialog(null, "This panel is already open, stoping creating of panel.", "Panel already exists", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setTitleAt(i, tabName); break; } } NodeList tempBindings = root.getElementsByTagName("binding"); for (int i = 0; i < tempBindings.getLength(); i++) { Element binding = (Element) tempBindings.item(i); String guiname = binding.getAttribute("guiname"); String tmethod = binding.getAttribute("method"); String taskname = binding.getAttribute("taskname"); String formater = binding.getAttribute("formater"); BindingContainer tempBinding; if (formater == null || (formater != null && formater.equals(""))) { tempBinding = new BindingContainer(guiname, tmethod, taskname); } else { tempBinding = new BindingContainer(guiname, tmethod, taskname, formater); } bindings.add(tempBinding); } } catch (Exception e) { System.err.println("Exception message: " + e.getMessage()); System.out.println("Loading Monitor Failed, couldnt parse XML file."); e.printStackTrace(System.err); return; } setPlain(monitor.getValidating()); setPlain(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Done"); setBold(monitor.getDownload()); setBold(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Working"); List<File> jarFiles = new ArrayList<File>(); File cacheDir = new File(Config.getCacheDir()); if (!cacheDir.exists()) { cacheDir.mkdir(); } for (URL resUrl : resources) { try { HttpClient client = new HttpClient(); HttpMethod methodRes = new GetMethod(resUrl.toString()); int response = client.executeMethod(methodRes); if (response == 200) { int index = resUrl.toString().lastIndexOf("/") + 1; File file = new File(Config.getCacheDir() + resUrl.toString().substring(index)); FileOutputStream out = new FileOutputStream(file); InputStream in = methodRes.getResponseBodyAsStream(); int readTemp = 0; while ((readTemp = in.read()) != -1) { out.write(readTemp); } System.out.println(file.getName() + " downloaded."); methodRes.releaseConnection(); if (file.getName().endsWith(".jar")) { jarFiles.add(file); } } else { methodRes.releaseConnection(); System.out.println("Loading Monitor Failed. Unable to get resource " + url); return; } } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading resource file " + "from HTTP Server"); e.printStackTrace(System.err); return; } } URL[] urls = new URL[jarFiles.size()]; try { for (int i = 0; i < jarFiles.size(); i++) { File file = jarFiles.get(i); File newFile = new File(Config.getCacheDir() + "/" + System.currentTimeMillis() + file.getName()); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(newFile); int n = 0; byte[] buf = new byte[1024]; while ((n = in.read(buf, 0, 1024)) > -1) { out.write(buf, 0, n); } out.close(); out.close(); in.close(); urls[i] = new URL("file:" + newFile.getAbsolutePath()); } } catch (Exception e1) { System.out.println("Unable to load jar files."); e1.printStackTrace(); } URLClassLoader loader = new URLClassLoader(urls); engine.setClassLoader(loader); setPlain(monitor.getDownload()); setPlain(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Done"); setBold(monitor.getGui()); setBold(monitor.getGuiStatus()); monitor.getGuiStatus().setText(" Working"); Container container; try { String tempXml = xml.toString(); int start = tempXml.indexOf("<gui"); start = tempXml.indexOf('>', start) + 1; int end = tempXml.indexOf("</gui>"); container = engine.render(new StringReader(tempXml.substring(start, end))); } catch (Exception e) { e.printStackTrace(System.err); System.err.println("Exception msg: " + e.getMessage()); System.out.println("Loading Monitor Failed, error creating gui."); return; } for (BindingContainer bcon : bindings) { List<Task> temp = tasks.get(bcon.getTask()); if (temp == null) { System.out.println("Task with name " + bcon.getTask() + " doesnt exist."); } else { for (Task task : temp) { if (task != null) { Object comp = engine.find(bcon.getComponent()); if (comp != null) { if (task.getTaskType() == Task.LISTEN && task.getFilter() instanceof AttributeChangeNotificationFilter) { TaskNotificationListener listener = (TaskNotificationListener) task.getListener(); if (bcon.getFormater() == null) { listener.addResultListener(new Binding(comp, bcon.getMethod())); } else { listener.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } else { if (bcon.getFormater() == null) { task.addResultListener(new Binding(comp, bcon.getMethod())); } else { task.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } } else { System.out.println("Refering to gui name, " + bcon.getComponent() + ", that doesnt exist. Unable to create monitor."); return; } } else { System.out.println("Refering to task name, " + bcon.getTask() + ", that doesnt exist. Unable to create monitor."); return; } } } } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setComponentAt(i, new MonitorContainerPanel(container, this)); break; } } System.out.println("Connecting to server(s)."); Enumeration e = servers.keys(); List<JmxWorker> list = new ArrayList<JmxWorker>(); while (e.hasMoreElements()) { JmxWorker worker = servers.get(e.nextElement()).getWorker(); worker.setRunning(true); worker.start(); list.add(worker); } MonitorServer.add(tabName, list); Config.addUrl(url); } Code Sample 2: protected void copy(File src, File dest) throws IOException { if (src.isDirectory() && dest.isFile()) throw new IOException("Cannot copy a directory to a file"); if (src.isDirectory()) { File newDir = new File(dest, src.getName()); if (!newDir.mkdirs()) throw new IOException("Cannot create a new Directory"); File[] entries = src.listFiles(); for (int i = 0; i < entries.length; ++i) copy(entries[i], newDir); return; } if (dest.isDirectory()) { File newFile = new File(dest, src.getName()); newFile.createNewFile(); copy(src, newFile); return; } try { if (src.length() == 0) { dest.createNewFile(); return; } FileChannel fc = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); long transfered = 0; long totalLength = src.length(); while (transfered < totalLength) { long num = fc.transferTo(transfered, totalLength - transfered, dstChannel); if (num == 0) throw new IOException("Error while copying"); transfered += num; } dstChannel.close(); fc.close(); } catch (IOException e) { if (os.equals("Unix")) { _logger.fine("Trying to use cp to copy file..."); File cp = new File("/usr/bin/cp"); if (!cp.exists()) cp = new File("/bin/cp"); if (!cp.exists()) cp = new File("/usr/local/bin/cp"); if (!cp.exists()) cp = new File("/sbin/cp"); if (!cp.exists()) cp = new File("/usr/sbin/cp"); if (!cp.exists()) cp = new File("/usr/local/sbin/cp"); if (cp.exists()) { Process cpProcess = Runtime.getRuntime().exec(cp.getAbsolutePath() + " '" + src.getAbsolutePath() + "' '" + dest.getAbsolutePath() + "'"); int errCode; try { errCode = cpProcess.waitFor(); } catch (java.lang.InterruptedException ie) { throw e; } return; } } throw e; } }
00
Code Sample 1: public static boolean changeCredentials() { boolean passed = false; boolean credentials = false; HashMap info = null; Debug.log("Main.changeCredentials", "show dialog for userinfo"); info = getUserInfo(); if ((Boolean) info.get("submit")) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(info.get("password").toString().getBytes()); String passHash = new BigInteger(1, md5.digest()).toString(16); Debug.log("Main.changeCredentials", "validate credentials with the database"); passed = xmlRpcC.checkUser(info.get("username").toString(), passHash); Debug.log("Main.changeCredentials", "write the credentials to file"); xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash); credentials = passed; testVar = true; } catch (Exception ex) { System.out.println(ex.toString()); if (ex.getMessage().toLowerCase().contains("unable")) { JOptionPane.showMessageDialog(null, "Database problem occured, please try again later", "Error", JOptionPane.ERROR_MESSAGE); passed = true; testVar = false; } else { passed = Boolean.parseBoolean(ex.getMessage()); JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE); } } } else { if (new File(userdataFile).exists()) { testVar = true; credentials = true; } else { testVar = false; JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed until you enter them ", "Warning", JOptionPane.ERROR_MESSAGE); } passed = true; } while (!passed) { Debug.log("Main.changeCredentials", "show dialog for userinfo"); info = getUserInfo(); if ((Boolean) info.get("submit")) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(info.get("password").toString().getBytes()); String passHash = new BigInteger(1, md5.digest()).toString(16); Debug.log("Main.changeCredentials", "validate credentials with the database"); passed = xmlRpcC.checkUser(info.get("username").toString(), passHash); Debug.log("Main.changeCredentials", "write credentials to local xml file"); xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash); credentials = passed; testVar = true; } catch (Exception ex) { Debug.log("Main.changeCredentials", "credential validation failed"); passed = Boolean.parseBoolean(ex.getMessage()); JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE); } } else { if (new File(userdataFile).exists()) { testVar = true; credentials = true; } else { testVar = false; JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed untill u enter them ", "Warning", JOptionPane.ERROR_MESSAGE); } passed = true; } } return credentials; } Code Sample 2: private String fetchContent() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { buf.append(str); } return buf.toString(); }
11
Code Sample 1: private void insert() throws SQLException, NamingException { Logger logger = getLogger(); if (logger.isDebugEnabled()) { logger.debug("enter - " + getClass().getName() + ".insert()"); } try { if (logger.isInfoEnabled()) { logger.info("insert(): Create new sequencer record for " + getName()); } Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(dataSourceName); conn = ds.getConnection(); conn.setReadOnly(false); stmt = conn.prepareStatement(INSERT_SEQ); stmt.setString(INS_NAME, getName()); stmt.setLong(INS_NEXT_KEY, defaultInterval * 2); stmt.setLong(INS_INTERVAL, defaultInterval); stmt.setLong(INS_UPDATE, System.currentTimeMillis()); try { if (stmt.executeUpdate() != 1) { nextId = -1L; logger.warn("insert(): Failed to create sequencer entry for " + getName() + " (no error message)"); } else if (logger.isInfoEnabled()) { nextId = defaultInterval; nextSeed = defaultInterval * 2; interval = defaultInterval; logger.info("insert(): First ID will be " + nextId); } } catch (SQLException e) { logger.warn("insert(): Error inserting row into database, possible concurrency issue: " + e.getMessage()); if (logger.isDebugEnabled()) { e.printStackTrace(); } nextId = -1L; } if (!conn.getAutoCommit()) { conn.commit(); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException ignore) { } } if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) { } } if (conn != null) { if (!conn.getAutoCommit()) { try { conn.rollback(); } catch (SQLException ignore) { } } try { conn.close(); } catch (SQLException ignore) { } } } } finally { if (logger.isDebugEnabled()) { logger.debug("exit - " + getClass().getName() + ".insert()"); } } } Code Sample 2: protected void doBackupOrganizeType() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strSelQuery = "SELECT organize_type_id,organize_type_name,width " + "FROM " + Common.ORGANIZE_TYPE_TABLE; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_B_TABLE + " " + "(version_no,organize_type_id,organize_type_name,width) " + "VALUES (?,?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strSelQuery); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setInt(1, this.versionNO); ps.setString(2, result.getString("organize_type_id")); ps.setString(3, result.getString("organize_type_name")); ps.setInt(4, result.getInt("width")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeType(): ERROR Inserting data " + "in T_SYS_ORGANIZE_B_TYPE INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeType(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doBackupOrganizeType(): SQLException while committing or rollback"); } }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true); IOUtils.copy(reader, out, null); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } 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 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(); } }
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: JcrFile createBody(Part part) throws IOException, MessagingException { JcrFile body = new JcrFile(); body.setName("part"); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); body.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); body.setMimeType(part.getContentType()); body.setLastModified(java.util.Calendar.getInstance()); return body; }
11
Code Sample 1: private synchronized void persist() { Connection conn = null; try { PoolManager pm = PoolManager.getInstance(); conn = pm.getConnection(JukeXTrackStore.DB_NAME); conn.setAutoCommit(false); Statement state = conn.createStatement(); state.executeUpdate("DELETE FROM PlaylistEntry WHERE playlistid=" + this.id); if (this.size() > 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO PlaylistEntry ( playlistid , trackid , position ) VALUES "); int location = 0; Iterator i = ll.iterator(); while (i.hasNext()) { long currTrackID = ((DatabaseObject) i.next()).getId(); sql.append('(').append(this.id).append(',').append(currTrackID).append(',').append(location++).append(')'); if (i.hasNext()) sql.append(','); } state.executeUpdate(sql.toString()); } conn.commit(); conn.setAutoCommit(true); state.close(); } catch (SQLException se) { try { conn.rollback(); } catch (SQLException ignore) { } log.error("Encountered an error persisting a playlist", se); } finally { try { conn.close(); } catch (SQLException ignore) { } } } Code Sample 2: public void SetRoles(Connection conn, User user, String[] roles) throws NpsException { if (!IsSysAdmin() && !IsLocalAdmin()) throw new NpsException(ErrorHelper.ACCESS_NOPRIVILEGE); PreparedStatement pstmt = null; ResultSet rs = null; try { String sql = "delete from userrole where userid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.id); pstmt.executeUpdate(); if (roles != null && roles.length > 0) { try { pstmt.close(); } catch (Exception e1) { } sql = "insert into userrole(userid,roleid) values(?,?)"; pstmt = conn.prepareStatement(sql); for (int i = 0; i < roles.length; i++) { if (roles[i] != null && roles[i].length() > 0) { pstmt.setString(1, user.GetId()); pstmt.setString(2, roles[i]); pstmt.executeUpdate(); } } } try { pstmt.close(); } catch (Exception e1) { } if (user.roles_by_name != null) user.roles_by_name.clear(); if (user.roles_by_id != null) user.roles_by_id.clear(); if (roles != null && roles.length > 0) { sql = "select b.* from UserRole a,Role b where a.roleid = b.id and a.userid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.id); rs = pstmt.executeQuery(); while (rs.next()) { if (user.roles_by_name == null) user.roles_by_name = new Hashtable(); if (user.roles_by_id == null) user.roles_by_id = new Hashtable(); user.roles_by_name.put(rs.getString("name"), rs.getString("id")); user.roles_by_id.put(rs.getString("id"), rs.getString("name")); } } } catch (Exception e) { try { conn.rollback(); } catch (Exception e1) { } nps.util.DefaultLog.error(e); } finally { if (rs != null) try { rs.close(); } catch (Exception e) { } if (pstmt != null) try { pstmt.close(); } catch (Exception e1) { } } }
00
Code Sample 1: public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); PreparedStatement ps = con.prepareStatement(this.deleteSQL); ps.setString(1, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } } Code Sample 2: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
00
Code Sample 1: @Override public boolean putDescription(String uuid, String description) throws DatabaseException { if (uuid == null) throw new NullPointerException("uuid"); if (description == null) throw new NullPointerException("description"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } boolean found = true; try { PreparedStatement findSt = getConnection().prepareStatement(SELECT_COMMON_DESCRIPTION_STATEMENT); PreparedStatement updSt = null; findSt.setString(1, uuid); ResultSet rs = findSt.executeQuery(); found = rs.next(); int modified = 0; updSt = getConnection().prepareStatement(found ? UPDATE_COMMON_DESCRIPTION_STATEMENT : INSERT_COMMON_DESCRIPTION_STATEMENT); updSt.setString(1, description); updSt.setString(2, uuid); modified = updSt.executeUpdate(); if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + findSt + "\" and \"" + updSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Queries: \"" + findSt + "\" and \"" + updSt + "\""); found = false; } } catch (SQLException e) { LOGGER.error(e); found = false; } finally { closeConnection(); } return found; } Code Sample 2: public byte[] authClient(String host, String user, String passwd, String realm, String serverChallenge) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream b64os = new BASE64EncoderStream(bos, Integer.MAX_VALUE); SecureRandom random; try { random = new SecureRandom(); md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { if (debugout != null) debugout.println("DEBUG DIGEST-MD5: " + ex); throw new IOException(ex.toString()); } StringBuffer result = new StringBuffer(); uri = "smtp/" + host; String nc = "00000001"; String qop = "auth"; byte[] bytes = new byte[32]; int resp; if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Begin authentication ..."); Hashtable map = tokenize(serverChallenge); if (realm == null) { String text = (String) map.get("realm"); realm = text != null ? new StringTokenizer(text, ",").nextToken() : host; } String nonce = (String) map.get("nonce"); random.nextBytes(bytes); b64os.write(bytes); b64os.flush(); String cnonce = bos.toString(); bos.reset(); md5.update(md5.digest(ASCIIUtility.getBytes(user + ":" + realm + ":" + passwd))); md5.update(ASCIIUtility.getBytes(":" + nonce + ":" + cnonce)); clientResponse = toHex(md5.digest()) + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":"; md5.update(ASCIIUtility.getBytes("AUTHENTICATE:" + uri)); md5.update(ASCIIUtility.getBytes(clientResponse + toHex(md5.digest()))); result.append("username=\"" + user + "\""); result.append(",realm=\"" + realm + "\""); result.append(",qop=" + qop); result.append(",nc=" + nc); result.append(",nonce=\"" + nonce + "\""); result.append(",cnonce=\"" + cnonce + "\""); result.append(",digest-uri=\"" + uri + "\""); result.append(",response=" + toHex(md5.digest())); if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Response => " + result.toString()); b64os.write(ASCIIUtility.getBytes(result.toString())); b64os.flush(); return bos.toByteArray(); }
00
Code Sample 1: public static void copyFile(String fromFile, String toFile) { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } state = CONNECTED; logger.info("Successfully logged in"); version = determineVersion(); writer.setTargetVersion(version); logger.info("Determined Asterisk version: " + version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
11
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: private String generateHash(String key, String data) throws ChiropteraException { try { MessageDigest md = MessageDigest.getInstance(Constants.Connection.Auth.MD5); md.update(key.getBytes()); byte[] raw = md.digest(); String s = toHexString(raw); SecretKey skey = new SecretKeySpec(s.getBytes(), Constants.Connection.Auth.HMACMD5); Mac mac = Mac.getInstance(skey.getAlgorithm()); mac.init(skey); byte digest[] = mac.doFinal(data.getBytes()); String digestB64 = BaculaBase64.binToBase64(digest); return digestB64.substring(0, digestB64.length()); } catch (NoSuchAlgorithmException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } catch (InvalidKeyException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException 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 String crypt(String suppliedPassword) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(suppliedPassword.getBytes()); String encriptedPassword = null; try { encriptedPassword = new String(Base64.encode(md.digest()), "ASCII"); } catch (UnsupportedEncodingException e) { } return encriptedPassword; }
00
Code Sample 1: public static void pingSearchEngine(String engineURL) throws MalformedURLException, UnsupportedEncodingException { if ((ConfigurationManager.getProperty("http.proxy.host") != null) && (ConfigurationManager.getProperty("http.proxy.port") != null)) { System.setProperty("proxySet", "true"); System.setProperty("proxyHost", ConfigurationManager.getProperty("http.proxy.host")); System.getProperty("proxyPort", ConfigurationManager.getProperty("http.proxy.port")); } String sitemapURL = ConfigurationManager.getProperty("dspace.url") + "/sitemap"; URL url = new URL(engineURL + URLEncoder.encode(sitemapURL, "UTF-8")); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer resp = new StringBuffer(); while ((inputLine = in.readLine()) != null) { resp.append(inputLine).append("\n"); } in.close(); if (connection.getResponseCode() == 200) { log.info("Pinged " + url.toString() + " successfully"); } else { log.warn("Error response pinging " + url.toString() + ":\n" + resp); } } catch (IOException e) { log.warn("Error pinging " + url.toString(), e); } } Code Sample 2: public static void translateTableMetaData(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table", nsDefinition); String filename = baseDir + "table.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + ".xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + ".json", baseDir + tableName + ".xsl"); }
00
Code Sample 1: @Override public void run() { try { if (LOG.isDebugEnabled()) { LOG.debug("Backupthread started"); } if (_file.exists()) { _file.delete(); } final ZipOutputStream zOut = new ZipOutputStream(new FileOutputStream(_file)); zOut.setLevel(9); final File xmlFile = File.createTempFile("mp3db", ".xml"); final OutputStream ost = new FileOutputStream(xmlFile); final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(ost, "UTF-8"); writer.writeStartDocument("UTF-8", "1.0"); writer.writeCharacters("\n"); writer.writeStartElement("mp3db"); writer.writeAttribute("version", Integer.toString(Main.ENGINEVERSION)); final MediafileDAO mfDAO = new MediafileDAO(); final AlbumDAO aDAO = new AlbumDAO(); final CdDAO cdDAO = new CdDAO(); final CoveritemDAO ciDAO = new CoveritemDAO(); int itemCount = 0; try { itemCount += mfDAO.getCount(); itemCount += aDAO.getCount(); itemCount += cdDAO.getCount(); itemCount += ciDAO.getCount(); fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, itemCount)); } catch (final Exception e) { LOG.error("Error getting size", e); fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, -1)); } int cdCounter = 0; int mediafileCounter = 0; int albumCounter = 0; int coveritemCounter = 0; int counter = 0; final List<CdIf> data = cdDAO.getCdsOrderById(); if (data.size() > 0) { final Map<Integer, Integer> albums = new HashMap<Integer, Integer>(); final Iterator<CdIf> it = data.iterator(); while (it.hasNext() && !_break) { final CdIf cd = it.next(); final Integer cdId = Integer.valueOf(cdCounter++); writer.writeStartElement(TypeConstants.XML_CD); exportCd(writer, cd, cdId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); final List<MediafileIf> files = cd.getMediafiles(); final Iterator<MediafileIf> mfit = files.iterator(); MediafileIf mf; while (mfit.hasNext() && !_break) { mf = mfit.next(); final Integer mfId = Integer.valueOf(mediafileCounter++); writer.writeStartElement(TypeConstants.XML_MEDIAFILE); exportMediafile(writer, mf, mfId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); final AlbumIf a = mf.getAlbum(); if (a != null) { Integer inte; if (albums.containsKey(a.getAid())) { inte = albums.get(a.getAid()); writeLink(writer, TypeConstants.XML_ALBUM, inte); } else { inte = Integer.valueOf(albumCounter++); writer.writeStartElement(TypeConstants.XML_ALBUM); exportAlbum(writer, a, inte); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); albums.put(a.getAid(), inte); if (a.hasCoveritems() && !_break) { final List<CoveritemIf> covers = a.getCoveritems(); final Iterator<CoveritemIf> coit = covers.iterator(); while (coit.hasNext() && !_break) { final Integer coveritemId = Integer.valueOf(coveritemCounter++); exportCoveritem(writer, zOut, coit.next(), coveritemId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); } } writer.writeEndElement(); } GenericDAO.getEntityManager().close(); } writer.writeEndElement(); } writer.writeEndElement(); writer.flush(); it.remove(); GenericDAO.getEntityManager().close(); } } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); ost.flush(); ost.close(); if (_break) { zOut.close(); _file.delete(); } else { zOut.putNextEntry(new ZipEntry("mp3.xml")); final InputStream xmlIn = FileUtils.openInputStream(xmlFile); IOUtils.copy(xmlIn, zOut); xmlIn.close(); zOut.close(); } xmlFile.delete(); fireStatusEvent(new StatusEvent(this, StatusEventType.FINISH)); } catch (final Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Error backup database", e); } fireStatusEvent(new StatusEvent(this, e, "")); _messenger.fireMessageEvent(new MessageEvent(this, "ERROR", MessageEventTypeEnum.ERROR, GuiStrings.getInstance().getString("error.backup"), e)); } } Code Sample 2: private void readFromStorableInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); StorableInput input = new StorableInput(stream); fDrawing.release(); fDrawing = (Drawing) input.readStorable(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error:" + e); } }
11
Code Sample 1: public String execute(HttpServletRequest request, HttpServletResponse response, User user, String parameter) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, parameter, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; } Code Sample 2: public void init(String[] arguments) { if (arguments.length < 1) { printHelp(); return; } String[] valid_args = new String[] { "device*", "d*", "help", "h", "speed#", "s#", "file*", "f*", "gpsd*", "nmea", "n", "garmin", "g", "sirf", "i", "rawdata", "downloadtracks", "downloadwaypoints", "downloadroutes", "deviceinfo", "printposonce", "printpos", "p", "printalt", "printspeed", "printheading", "printsat", "template*", "outfile*", "screenshot*", "printdefaulttemplate", "helptemplate", "nmealogfile*", "l", "uploadtracks", "uploadroutes", "uploadwaypoints", "infile*" }; CommandArguments args = null; try { args = new CommandArguments(arguments, valid_args); } catch (CommandArgumentException cae) { System.err.println("Invalid arguments: " + cae.getMessage()); printHelp(); return; } String filename = null; String serial_port_name = null; boolean gpsd = false; String gpsd_host = "localhost"; int gpsd_port = 2947; int serial_port_speed = -1; GPSDataProcessor gps_data_processor; String nmea_log_file = null; if (args.isSet("help") || (args.isSet("h"))) { printHelp(); return; } if (args.isSet("helptemplate")) { printHelpTemplate(); } if (args.isSet("printdefaulttemplate")) { System.out.println(DEFAULT_TEMPLATE); } if (args.isSet("device")) { serial_port_name = (String) args.getValue("device"); } else if (args.isSet("d")) { serial_port_name = (String) args.getValue("d"); } if (args.isSet("speed")) { serial_port_speed = ((Integer) args.getValue("speed")).intValue(); } else if (args.isSet("s")) { serial_port_speed = ((Integer) args.getValue("s")).intValue(); } if (args.isSet("file")) { filename = (String) args.getValue("file"); } else if (args.isSet("f")) { filename = (String) args.getValue("f"); } if (args.isSet("gpsd")) { gpsd = true; String gpsd_host_port = (String) args.getValue("gpsd"); if (gpsd_host_port != null && gpsd_host_port.length() > 0) { String[] params = gpsd_host_port.split(":"); gpsd_host = params[0]; if (params.length > 0) { gpsd_port = Integer.parseInt(params[1]); } } } if (args.isSet("garmin") || args.isSet("g")) { gps_data_processor = new GPSGarminDataProcessor(); serial_port_speed = 9600; if (filename != null) { System.err.println("ERROR: Cannot read garmin data from file, only serial port supported!"); return; } } else if (args.isSet("sirf") || args.isSet("i")) { gps_data_processor = new GPSSirfDataProcessor(); serial_port_speed = 19200; if (filename != null) { System.err.println("ERROR: Cannot read sirf data from file, only serial port supported!"); return; } } else { gps_data_processor = new GPSNmeaDataProcessor(); serial_port_speed = 4800; } if (args.isSet("nmealogfile") || (args.isSet("l"))) { if (args.isSet("nmealogfile")) nmea_log_file = args.getStringValue("nmealogfile"); else nmea_log_file = args.getStringValue("l"); } if (args.isSet("rawdata")) { gps_data_processor.addGPSRawDataListener(new GPSRawDataListener() { public void gpsRawDataReceived(char[] data, int offset, int length) { System.out.println("RAWLOG: " + new String(data, offset, length)); } }); } GPSDevice gps_device; Hashtable environment = new Hashtable(); if (filename != null) { environment.put(GPSFileDevice.PATH_NAME_KEY, filename); gps_device = new GPSFileDevice(); } else if (gpsd) { environment.put(GPSNetworkGpsdDevice.GPSD_HOST_KEY, gpsd_host); environment.put(GPSNetworkGpsdDevice.GPSD_PORT_KEY, new Integer(gpsd_port)); gps_device = new GPSNetworkGpsdDevice(); } else { if (serial_port_name != null) environment.put(GPSSerialDevice.PORT_NAME_KEY, serial_port_name); if (serial_port_speed > -1) environment.put(GPSSerialDevice.PORT_SPEED_KEY, new Integer(serial_port_speed)); gps_device = new GPSSerialDevice(); } try { gps_device.init(environment); gps_data_processor.setGPSDevice(gps_device); gps_data_processor.open(); gps_data_processor.addProgressListener(this); if ((nmea_log_file != null) && (nmea_log_file.length() > 0)) { gps_data_processor.addGPSRawDataListener(new GPSRawDataFileLogger(nmea_log_file)); } if (args.isSet("deviceinfo")) { System.out.println("GPSInfo:"); String[] infos = gps_data_processor.getGPSInfo(); for (int index = 0; index < infos.length; index++) { System.out.println(infos[index]); } } if (args.isSet("screenshot")) { FileOutputStream out = new FileOutputStream((String) args.getValue("screenshot")); BufferedImage image = gps_data_processor.getScreenShot(); ImageIO.write(image, "PNG", out); } boolean print_waypoints = args.isSet("downloadwaypoints"); boolean print_routes = args.isSet("downloadroutes"); boolean print_tracks = args.isSet("downloadtracks"); if (print_waypoints || print_routes || print_tracks) { VelocityContext context = new VelocityContext(); if (print_waypoints) { List waypoints = gps_data_processor.getWaypoints(); if (waypoints != null) context.put("waypoints", waypoints); else print_waypoints = false; } if (print_tracks) { List tracks = gps_data_processor.getTracks(); if (tracks != null) context.put("tracks", tracks); else print_tracks = false; } if (print_routes) { List routes = gps_data_processor.getRoutes(); if (routes != null) context.put("routes", routes); else print_routes = false; } context.put("printwaypoints", new Boolean(print_waypoints)); context.put("printtracks", new Boolean(print_tracks)); context.put("printroutes", new Boolean(print_routes)); Writer writer; Reader reader; if (args.isSet("template")) { String template_file = (String) args.getValue("template"); reader = new FileReader(template_file); } else { reader = new StringReader(DEFAULT_TEMPLATE); } if (args.isSet("outfile")) writer = new FileWriter((String) args.getValue("outfile")); else writer = new OutputStreamWriter(System.out); addDefaultValuesToContext(context); boolean result = printTemplate(context, reader, writer); } boolean read_waypoints = (args.isSet("uploadwaypoints") && args.isSet("infile")); boolean read_routes = (args.isSet("uploadroutes") && args.isSet("infile")); boolean read_tracks = (args.isSet("uploadtracks") && args.isSet("infile")); if (read_waypoints || read_routes || read_tracks) { ReadGPX reader = new ReadGPX(); String in_file = (String) args.getValue("infile"); reader.parseFile(in_file); if (read_waypoints) gps_data_processor.setWaypoints(reader.getWaypoints()); if (read_routes) gps_data_processor.setRoutes(reader.getRoutes()); if (read_tracks) gps_data_processor.setTracks(reader.getTracks()); } if (args.isSet("printposonce")) { GPSPosition pos = gps_data_processor.getGPSPosition(); System.out.println("Current Position: " + pos); } if (args.isSet("printpos") || args.isSet("p")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.LOCATION, this); } if (args.isSet("printalt")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.ALTITUDE, this); } if (args.isSet("printspeed")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.SPEED, this); } if (args.isSet("printheading")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.HEADING, this); } if (args.isSet("printsat")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.NUMBER_SATELLITES, this); gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.SATELLITE_INFO, this); } if (args.isSet("printpos") || args.isSet("p") || args.isSet("printalt") || args.isSet("printsat") || args.isSet("printspeed") || args.isSet("printheading")) { gps_data_processor.startSendPositionPeriodically(1000L); try { System.in.read(); } catch (IOException ignore) { } } gps_data_processor.close(); } catch (GPSException e) { e.printStackTrace(); } catch (FileNotFoundException fnfe) { System.err.println("ERROR: File not found: " + fnfe.getMessage()); } catch (IOException ioe) { System.err.println("ERROR: I/O Error: " + ioe.getMessage()); } }
00
Code Sample 1: public ChatClient registerPlayer(int playerId, String playerLogin) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(playerLogin.getBytes("UTF-8"), 0, playerLogin.length()); byte[] accountToken = md.digest(); byte[] token = generateToken(accountToken); ChatClient chatClient = new ChatClient(playerId, token); players.put(playerId, chatClient); return chatClient; } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
11
Code Sample 1: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } } Code Sample 2: public File createFileFromClasspathResource(String resourceUrl) throws IOException { File fichierTest = File.createTempFile("xmlFieldTestFile", ""); FileOutputStream fos = new FileOutputStream(fichierTest); InputStream is = XmlFieldDomSelectorTest.class.getResourceAsStream(resourceUrl); IOUtils.copy(is, fos); is.close(); fos.close(); return fichierTest; }
11
Code Sample 1: public static boolean encodeFileToFile(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.ENCODE); 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; } Code Sample 2: 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; }
11
Code Sample 1: public void run() { if (getCommand() == null) throw new IllegalArgumentException("Given command is null!"); if (getSocketProvider() == null) throw new IllegalArgumentException("Given connection is not open!"); if (getCommand() instanceof ListCommand) { try { setReply(ReplyWorker.readReply(getSocketProvider(), true)); setStatus(ReplyWorker.FINISHED); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } return; } else if (getCommand() instanceof RetrieveCommand) { RetrieveCommand retrieveCommand = (RetrieveCommand) getCommand(); if (retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_I || retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Download file: " + retrieveCommand.getFromFile().toString()); FileOutputStream out = null; FileChannel channel = null; if (getDownloadMethod() == RetrieveCommand.FILE_BASED) { out = new FileOutputStream(retrieveCommand.getToFile().getFile()); channel = out.getChannel(); if (retrieveCommand.getResumePosition() != -1) { try { channel.position(retrieveCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } int amount; try { while ((amount = getSocketProvider().read(buffer)) != -1) { if (amount == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); setStatus(ReplyWorker.FINISHED); if (channel != null) channel.close(); if (this.outputPipe != null) this.outputPipe.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for download!"); return; } else if (getCommand() instanceof StoreCommand) { StoreCommand storeCommand = (StoreCommand) getCommand(); if (storeCommand.getToFile().getTransferType().intern() == Command.TYPE_I || storeCommand.getToFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Upload file: " + storeCommand.getFromFile()); InputStream in = storeCommand.getStream(); int amount; int socketWrite; int socketAmount = 0; if (in instanceof FileInputStream) { FileChannel channel = ((FileInputStream) in).getChannel(); if (storeCommand.getResumePosition() != -1) { try { channel.position(storeCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } try { while ((amount = channel.read(buffer)) != -1) { buffer.flip(); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount += socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); channel.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } else { try { while ((amount = in.read(buffer.array())) != -1) { buffer.flip(); buffer.limit(amount); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount = socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); in.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { in.close(); getSocketProvider().close(); } catch (Exception e) { } } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for upload!"); } else throw new IllegalArgumentException("Given command is not supported!"); } Code Sample 2: @Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } }
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 cleanup(long timeout) throws PersisterException { long threshold = System.currentTimeMillis() - timeout; Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("delete from " + _table_name + " where " + _ts_col + " < ?"); ps.setLong(1, threshold); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to cleanup timed out objects: ", th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
11
Code Sample 1: public void readBooklist(String filename) { Reader input = null; try { if (filename.startsWith("http:")) { URL url = new URL(filename); URLConnection conn = url.openConnection(); input = new InputStreamReader(conn.getInputStream()); } else { String fileNameAll = filename; try { fileNameAll = new File(filename).getCanonicalPath(); } catch (IOException e) { fileNameAll = new File(filename).getAbsolutePath(); } input = new FileReader(new File(fileNameAll)); } BufferedReader reader = new BufferedReader(input); String line; Date today = new Date(); while ((line = reader.readLine()) != null) { if (shuttingDown) break; String fields[] = line.split("\\|"); Map<String, String> valuesToAdd = new LinkedHashMap<String, String>(); valuesToAdd.put("fund_code_facet", fields[11]); valuesToAdd.put("date_received_facet", fields[0]); DateFormat format = new SimpleDateFormat("yyyyMMdd"); Date dateReceived = format.parse(fields[0], new ParsePosition(0)); if (dateReceived.after(today)) continue; String docID = "u" + fields[9]; try { Map<String, Object> docMap = getDocumentMap(docID); if (docMap != null) { addNewDataToRecord(docMap, valuesToAdd); documentCache.put(docID, docMap); if (doUpdate && docMap != null && docMap.size() != 0) { update(docMap); } } } catch (SolrMarcIndexerException e) { if (e.getLevel() == SolrMarcIndexerException.IGNORE) { logger.error("Indexing routine says record " + docID + " should be ignored"); } else if (e.getLevel() == SolrMarcIndexerException.DELETE) { logger.error("Indexing routine says record " + docID + " should be deleted"); } if (e.getLevel() == SolrMarcIndexerException.EXIT) { logger.error("Indexing routine says processing should be terminated by record " + docID); break; } } } } catch (FileNotFoundException e) { logger.info(e.getMessage()); logger.error(e.getCause()); } catch (IOException e) { logger.info(e.getMessage()); logger.error(e.getCause()); } } Code Sample 2: private void loadDateFormats() { String fileToLocate = "/" + FILENAME_DATE_FMT; URL url = getClass().getClassLoader().getResource(fileToLocate); if (url == null) { return; } List<String> lines; try { lines = IOUtils.readLines(url.openStream()); } catch (IOException e) { throw new ConfigurationException("Problem loading file " + fileToLocate, e); } for (String line : lines) { if (line.startsWith("#") || StringUtils.isBlank(line)) { continue; } String[] parts = StringUtils.split(line, "="); addFormat(parts[0], new SimpleDateFormat(parts[1])); } }
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: public void xtestFile2() throws Exception { InputStream inputStream = new FileInputStream(IOTest.FILE); OutputStream outputStream = new FileOutputStream("C:/Temp/testFile2.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
00
Code Sample 1: public String fetch(final String address) throws EncoderException { final String escapedAddress = new URLCodec().encode(address); final String requestUrl = GeoCodeFetch.urlXmlPath + "&" + "address=" + escapedAddress; this.log.debug("requestUrl: {}", requestUrl); try { final StringBuffer sb = new StringBuffer(); final URL url = new URL(requestUrl); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { this.log.debug("line: {}", line); sb.append(line); } reader.close(); return (sb.toString()); } catch (final MalformedURLException ex) { this.log.error(ExceptionUtils.getStackTrace(ex)); } catch (final IOException ex) { this.log.error(ExceptionUtils.getStackTrace(ex)); } return (""); } Code Sample 2: public static synchronized String hash(String plaintext) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { return null; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
00
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 static String encrypt(String algorithm, String str) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(str.getBytes()); StringBuffer sb = new StringBuffer(); byte[] bytes = md.digest(); for (int i = 0; i < bytes.length; i++) { int b = bytes[i] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } return sb.toString(); } catch (Exception e) { return ""; } }
11
Code Sample 1: public void test() throws Exception { StringDocument doc = new StringDocument("Test", "UTF-8"); doc.open(); try { assertEquals("UTF-8", doc.getCharacterEncoding()); assertEquals("Test", doc.getText()); InputStream input = doc.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { writer.close(); } assertEquals("Test", writer.toString()); } finally { doc.close(); } } Code Sample 2: @Action(value = "ajaxFileUploads", results = { }) public void ajaxFileUploads() throws IOException { String extName = ""; String newFilename = ""; String nowTimeStr = ""; String realpath = ""; if (Validate.StrNotNull(this.getImgdirpath())) { realpath = "Uploads/" + this.getImgdirpath() + "/"; } else { realpath = this.isexistdir(); } SimpleDateFormat sDateFormat; Random r = new Random(); String savePath = ServletActionContext.getServletContext().getRealPath(""); savePath = savePath + realpath; HttpServletResponse response = ServletActionContext.getResponse(); int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000; sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); nowTimeStr = sDateFormat.format(new Date()); String filename = request.getHeader("X-File-Name"); if (filename.lastIndexOf(".") >= 0) { extName = filename.substring(filename.lastIndexOf(".")); } newFilename = nowTimeStr + rannum + extName; PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log.debug(ImgTAction.class.getName() + "has thrown an exception:" + ex.getMessage()); } try { is = request.getInputStream(); fos = new FileOutputStream(new File(savePath + newFilename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success:'" + realpath + newFilename + "'}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { this.setImgdirpath(null); fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
11
Code Sample 1: public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, out); writer.setPdfVersion(PdfWriter.VERSION_1_3); writer.setFullCompression(); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STRENGTH128BITS, password, null, securityType); } final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } else if (base_url != null) { document.addTitle(base_url); } final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } else { document.addCreator(IHtmlToPdfTransformer.VERSION); } final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.addProducer(sproducer); } else { document.addProducer(IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer); } document.open(); } PdfImportedPage page; for (int j = 0; j < n; ) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } } document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext(); ) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i).replaceAll("<pagecount>", "" + n); final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } else { reader = new PdfReader(tmp2.getAbsolutePath()); } final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STRENGTH128BITS, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } if (reason != null) { sap.setReason(reason); } if (location != null) { sap.setLocation(location); } stp.close(); oldOut.flush(); } } catch (final Exception e) { throw new CConvertException("ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } finally { try { tmp.delete(); } catch (final Exception ignore) { } try { tmp2.delete(); } catch (final Exception ignore) { } } } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { if (destination.getParentFile() != null && !destination.getParentFile().exists()) { destination.getParentFile().mkdirs(); } if (destination.exists() && !destination.canWrite()) { String message = "Unable to open file " + destination + " for writing."; throw new IOException(message); } InputStream input = source.openStream(); try { FileOutputStream output = new FileOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
00
Code Sample 1: public void copieFichier(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } Code Sample 2: public static Document getXHTMLDocument(URL _url) throws IOException { final Tidy tidy = new Tidy(); tidy.setQuiet(true); tidy.setShowWarnings(false); tidy.setXmlOut(true); final BufferedInputStream input_stream = new BufferedInputStream(_url.openStream()); return tidy.parseDOM(input_stream, null); }
00
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, 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 { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public void insertComponent() throws SQLException { Connection connection = null; PreparedStatement ps = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = (Connection) DriverManager.getConnection(this.jdbcURL); connection.setAutoCommit(false); String query = "INSERT INTO components(name,rate,quantity, description) VALUES(?,?,?,?)"; ps = (PreparedStatement) connection.prepareStatement(query); ps.setString(1, this.name); ps.setDouble(2, this.rate); ps.setInt(3, this.quantity); ps.setString(4, this.description); ps.executeUpdate(); connection.commit(); } catch (Exception ex) { connection.rollback(); } finally { try { connection.close(); } catch (Exception ex) { } try { ps.close(); } catch (Exception ex) { } } }
00
Code Sample 1: public static void main(String[] args) throws Exception { String layerName = args[0]; String layerDescription = args[1]; String units = args[2]; String rawDataDirPath = args[3]; String processDirPath = args[4]; String divaDirPath = args[5]; String legendDirPath = args[6]; String geotiffDirPath = args[7]; String dbJdbcUrl = args[8]; String dbUsername = args[9]; String dbPassword = args[10]; String geoserverUsername = args[11]; String geoserverPassword = args[12]; File rawDataDir = new File(rawDataDirPath); if (!rawDataDir.exists() || !rawDataDir.isDirectory()) { throw new RuntimeException("Supplied raw data directory " + rawDataDirPath + " does not exist or is not a directory"); } File processDir = new File(processDirPath); if (!processDir.exists() || !processDir.isDirectory()) { throw new RuntimeException("Supplied process directory " + processDirPath + " does not exist or is not a directory"); } File divaDir = new File(divaDirPath); if (!divaDir.exists() || !divaDir.isDirectory()) { throw new RuntimeException("Supplied diva directory " + divaDirPath + " does not exist or is not a directory"); } File legendDir = new File(legendDirPath); if (!legendDir.exists() || !legendDir.isDirectory()) { throw new RuntimeException("Supplied legend directory " + legendDirPath + " does not exist or is not a directory"); } File geotiffDir = new File(geotiffDirPath); if (!geotiffDir.exists() || !geotiffDir.isDirectory()) { throw new RuntimeException("Supplied geotiff directory " + geotiffDirPath + " does not exist or is not a directory"); } System.out.println("Beginning environmetal load"); System.out.println("Connecting to database"); Class.forName("org.postgresql.Driver"); Properties props = new Properties(); props.setProperty("user", dbUsername); props.setProperty("password", dbPassword); Connection conn = DriverManager.getConnection(dbJdbcUrl, props); conn.setAutoCommit(false); try { File layerProcessDir = new File(processDir, layerName); layerProcessDir.mkdir(); System.out.println("Running gdalwarp"); File hdrFile = new File(rawDataDir, "hdr.adf"); if (!hdrFile.exists()) { throw new RuntimeException("Could not find hdr.adf in " + rawDataDirPath); } File bilFile = new File(layerProcessDir, layerName + ".bil"); Process procGdalWarp = Runtime.getRuntime().exec(new String[] { "gdalwarp", "-of", "EHdr", "-ot", "Float32", hdrFile.getAbsolutePath(), bilFile.getAbsolutePath() }); int gdalWarpReturnVal = procGdalWarp.waitFor(); if (gdalWarpReturnVal != 0) { String gdalWarpErrorOutput = IOUtils.toString(procGdalWarp.getErrorStream()); throw new RuntimeException("gdalwarp failed: " + gdalWarpErrorOutput); } System.out.println("Running Bil2diva"); boolean bil2DivaSuccess = Bil2diva.bil2diva(layerProcessDir.getAbsolutePath() + File.separator + layerName, divaDir.getAbsolutePath() + File.separator + layerName, units); if (!bil2DivaSuccess) { throw new RuntimeException("Bil2diva Failed"); } System.out.println("Running GridLegend"); boolean gridLegendSuccess = GridLegend.generateGridLegend(divaDir.getAbsolutePath() + File.separator + layerName, legendDir.getAbsolutePath() + File.separator + layerName, 1, false); if (!gridLegendSuccess) { throw new RuntimeException("GridLegend Failed"); } System.out.println("Running gdal_translate"); File geotiffFile = new File(geotiffDir, layerName + ".tif"); Process procGdalTranslate = Runtime.getRuntime().exec(new String[] { "gdal_translate", "-of", "GTiff", bilFile.getAbsolutePath(), geotiffFile.getAbsolutePath() }); int gdalTranslateReturnVal = procGdalTranslate.waitFor(); if (gdalTranslateReturnVal != 0) { String gdalTranslateErrorOutput = IOUtils.toString(procGdalTranslate.getErrorStream()); throw new RuntimeException("gdal_translate failed: " + gdalTranslateErrorOutput); } System.out.println("Extracting extents and min/max environmental value from diva .grd file"); File divaGrd = new File(divaDir, layerName + ".grd"); if (!divaGrd.exists()) { throw new RuntimeException("Could not locate diva .grd file: " + divaGrd.toString()); } String strDivaGrd = FileUtils.readFileToString(divaGrd); float minValue = Float.parseFloat(matchPattern(strDivaGrd, "^MinValue=(.+)$")); float maxValue = Float.parseFloat(matchPattern(strDivaGrd, "^MaxValue=(.+)$")); float minLatitude = Float.parseFloat(matchPattern(strDivaGrd, "^MinY=(.+)$")); float maxLatitude = Float.parseFloat(matchPattern(strDivaGrd, "^MaxY=(.+)$")); float minLongitude = Float.parseFloat(matchPattern(strDivaGrd, "^MinX=(.+)$")); float maxLongitude = Float.parseFloat(matchPattern(strDivaGrd, "^MaxX=(.+)$")); System.out.println("Generating ID for new layer..."); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT MAX(id) from layers"); rs.next(); int id = 1; String idAsString = rs.getString(1); if (idAsString != null) { id = Integer.parseInt(idAsString); id++; } String displayPath = MessageFormat.format(GEOSERVER_QUERY_TEMPLATE, layerName); System.out.println("Creating layers table entry..."); PreparedStatement createLayersStatement = createLayersInsert(conn, id, layerDescription, divaDir.getAbsolutePath(), layerName, displayPath, minLatitude, minLongitude, maxLatitude, maxLongitude, minValue, maxValue, units); createLayersStatement.execute(); System.out.println("Creating fields table entry..."); PreparedStatement createFieldsStatement = createFieldsInsert(conn, id, layerName, layerDescription); createFieldsStatement.execute(); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8082), new UsernamePasswordCredentials(geoserverUsername, geoserverPassword)); System.out.println("Creating layer in geoserver..."); HttpPut createLayerPut = new HttpPut(String.format("http://localhost:8082/geoserver/rest/workspaces/ALA/coveragestores/%s/external.geotiff", layerName)); createLayerPut.setHeader("Content-type", "text/plain"); createLayerPut.setEntity(new StringEntity(geotiffFile.toURI().toURL().toString())); HttpResponse createLayerResponse = httpClient.execute(createLayerPut); if (createLayerResponse.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Error creating layer in geoserver: " + createLayerResponse.toString()); } EntityUtils.consume(createLayerResponse.getEntity()); System.out.println("Creating style in geoserver"); HttpPost createStylePost = new HttpPost("http://localhost:8082/geoserver/rest/styles"); createStylePost.setHeader("Content-type", "text/xml"); createStylePost.setEntity(new StringEntity(String.format("<style><name>%s_style</name><filename>%s.sld</filename></style>", layerName, layerName))); HttpResponse createStyleResponse = httpClient.execute(createLayerPut); if (createStyleResponse.getStatusLine().getStatusCode() != 201) { throw new RuntimeException("Error creating style in geoserver: " + createStyleResponse.toString()); } EntityUtils.consume(createStyleResponse.getEntity()); System.out.println("Uploading sld file to geoserver"); File sldFile = new File(legendDir, layerName + ".sld"); String sldData = FileUtils.readFileToString(sldFile); HttpPut uploadSldPut = new HttpPut(String.format("http://localhost:8082/geoserver/rest/styles/%s_style", layerName)); uploadSldPut.setHeader("Content-type", "application/vnd.ogc.sld+xml"); uploadSldPut.setEntity(new StringEntity(sldData)); HttpResponse uploadSldResponse = httpClient.execute(uploadSldPut); if (uploadSldResponse.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Error uploading sld file geoserver: " + uploadSldResponse.toString()); } EntityUtils.consume(uploadSldResponse.getEntity()); System.out.println("Setting default style in geoserver"); HttpPut setDefaultStylePut = new HttpPut(String.format("http://localhost:8082/geoserver/rest/layers/ALA:%s", layerName)); setDefaultStylePut.setHeader("Content-type", "text/xml"); setDefaultStylePut.setEntity(new StringEntity(String.format("<layer><enabled>true</enabled><defaultStyle><name>%s_style</name></defaultStyle></layer>", layerName))); HttpResponse setDefaultStyleResponse = httpClient.execute(createLayerPut); if (setDefaultStyleResponse.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Setting default style in geoserver: " + setDefaultStyleResponse.toString()); } EntityUtils.consume(setDefaultStyleResponse.getEntity()); conn.commit(); } catch (Exception ex) { ex.printStackTrace(); conn.rollback(); } } Code Sample 2: public void setRemoteConfig(String s) { try { HashMap<String, String> map = new HashMap<String, String>(); URL url = new URL(s); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.startsWith("#")) continue; String[] split = line.split("="); if (split.length >= 2) { map.put(split[0], split[1]); } } MethodAndFieldSetter.setMethodsAndFields(this, map); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); } Code Sample 2: public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
11
Code Sample 1: public File getFile(String file) { DirProperties dp; List files = new ArrayList(); for (int i = 0; i < locs.size(); i++) { dp = (DirProperties) locs.get(i); if (dp.isReadable()) { File g = new File(dp.getLocation() + slash() + file); if (g.exists()) files.add(g); } } if (files.size() == 0) { throw new UnsupportedOperationException("at least one DirProperty should get 'read=true'"); } else if (files.size() == 1) { return (File) files.get(0); } else { File fromFile = (File) files.get(files.size() - 2); File toFile = (File) files.get(files.size() - 1); byte reading[] = new byte[2024]; try { FileInputStream stream = new FileInputStream(fromFile); FileOutputStream outStr = new FileOutputStream(toFile); while (stream.read(reading) != -1) { outStr.write(reading); } } catch (FileNotFoundException ex) { getLogger().severe("FileNotFound: while copying from " + fromFile + " to " + toFile); } catch (IOException ex) { getLogger().severe("IOException: while copying from " + fromFile + " to " + toFile); } return toFile; } } Code Sample 2: public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); }
00
Code Sample 1: public static boolean encodeFileToFile(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.ENCODE); 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; } Code Sample 2: private String checkForUpdate() { InputStream is = null; try { URL url = new URL(CHECK_UPDATES_URL); try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "TinyLaF"); Object content = conn.getContent(); if (!(content instanceof InputStream)) { return "An exception occured while checking for updates." + "\n\nException was: Content is no InputStream"; } is = (InputStream) content; } catch (IOException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } } catch (MalformedURLException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } try { BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buff = new StringBuffer(); String line; while ((line = in.readLine()) != null) { buff.append(line); } in.close(); return buff.toString(); } catch (IOException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } }
00
Code Sample 1: private void triggerBuild(Properties props, String project, int rev) throws IOException { boolean doBld = Boolean.parseBoolean(props.getProperty(project + ".bld")); String url = props.getProperty(project + ".url"); if (!doBld || project == null || project.length() == 0) { System.out.println("BuildLauncher: Not configured to build '" + project + "'"); return; } else if (url == null) { throw new IOException("Tried to launch build for project '" + project + "' but " + project + ".url property is not defined!"); } SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); System.out.println(fmt.format(new Date()) + ": Triggering a build via: " + url); BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while (r.readLine() != null) ; System.out.println(fmt.format(new Date()) + ": Build triggered!"); LATEST_BUILD.put(project, rev); r.close(); System.out.println(fmt.format(new Date()) + ": triggerBuild() done!"); } Code Sample 2: @Override public String encryptString(String passphrase, String message) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes("UTF-8")); byte digest[] = md.digest(); String digestString = base64encode(digest); System.out.println(digestString); SecureRandom sr = new SecureRandom(digestString.getBytes()); KeyGenerator kGen = KeyGenerator.getInstance("AES"); kGen.init(128, sr); Key key = kGen.generateKey(); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] bIn = cipher.doFinal(message.getBytes("UTF-8")); String base64Encoded = base64encode(bIn); return base64Encoded; }
00
Code Sample 1: public static RecordResponse loadRecord(RecordRequest recordRequest) { RecordResponse recordResponse = new RecordResponse(); try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(recordRequest.isContact() ? URL_RECORD_CONTACT : URL_RECORD_COMPANY); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6); nameValuePairs.add(new BasicNameValuePair("format", "xml")); nameValuePairs.add(new BasicNameValuePair("token", recordRequest.getToken())); nameValuePairs.add(new BasicNameValuePair("id", recordRequest.getId())); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); String line = EntityUtils.toString(response.getEntity()); Document document = XMLfunctions.XMLfromString(line); NodeList nodes = document.getElementsByTagName("response"); Element e = (Element) nodes.item(0); String Name__Last__First_ = XMLfunctions.getValue(e, recordRequest.isContact() ? "Name__Last__First_" : "Name"); String phone = ""; if (!recordRequest.isContact()) phone = XMLfunctions.getValue(e, "Phone"); String Email1 = XMLfunctions.getValue(e, recordRequest.isContact() ? "Personal_Email" : "Email"); String Home_Fax = XMLfunctions.getValue(e, recordRequest.isContact() ? "Home_Fax" : "Fax1"); String Address1 = XMLfunctions.getValue(e, "Address1"); String Address2 = XMLfunctions.getValue(e, "Address2"); String City = XMLfunctions.getValue(e, "City"); String State = XMLfunctions.getValue(e, "State"); String Zip = XMLfunctions.getValue(e, "Zip"); String Country = XMLfunctions.getValue(e, "Country"); String Profile = XMLfunctions.getValue(e, "Profile"); String success = XMLfunctions.getValue(e, "success"); String error = XMLfunctions.getValue(e, "error"); recordResponse.setName(Name__Last__First_); recordResponse.setPhone(phone); recordResponse.setEmail(Email1); recordResponse.setHomeFax(Home_Fax); recordResponse.setAddress1(Address1); recordResponse.setAddress2(Address2); recordResponse.setCity(City); recordResponse.setState(State); recordResponse.setZip(Zip); recordResponse.setProfile(Profile); recordResponse.setCountry(Country); recordResponse.setSuccess(success); recordResponse.setError(error); } catch (Exception e) { } return recordResponse; } Code Sample 2: protected static void writeFileToStream(FileWrapper file, String filename, ZipOutputStream zipStream) throws CausedIOException, IOException { InputStream in; try { in = file.getInputStream(); } catch (Exception e) { throw new CausedIOException("Could not obtain InputStream for " + filename, e); } try { IOUtils.copy(in, zipStream); } finally { IOUtils.closeQuietly(in); } }
00
Code Sample 1: public void addEntry(InputStream jis, JarEntry entry) throws IOException, URISyntaxException { File target = new File(this.target.getPath() + entry.getName()).getAbsoluteFile(); if (!target.exists()) { target.createNewFile(); } if ((new File(this.source.toURI())).isDirectory()) { File sourceEntry = new File(this.source.getPath() + entry.getName()); FileInputStream fis = new FileInputStream(sourceEntry); byte[] classBytes = new byte[fis.available()]; fis.read(classBytes); (new FileOutputStream(target)).write(classBytes); } else { readwriteStreams(jis, (new FileOutputStream(target))); } } Code Sample 2: public synchronized int executeCommand(Vector<String> pvStatement) throws Exception { int ret = 0, i = 0; Statement stmt = null; String temp = ""; try { oConexion.setAutoCommit(false); stmt = oConexion.createStatement(); for (i = 0; i < pvStatement.size(); i++) { temp = (String) pvStatement.elementAt(i); ret += stmt.executeUpdate(temp); } oConexion.commit(); } catch (SQLException e) { oConexion.rollback(); throw e; } finally { stmt.close(); stmt = null; } return ret; }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { FileChannel from = new FileInputStream(src).getChannel(); FileChannel to = new FileOutputStream(dst).getChannel(); from.transferTo(0, src.length(), to); from.close(); to.close(); } Code Sample 2: public static boolean encodeFileToFile(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.ENCODE); 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; }
00
Code Sample 1: @Override public void run() { try { status = UploadStatus.INITIALISING; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.filedropper.com"); httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2 GTBDFff GTB7.0"); HttpResponse httpresponse = httpclient.execute(httpget); httpresponse.getEntity().consumeContent(); httppost = new HttpPost("http://www.filedropper.com/index.php?xml=true"); httppost.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2 GTBDFff GTB7.0"); MultipartEntity requestEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); requestEntity.addPart("file", new MonitoredFileBody(file, uploadProgress)); requestEntity.addPart("Upload", new StringBody("Submit Query")); httppost.setEntity(requestEntity); status = UploadStatus.UPLOADING; httpresponse = httpclient.execute(httppost); String strResponse = EntityUtils.toString(httpresponse.getEntity()); status = UploadStatus.GETTINGLINK; downURL = "http://www.filedropper.com/" + strResponse.substring(strResponse.lastIndexOf("=") + 1); NULogger.getLogger().info(downURL); uploadFinished(); } catch (Exception ex) { ex.printStackTrace(); NULogger.getLogger().severe(ex.toString()); uploadFailed(); } } Code Sample 2: public byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; }
11
Code Sample 1: private static boolean verifyAppId(String appid) { try { String urlstr = "http://" + appid + ".appspot.com"; URL url = new URL(urlstr); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buf.append(line); } reader.close(); return buf.toString().contains("snova"); } catch (Exception e) { } return false; } Code Sample 2: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getroutes/1"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetClient_", "<jsonobject>\n" + json.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray = json.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringAgent = nameArray.getJSONObject(i).getString("Agent"); tempStringClient = nameArray.getJSONObject(i).getString("Client"); tempStringRoute = nameArray.getJSONObject(i).getString("Route"); tempStringZone = nameArray.getJSONObject(i).getString("Zone"); Log.i("_GetClient_", "<Agent" + i + ">" + tempStringAgent + "</Agent" + i + ">\n"); Log.i("_GetClient_", "<Client" + i + ">" + tempStringClient + "</Client" + i + ">\n"); Log.i("_GetClient_", "<Route" + i + ">" + tempStringRoute + "</Route" + i + ">\n"); Log.i("_GetClient_", "<Zone" + i + ">" + tempStringZone + "</Zone" + i + ">\n"); tempString = nameArray.getJSONObject(i).getString("Client") + "\n" + nameArray.getJSONObject(i).getString("Route") + "\n" + nameArray.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, orderTimeStamps)); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.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: @Override public void run() { try { if (LOG.isDebugEnabled()) { LOG.debug("Backupthread started"); } if (_file.exists()) { _file.delete(); } final ZipOutputStream zOut = new ZipOutputStream(new FileOutputStream(_file)); zOut.setLevel(9); final File xmlFile = File.createTempFile("mp3db", ".xml"); final OutputStream ost = new FileOutputStream(xmlFile); final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(ost, "UTF-8"); writer.writeStartDocument("UTF-8", "1.0"); writer.writeCharacters("\n"); writer.writeStartElement("mp3db"); writer.writeAttribute("version", Integer.toString(Main.ENGINEVERSION)); final MediafileDAO mfDAO = new MediafileDAO(); final AlbumDAO aDAO = new AlbumDAO(); final CdDAO cdDAO = new CdDAO(); final CoveritemDAO ciDAO = new CoveritemDAO(); int itemCount = 0; try { itemCount += mfDAO.getCount(); itemCount += aDAO.getCount(); itemCount += cdDAO.getCount(); itemCount += ciDAO.getCount(); fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, itemCount)); } catch (final Exception e) { LOG.error("Error getting size", e); fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, -1)); } int cdCounter = 0; int mediafileCounter = 0; int albumCounter = 0; int coveritemCounter = 0; int counter = 0; final List<CdIf> data = cdDAO.getCdsOrderById(); if (data.size() > 0) { final Map<Integer, Integer> albums = new HashMap<Integer, Integer>(); final Iterator<CdIf> it = data.iterator(); while (it.hasNext() && !_break) { final CdIf cd = it.next(); final Integer cdId = Integer.valueOf(cdCounter++); writer.writeStartElement(TypeConstants.XML_CD); exportCd(writer, cd, cdId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); final List<MediafileIf> files = cd.getMediafiles(); final Iterator<MediafileIf> mfit = files.iterator(); MediafileIf mf; while (mfit.hasNext() && !_break) { mf = mfit.next(); final Integer mfId = Integer.valueOf(mediafileCounter++); writer.writeStartElement(TypeConstants.XML_MEDIAFILE); exportMediafile(writer, mf, mfId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); final AlbumIf a = mf.getAlbum(); if (a != null) { Integer inte; if (albums.containsKey(a.getAid())) { inte = albums.get(a.getAid()); writeLink(writer, TypeConstants.XML_ALBUM, inte); } else { inte = Integer.valueOf(albumCounter++); writer.writeStartElement(TypeConstants.XML_ALBUM); exportAlbum(writer, a, inte); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); albums.put(a.getAid(), inte); if (a.hasCoveritems() && !_break) { final List<CoveritemIf> covers = a.getCoveritems(); final Iterator<CoveritemIf> coit = covers.iterator(); while (coit.hasNext() && !_break) { final Integer coveritemId = Integer.valueOf(coveritemCounter++); exportCoveritem(writer, zOut, coit.next(), coveritemId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); } } writer.writeEndElement(); } GenericDAO.getEntityManager().close(); } writer.writeEndElement(); } writer.writeEndElement(); writer.flush(); it.remove(); GenericDAO.getEntityManager().close(); } } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); ost.flush(); ost.close(); if (_break) { zOut.close(); _file.delete(); } else { zOut.putNextEntry(new ZipEntry("mp3.xml")); final InputStream xmlIn = FileUtils.openInputStream(xmlFile); IOUtils.copy(xmlIn, zOut); xmlIn.close(); zOut.close(); } xmlFile.delete(); fireStatusEvent(new StatusEvent(this, StatusEventType.FINISH)); } catch (final Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Error backup database", e); } fireStatusEvent(new StatusEvent(this, e, "")); _messenger.fireMessageEvent(new MessageEvent(this, "ERROR", MessageEventTypeEnum.ERROR, GuiStrings.getInstance().getString("error.backup"), e)); } } Code Sample 2: public static void copyFile4(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); }
11
Code Sample 1: public void copyFile(File in, File out) throws Exception { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } Code Sample 2: @Override public void run() { try { IOUtils.copy(_is, processOutStr); } catch (final IOException ioe) { proc.destroy(); } finally { IOUtils.closeQuietly(_is); IOUtils.closeQuietly(processOutStr); } }
11
Code Sample 1: @SuppressWarnings("finally") private void decompress(final File src) throws IOException { final String srcPath = src.getPath(); checkSourceFile(src); final boolean test = this.switches.contains(Switch.test); final File dst; if (test) dst = File.createTempFile("jaxlib-bzip", null); else { if (srcPath.endsWith(".bz2")) dst = new File(srcPath.substring(0, srcPath.length() - 4)); else { this.log.println("WARNING: Can't guess original name, using extension \".out\":").println(srcPath); dst = new File(srcPath + ".out"); } } if (!checkDestFile(dst)) return; final boolean showProgress = this.switches.contains(Switch.showProgress); BZip2InputStream in = null; FileOutputStream out = null; FileChannel outChannel = null; FileLock inLock = null; FileLock outLock = null; try { final FileInputStream in0 = new FileInputStream(src); final FileChannel inChannel = in0.getChannel(); final long inSize = inChannel.size(); inLock = inChannel.tryLock(0, inSize, true); if (inLock == null) throw error("source file locked by another process: " + src); in = new BZip2InputStream(new BufferedXInputStream(in0, 8192)); out = new FileOutputStream(dst); outChannel = out.getChannel(); outLock = outChannel.tryLock(); if (outLock == null) throw error("destination file locked by another process: " + dst); if (showProgress || this.verbose) { this.log.print("source: " + src).print(": size=").println(inSize); this.log.println("target: " + dst); } long pos = 0; int progress = 0; final long maxStep = showProgress ? Math.max(8192, inSize / MAX_PROGRESS) : Integer.MAX_VALUE; while (true) { final long step = outChannel.transferFrom(in, pos, maxStep); if (step <= 0) { final long a = inChannel.size(); if (a != inSize) throw error("file " + src + " has been modified concurrently by another process"); if (inChannel.position() >= inSize) { if (showProgress) { for (int i = progress; i < MAX_PROGRESS; i++) this.log.print('#'); this.log.println(" done"); } break; } } else { pos += step; if (showProgress) { final double p = (double) inChannel.position() / (double) inSize; final int newProgress = (int) (MAX_PROGRESS * p); for (int i = progress; i < newProgress; i++) this.log.print('#'); progress = newProgress; } } } final long outSize = outChannel.size(); in.close(); out.close(); if (this.verbose) { final double ratio = (outSize == 0) ? (inSize * 100) : ((double) inSize / (double) outSize); this.log.print("compressed size: ").print(inSize) .print("; decompressed size: ").print(outSize) .print("; compression ratio: ").print(ratio).println('%'); } if (!test && !this.switches.contains(Switch.keep)) { if (!src.delete()) throw error("unable to delete sourcefile: " + src); } if (test && !dst.delete()) throw error("unable to delete testfile: " + dst); } catch (final IOException ex) { IO.tryClose(in); IO.tryClose(out); IO.tryRelease(inLock); IO.tryRelease(outLock); try { this.log.println(); } finally { throw ex; } } } Code Sample 2: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/zip"); response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip"); try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("server.zip"); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; java.util.Properties props = new java.util.Properties(); props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt")); String jbossHomePath = props.getProperty("JBOSS_HOME"); jbossHomePath = jbossHomePath.replaceAll("deploy", "log"); FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log")); origin = new BufferedInputStream(fis, BUFFER); ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log"); zipOut.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } origin.close(); zipOut.closeEntry(); java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip")); java.nio.channels.FileChannel fc1 = fis1.getChannel(); int length1 = (int) fc1.size(); byte buffer[] = new byte[length1]; System.out.println("size of zip file = " + length1); fis1.read(buffer); OutputStream out1 = response.getOutputStream(); out1.write(buffer); fis1.close(); out1.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private void addEMInformation() { try { long emDate = System.currentTimeMillis(); if (_local == true) { File emFile = new File("emprotz.dat"); if (!emFile.exists()) { return; } emDate = emFile.lastModified(); } if (emDate > this._emFileDate) { this._emFileDate = emDate; this._emDate = emDate; for (int ii = 0; ii < this._projectInfo.size(); ii++) { Information info = getInfo(ii); if (info != null) { info._emDeadline = null; info._emFrames = null; info._emValue = null; } } Reader reader = null; if (_local == true) { reader = new FileReader("emprotz.dat"); } else { StringBuffer urlName = new StringBuffer(); urlName.append("http://home.comcast.net/"); urlName.append("~wxdude1/emsite/download/"); urlName.append("emprotz.zip"); try { URL url = new URL(urlName.toString()); InputStream stream = url.openStream(); ZipInputStream zip = new ZipInputStream(stream); zip.getNextEntry(); reader = new InputStreamReader(zip); } catch (MalformedURLException mue) { mue.printStackTrace(); } } BufferedReader file = new BufferedReader(reader); try { String line1 = null; int count = 0; while ((line1 = file.readLine()) != null) { String line2 = (line1 != null) ? file.readLine() : null; String line3 = (line2 != null) ? file.readLine() : null; String line4 = (line3 != null) ? file.readLine() : null; count++; if ((count > 1) && (line1 != null) && (line2 != null) && (line3 != null) && (line4 != null)) { if (line1.length() > 2) { int posBegin = line1.indexOf("\"", 0); int posEnd = line1.indexOf("\"", posBegin + 1); if ((posBegin >= 0) && (posEnd >= 0)) { String project = line1.substring(posBegin + 1, posEnd - posBegin); int projectNum = Integer.parseInt(project); Integer deadline = Integer.valueOf(line2.trim()); Double value = Double.valueOf(line3.trim()); Integer frames = Integer.valueOf(line4.trim()); Information info = getInfo(projectNum); if (info == null) { info = createInfo(projectNum); } if (info._emValue == null) { info._emDeadline = deadline; info._emFrames = frames; info._emValue = value; } } } } } } catch (Exception e) { e.printStackTrace(); } finally { file.close(); } } } catch (FileNotFoundException e) { } catch (IOException e) { } } Code Sample 2: public static boolean download(String url, File file) { HttpURLConnection conn = null; BufferedInputStream in = null; BufferedOutputStream out = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.connect(); if (conn.getResponseCode() == 200) { System.out.println("length:" + conn.getContentLength()); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(file)); byte[] b = new byte[1024 << 10]; int i = 0; while ((i = in.read(b)) > -1) { if (i > 0) out.write(b, 0, i); } return true; } else { System.out.println(conn.getResponseCode() + ":" + url); } } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } if (conn != null) conn.disconnect(); } return false; }
00
Code Sample 1: @Test public void test_lookupType_FullSearch_TwoWords() throws Exception { URL url = new URL(baseUrl + "/lookupType/deep+core"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("[{\"itemTypeID\":11395,\"itemCategoryID\":16,\"name\":\"Deep Core Mining\",\"icon\":\"50_11\"},{\"itemTypeID\":12108,\"itemCategoryID\":7,\"name\":\"Deep Core Mining Laser I\",\"icon\":\"35_01\",\"metaLevel\":0},{\"itemTypeID\":12109,\"itemCategoryID\":9,\"name\":\"Deep Core Mining Laser I Blueprint\",\"icon\":\"12_08\"},{\"itemTypeID\":18068,\"itemCategoryID\":7,\"name\":\"Modulated Deep Core Miner II\",\"icon\":\"35_01\",\"metaLevel\":5},{\"itemTypeID\":18069,\"itemCategoryID\":9,\"name\":\"Modulated Deep Core Miner II Blueprint\",\"icon\":\"12_08\"},{\"itemTypeID\":24305,\"itemCategoryID\":7,\"name\":\"Modulated Deep Core Strip Miner II\",\"icon\":\"49_05\",\"metaLevel\":5},{\"itemTypeID\":24306,\"itemCategoryID\":9,\"name\":\"Modulated Deep Core Strip Miner II Blueprint\",\"icon\":\"12_08\"},{\"itemTypeID\":28748,\"itemCategoryID\":7,\"name\":\"ORE Deep Core Mining Laser\",\"icon\":\"35_01\",\"metaLevel\":6}]")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); } 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; }
00
Code Sample 1: public static void bubbleSort(String[] a) { Collator myCollator = Collator.getInstance(); boolean switched = true; for (int pass = 0; pass < a.length - 1 && switched; pass++) { switched = false; for (int i = 0; i < a.length - pass - 1; i++) { if (myCollator.compare(a[i], a[i + 1]) > 0) { switched = true; String temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } } } Code Sample 2: private static void downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
11
Code Sample 1: private void transformFile(File input, File output, Cipher cipher, boolean compress, String progressMessage) throws IOException { FileInputStream fileInputStream = new FileInputStream(input); InputStream inputStream; if (progressMessage != null) { inputStream = new ProgressMonitorInputStream(null, progressMessage, fileInputStream); } else { inputStream = fileInputStream; } FilterInputStream is = new BufferedInputStream(inputStream); FilterOutputStream os = new BufferedOutputStream(new FileOutputStream(output)); FilterInputStream fis; FilterOutputStream fos; if (compress) { fis = is; fos = new GZIPOutputStream(new CipherOutputStream(os, cipher)); } else { fis = new GZIPInputStream(new CipherInputStream(is, cipher)); fos = os; } byte[] buffer = new byte[cipher.getBlockSize() * blocksInBuffer]; int readLength = fis.read(buffer); while (readLength != -1) { fos.write(buffer, 0, readLength); readLength = fis.read(buffer); } if (compress) { GZIPOutputStream gos = (GZIPOutputStream) fos; gos.finish(); } fos.close(); fis.close(); } Code Sample 2: public static void copy(final File src, File dst, final boolean overwrite) throws IOException, IllegalArgumentException { if (!src.isFile() || !src.exists()) { throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); } if (dst.exists()) { if (dst.isDirectory()) { dst = new File(dst, src.getName()); } else if (dst.isFile()) { if (!overwrite) { throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); } } else { throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); } } final File dstParent = dst.getParentFile(); if (!dstParent.exists()) { if (!dstParent.mkdirs()) { throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); } } long fileSize = src.length(); if (fileSize > 20971520l) { final FileInputStream in = new FileInputStream(src); final FileOutputStream out = new FileOutputStream(dst); try { int doneCnt = -1; final int bufSize = 32768; final byte buf[] = new byte[bufSize]; while ((doneCnt = in.read(buf, 0, bufSize)) >= 0) { if (doneCnt == 0) { Thread.yield(); } else { out.write(buf, 0, doneCnt); } } out.flush(); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } } } else { final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } } } }
00
Code Sample 1: private static void copy(String srcFilename, String dstFilename, boolean override) throws IOException, XPathFactoryConfigurationException, SAXException, ParserConfigurationException, XPathExpressionException { File fileToCopy = new File(rootDir + "test-output/" + srcFilename); if (fileToCopy.exists()) { File newFile = new File(rootDir + "test-output/" + dstFilename); if (!newFile.exists() || override) { try { FileChannel srcChannel = new FileInputStream(rootDir + "test-output/" + srcFilename).getChannel(); FileChannel dstChannel = new FileOutputStream(rootDir + "test-output/" + dstFilename).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } } } Code Sample 2: public static String sha256(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] data = new byte[64]; md.update(str.getBytes("iso-8859-1"), 0, str.length()); data = md.digest(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } } catch (Exception e) { errorLog("{Malgn.sha256} " + e.getMessage()); } return buf.toString(); }
11
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: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: private String convert(InputStream input, String encoding) throws Exception { Process p = Runtime.getRuntime().exec("tidy -q -f /dev/null -wrap 0 --output-xml yes --doctype omit --force-output true --new-empty-tags " + emptyTags + " --quote-nbsp no -utf8"); Thread t = new CopyThread(input, p.getOutputStream()); t.start(); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(p.getInputStream(), output); p.waitFor(); t.join(); return output.toString(); } Code Sample 2: public int delete(BusinessObject o) throws DAOException { int delete = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_BILL")); pst.setInt(1, bill.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
11
Code Sample 1: public static void extractZip(Resource zip, FileObject outputDirectory) { ZipInputStream zis = null; try { zis = new ZipInputStream(zip.getResourceURL().openStream()); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String[] pathElements = entry.getName().split("/"); FileObject extractDir = outputDirectory; for (int i = 0; i < pathElements.length - 1; i++) { String pathElementName = pathElements[i]; FileObject pathElementFile = extractDir.resolveFile(pathElementName); if (!pathElementFile.exists()) { pathElementFile.createFolder(); } extractDir = pathElementFile; } String fileName = entry.getName(); if (fileName.endsWith("/")) { fileName = fileName.substring(0, fileName.length() - 1); } if (fileName.contains("/")) { fileName = fileName.substring(fileName.lastIndexOf('/') + 1); } if (entry.isDirectory()) { extractDir.resolveFile(fileName).createFolder(); } else { FileObject file = extractDir.resolveFile(fileName); file.createFile(); int size = (int) entry.getSize(); byte[] unpackBuffer = new byte[size]; zis.read(unpackBuffer, 0, size); InputStream in = null; OutputStream out = null; try { in = new ByteArrayInputStream(unpackBuffer); out = file.getContent().getOutputStream(); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } } catch (IOException e2) { throw new RuntimeException(e2); } finally { IOUtils.closeQuietly(zis); } } Code Sample 2: private void copyFile(String sourceFilename, String targetFilename) throws IOException { File source = new File(sourceFilename); File target = new File(targetFilename); InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: protected Properties loadFile(String fileName) { Properties prop = new Properties(); try { String packageName = getClass().getName(); packageName = packageName.substring(0, packageName.lastIndexOf(".")); String src = "src"; if (mavenBuild) { src = src + File.separator + "test" + File.separator + "resources"; } packageName = src + File.separator + packageName.replace('.', File.separatorChar); packageName += File.separator; packageName += fileName; URL url0 = new File(packageName).toURI().toURL(); final InputStream input = url0.openStream(); prop.load(input); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return prop; } Code Sample 2: 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); } }
00
Code Sample 1: public File sendPayload(SoapEnvelope payload, URL url) throws IOException { URLConnection conn = null; File tempFile = null; Logger l = Logger.instance(); String className = getClass().getName(); l.log(Logger.DEBUG, loggerPrefix, className + ".sendPayload", "sending payload to " + url.toString()); try { conn = url.openConnection(); conn.setDoOutput(true); payload.writeTo(conn.getOutputStream()); tempFile = readIntoTempFile(conn.getInputStream()); } catch (IOException ioe) { l.log(Logger.ERROR, loggerPrefix, className + ".sendPayload", ioe); throw ioe; } finally { conn = null; } l.log(Logger.DEBUG, loggerPrefix, className + ".sendPayload", "received response"); return tempFile; } Code Sample 2: public InputStream getInputStream(long offset) throws IOException { if (is != null && raf == null) { try { is.close(); } catch (Throwable th) { } finally { is = null; } } if (is == null && getUrl() != null && getFile() == null) { is = url.openStream(); } if (is == null) { if (getFile() != null) { raf = null; try { raf = new RandomAccessFile(getFile(), "r"); } catch (Exception ex) { } is = (raf != null) ? new RAFInputStream(raf, 0) : new BufferedInputStream(new FileInputStream(getFile()), 1024 * 30); } } if (is instanceof RAFInputStream) { RAFInputStream ris = (RAFInputStream) is; ris.seek(offset); } else { is.skip(offset); } return is; }
11
Code Sample 1: public void movePrior(String[] showOrder, String[] orgID, String targetShowOrder, String targetOrgID) throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; int moveCount = showOrder.length; DBOperation dbo = factory.createDBOperation(POOL_NAME); String strQuery = "select show_order from " + Common.ORGANIZE_TABLE + " where show_order=" + showOrder[moveCount - 1] + " and organize_id= '" + orgID[moveCount - 1] + "'"; try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strQuery); result = ps.executeQuery(); int maxOrderNo = 0; if (result.next()) { maxOrderNo = result.getInt(1); } String[] sqls = new String[moveCount + 1]; sqls[0] = "update " + Common.ORGANIZE_TABLE + " set show_order=" + maxOrderNo + " where show_order=" + targetShowOrder + " and organize_id= '" + targetOrgID + "'"; for (int i = 0; i < showOrder.length; i++) { sqls[i + 1] = "update " + Common.ORGANIZE_TABLE + " set show_order=show_order-1" + " where show_order=" + showOrder[i] + " and organize_id= '" + orgID[i] + "'"; } for (int j = 0; j < sqls.length; j++) { ps = con.prepareStatement(sqls[j]); int resultCount = ps.executeUpdate(); if (resultCount != 1) { throw new CesSystemException("Organize.movePrior(): ERROR Inserting data " + "in T_SYS_ORGANIZE update !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { if (con != null) { con.rollback(); } throw new CesSystemException("Organize.movePrior(): SQLException while mov organize order " + " :\n\t" + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); sql = "DELETE FROM usuario WHERE cod_usuario =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
11
Code Sample 1: public static void copyFile(File src, File dest) { try { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ioe) { System.err.println(ioe); } } Code Sample 2: public static void main(String[] args) { try { FileReader reader = new FileReader(args[0]); FileWriter writer = new FileWriter(args[1]); html2xhtml(reader, writer); writer.close(); reader.close(); } catch (Exception e) { freemind.main.Resources.getInstance().logException(e); } }
11
Code Sample 1: public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; } Code Sample 2: public static String encrypt(String key) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.update(key.getBytes()); byte hash[] = md5.digest(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String temp = Integer.toHexString(0xFF & hash[i]); if (temp.length() == 1) temp = "0" + temp; buffer.append(temp); } return buffer.toString(); }
00
Code Sample 1: @Override public void downloadByUUID(final UUID uuid, final HttpServletRequest request, final HttpServletResponse response) throws IOException { if (!exportsInProgress.containsKey(uuid)) { throw new IllegalStateException("No download with UUID: " + uuid); } final File compressedFile = exportsInProgress.get(uuid).file; logger.debug("File size: " + compressedFile.length()); OutputStream output = null; InputStream fileInputStream = null; try { output = response.getOutputStream(); prepareResponse(request, response, compressedFile); fileInputStream = new FileInputStream(compressedFile); IOUtils.copy(fileInputStream, output); output.flush(); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(output); } } Code Sample 2: public String getDefaultPaletteXML() { URL url = getClass().getResource("xml/palettes.xml"); StringBuffer contents = new StringBuffer(); try { InputStream inputStream = url.openStream(); int i; while (true) { i = inputStream.read(); if (i == -1) break; char c = (char) i; contents.append(c); } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return contents.toString(); }
11
Code Sample 1: public void test() throws Exception { StringDocument doc = new StringDocument("Test", "UTF-8"); doc.open(); try { assertEquals("UTF-8", doc.getCharacterEncoding()); assertEquals("Test", doc.getText()); InputStream input = doc.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { writer.close(); } assertEquals("Test", writer.toString()); } finally { doc.close(); } } Code Sample 2: @Before public void setUp() throws IOException { testSbk = File.createTempFile("songbook", "sbk"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("test.sbk"), new FileOutputStream(testSbk)); test1Sbk = File.createTempFile("songbook", "sbk"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("test1.sbk"), new FileOutputStream(test1Sbk)); }
11
Code Sample 1: private void writeAndCheckFile(DataFileReader reader, String base, String path, String hash, Reference ref, boolean hashall) throws Exception { Data data = ref.data; File file = new File(base + path); file.getParentFile().mkdirs(); if (Debug.level > 1) System.err.println("read file " + data.file + " at index " + data.index); OutputStream output = new FileOutputStream(file); if (hashall) output = new DigestOutputStream(output, MessageDigest.getInstance("MD5")); reader.read(output, data.index, data.file); output.close(); if (hashall) { String filehash = StringUtils.toHex(((DigestOutputStream) output).getMessageDigest().digest()); if (!hash.equals(filehash)) throw new RuntimeException("hash wasn't equal for " + file); } file.setLastModified(ref.lastmod); if (file.length() != data.size) throw new RuntimeException("corrupted file " + file); } Code Sample 2: public static void main(String[] args) throws IOException, WrongFormatException, URISyntaxException { System.out.println(new URI("google.com.ua.css").toString()); Scanner scc = new Scanner(System.in); System.err.print(scc.nextLine().substring(1)); ServerSocket s = new ServerSocket(5354); while (true) { Socket client = s.accept(); InputStream iStream = client.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(iStream)); String line = ""; while (!(line = bf.readLine()).equals("")) { System.out.println(line); } System.out.println("end of request"); new PrintWriter(client.getOutputStream()).println("hi"); bf.close(); } }
00
Code Sample 1: public boolean connect() { if (connectStatus > -1) return (connectStatus == 1); connectStatus = 0; try { URL url = new URL(getURL()); m_connection = (HttpURLConnection) url.openConnection(); m_connection.connect(); processHeaders(); m_inputStream = m_connection.getInputStream(); } catch (MalformedURLException e) { newError("connect failed", e, true); } catch (IOException e) { newError("connect failed", e, true); } return (connectStatus == 1); } Code Sample 2: public static int writeFile(URL url, File outFilename) { InputStream input; try { input = url.openStream(); } catch (IOException e) { e.printStackTrace(); return 0; } FileOutputStream outputStream; try { outputStream = new FileOutputStream(outFilename); } catch (FileNotFoundException e) { e.printStackTrace(); return 0; } return writeFile(input, outputStream); }
00
Code Sample 1: private static Map<String, File> loadServiceCache() { ArrayList<String> preferredOrder = new ArrayList<String>(); HashMap<String, File> serviceFileMapping = new HashMap<String, File>(); File file = new File(IsqlToolkit.getBaseDirectory(), CACHE_FILE); if (!file.exists()) { return serviceFileMapping; } if (file.canRead()) { FileReader fileReader = null; try { fileReader = new FileReader(file); BufferedReader lineReader = new BufferedReader(fileReader); while (lineReader.ready()) { String data = lineReader.readLine(); if (data.charAt(0) == '#') { continue; } int idx0 = 0; int idx1 = data.indexOf(SERVICE_FIELD_SEPERATOR); String name = StringUtilities.decodeASCII(data.substring(idx0, idx1)); String uri = StringUtilities.decodeASCII(data.substring(idx1 + 1)); if (name.equalsIgnoreCase(KEY_SERVICE_LIST)) { StringTokenizer st = new StringTokenizer(uri, SERVICE_SEPERATOR); while (st.hasMoreTokens()) { String serviceName = st.nextToken(); preferredOrder.add(serviceName.toLowerCase().trim()); } continue; } try { URL url = new URL(uri); File serviceFile = new File(url.getFile()); if (serviceFile.isDirectory()) { logger.warn(messages.format("compatability_kit.service_mapped_to_directory", name, uri)); continue; } else if (!serviceFile.canRead()) { logger.warn(messages.format("compatability_kit.service_not_readable", name, uri)); continue; } else if (!serviceFile.exists()) { logger.warn(messages.format("compatability_kit.service_does_not_exist", name, uri)); continue; } String bindName = name.toLowerCase().trim(); InputStream inputStream = null; try { inputStream = url.openStream(); InputSource inputSource = new InputSource(inputStream); bindName = ServiceDigester.parseService(inputSource, IsqlToolkit.getSharedEntityResolver()).getName(); } catch (Exception error) { continue; } if (serviceFileMapping.put(bindName, serviceFile) != null) { logger.warn(messages.format("compatability_kit.service_duplicate_name_error", name, uri)); } } catch (MalformedURLException e) { logger.error(messages.format("compatability_kit.service_uri_error", name, uri), e); } } } catch (IOException ioe) { logger.error("compatability_kit.service_generic_error", ioe); } finally { if (fileReader != null) { try { fileReader.close(); } catch (Throwable ignored) { } } } } return serviceFileMapping; } Code Sample 2: public String getPolicy(String messageBufferName) throws AppFabricException { String responseString = null; MessageBufferUtil msgBufferUtilObj = new MessageBufferUtil(solutionName, TokenConstants.getSimpleAuthAuthenticationType()); String requestUri = msgBufferUtilObj.getRequestUri(); String messageBufferUri = msgBufferUtilObj.getCreateMessageBufferUri(messageBufferName); String authorizationToken = ""; try { ACSTokenProvider tp = new ACSTokenProvider(httpWebProxyServer_, httpWebProxyPort_, this.credentials); authorizationToken = tp.getACSToken(requestUri, messageBufferUri); } catch (Exception e) { throw new AppFabricException(e.getMessage()); } try { messageBufferUri = messageBufferUri.replaceAll("http", "https"); URL urlConn = new URL(messageBufferUri); HttpURLConnection connection; StringBuffer sBuf = new StringBuffer(); if (httpWebProxy_ != null) connection = (HttpURLConnection) urlConn.openConnection(httpWebProxy_); else connection = (HttpURLConnection) urlConn.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-type", MessageBufferConstants.getCONTENT_TYPE_PROPERTY_FOR_ATOM_XML()); String authStr = TokenConstants.getWrapAuthenticationType() + " " + TokenConstants.getWrapAuthorizationHeaderKey() + "=\"" + authorizationToken + "\""; connection.setRequestProperty("Authorization", authStr); if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logRequest(connection, SDKLoggerHelper.RecordType.GetPolicy_REQUEST); String responseCode = "<responseCode>" + connection.getResponseCode() + "</responseCode>"; if ((connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_OK)) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rd.readLine()) != null) { sBuf.append(line); sBuf.append('\r'); } rd.close(); if (sBuf.toString().indexOf("<entry xmlns=") != -1) { responseString = sBuf.toString(); if (LoggerUtil.getIsLoggingOn()) { StringBuilder responseXML = new StringBuilder(); responseXML.append(responseCode); responseXML.append(responseString); SDKLoggerHelper.logMessage(URLEncoder.encode(responseXML.toString(), "UTF-8"), SDKLoggerHelper.RecordType.GetPolicy_RESPONSE); } return responseString; } else { throw new AppFabricException("Message buffer policy could not be retrieved"); } } else { if (LoggerUtil.getIsLoggingOn()) { SDKLoggerHelper.logMessage(URLEncoder.encode(responseCode, "UTF-8"), SDKLoggerHelper.RecordType.GetPolicy_RESPONSE); } throw new AppFabricException("Message buffer policy could not be retrieved. Error.Response code: " + connection.getResponseCode()); } } catch (Exception e) { throw new AppFabricException(e.getMessage()); } }
00
Code Sample 1: protected void loadResourceLocations() { try { for (String path : resourceLocations) { if (path.startsWith("${") && path.endsWith("}")) { int start = path.indexOf('{') + 1; int end = path.indexOf('}'); String key = path.substring(start, end).trim(); if (key.equals(ApplicationConstants.RESOURCE_SQL_LOCATION_PROP_NAME)) path = AdminHelper.getRepository().getURI("sql"); else path = AdminHelper.getRepository().getSetupApplicationProperties().get(key); log.debug(key + "=" + path); } FileObject fo = VFSUtils.resolveFile(path); if (fo.exists()) { URL url = fo.getURL(); url.openConnection(); if (fastDeploy) { if (log.isDebugEnabled()) { log.debug("Fast deploy : " + url); AdminSqlQueryFactory builder = null; for (DirectoryListener listener : scanner.getDirectoryListeners()) { if (listener instanceof AdminSqlQueryFactory) { builder = (AdminSqlQueryFactory) listener; } } File file = new File(url.getFile()); fastDeploy(file, builder); } } scanner.addScanURL(url); } } } catch (Exception e) { } } Code Sample 2: public void testPreparedStatementRollback1() throws Exception { Connection localCon = getConnection(); Statement stmt = localCon.createStatement(); stmt.execute("CREATE TABLE #psr1 (data BIT)"); localCon.setAutoCommit(false); PreparedStatement pstmt = localCon.prepareStatement("INSERT INTO #psr1 (data) VALUES (?)"); pstmt.setBoolean(1, true); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); localCon.rollback(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psr1"); assertFalse(rs.next()); rs.close(); stmt.close(); localCon.close(); try { localCon.commit(); fail("Expecting commit to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } try { localCon.rollback(); fail("Expecting rollback to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } }
00
Code Sample 1: public FileBean create(MimeTypeBean mimeType, SanBean san) throws SQLException { long fileId = 0; DataSource ds = getDataSource(DEFAULT_DATASOURCE); Connection conn = ds.getConnection(); try { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); stmt.execute(NEXT_FILE_ID); ResultSet rs = stmt.getResultSet(); while (rs.next()) { fileId = rs.getLong(NEXTVAL); } PreparedStatement pstmt = conn.prepareStatement(INSERT_FILE); pstmt.setLong(1, fileId); pstmt.setLong(2, mimeType.getId()); pstmt.setLong(3, san.getId()); pstmt.setLong(4, WORKFLOW_ATTENTE_VALIDATION); int nbrow = pstmt.executeUpdate(); if (nbrow == 0) { throw new SQLException(); } conn.commit(); closeRessources(conn, pstmt); } catch (SQLException e) { log.error("Can't FileDAOImpl.create " + e.getMessage()); conn.rollback(); throw e; } FileBean fileBean = new FileBean(); return fileBean; } Code Sample 2: public static void track(String strUserName, String strShortDescription, String strLongDescription, String strPriority, String strComponent) { String strFromToken = ""; try { URL url = new URL(getTracUrl() + "newticket"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String buffer = reader.readLine(); while (buffer != null) { if (buffer.contains("__FORM_TOKEN")) { Pattern pattern = Pattern.compile("value=\"[^\"]*\""); Matcher matcher = pattern.matcher(buffer); int start = 0; matcher.find(start); int von = matcher.start() + 7; int bis = matcher.end() - 1; strFromToken = buffer.substring(von, bis); } buffer = reader.readLine(); } HttpClient client = new HttpClient(); PostMethod method = new PostMethod(getTracUrl() + "newticket"); method.setRequestHeader("Cookie", "trac_form_token=" + strFromToken); method.addParameter("__FORM_TOKEN", strFromToken); method.addParameter("reporter", strUserName); method.addParameter("summary", strShortDescription); method.addParameter("type", "Fehler"); method.addParameter("description", strLongDescription); method.addParameter("action", "create"); method.addParameter("status", "new"); method.addParameter("priority", strPriority); method.addParameter("milestone", ""); method.addParameter("component", strComponent); method.addParameter("keywords", "BugReporter"); method.addParameter("cc", ""); method.addParameter("version", ""); client.executeMethod(method); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private void createUser(AddEditUserForm addform, HttpServletRequest request, ActionMapping mapping) throws Exception { MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone(); md.update(addform.getPassword().getBytes("UTF-8")); byte[] pd = md.digest(); StringBuffer app = new StringBuffer(); for (int i = 0; i < pd.length; i++) { String s2 = Integer.toHexString(pd[i] & 0xFF); app.append((s2.length() == 1) ? "0" + s2 : s2); } Session hbsession = HibernateUtil.currentSession(); try { Transaction tx = hbsession.beginTransaction(); NvUsers user = new NvUsers(); user.setLogin(addform.getLogin()); user.setPassword(app.toString()); hbsession.save(user); hbsession.flush(); if (!hbsession.connection().getAutoCommit()) { tx.commit(); } } finally { HibernateUtil.closeSession(); } } Code Sample 2: private void resolveFileDeclarations(Query query, Map<String, URL> sqlDeclarations) { Statement stmt = query.getStatement(); String fileDeclaration = stmt.getFile(); boolean hasFileDeclaration = fileDeclaration != null && !"".equals(fileDeclaration); if (hasFileDeclaration) { try { URL url = sqlDeclarations.get(stmt.getFile()); if (url != null) { URLConnection conn = url.openConnection(); InputStream input = conn.getInputStream(); String sqlDeclaration = StreamUtils.obtainStreamContents(input); stmt.setValue(sqlDeclaration); input.close(); } } catch (Exception e) { } } }
00
Code Sample 1: public static String calculateHA1(String username, byte[] password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(username, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(DAAP_REALM, ISO_8859_1)); md.update((byte) ':'); md.update(password); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } Code Sample 2: private void copyFileToDir(MyFile file, MyFile to, wlPanel panel) throws IOException { Utilities.print("started copying " + file.getAbsolutePath() + "\n"); FileOutputStream fos = new FileOutputStream(new File(to.getAbsolutePath())); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(new File(file.getAbsolutePath())); FileChannel fic = fis.getChannel(); Date d1 = new Date(); long amount = foc.transferFrom(fic, rest, fic.size() - rest); fic.close(); foc.force(false); foc.close(); Date d2 = new Date(); long time = d2.getTime() - d1.getTime(); double secs = time / 1000.0; double rate = amount / secs; frame.getStatusArea().append(secs + "s " + "amount: " + Utilities.humanReadable(amount) + " rate: " + Utilities.humanReadable(rate) + "/s\n", "black"); panel.updateView(); }
11
Code Sample 1: protected boolean downloadFile(TestThread thread, ActionResult result) { result.setRequestString("download file " + remoteFile); InputStream input = null; OutputStream output = null; OutputStream target = null; boolean status = false; ftpClient.enterLocalPassiveMode(); try { if (localFile != null) { File lcFile = new File(localFile); if (lcFile.exists() && lcFile.isDirectory()) output = new FileOutputStream(new File(lcFile, remoteFile)); else output = new FileOutputStream(lcFile); target = output; } else { target = new FileOutputStream(remoteFile); } input = ftpClient.retrieveFileStream(remoteFile); long bytes = IOUtils.copy(input, target); status = bytes > 0; if (status) { result.setResponseLength(bytes); } } catch (Exception e) { result.setException(new TestActionException(config, e)); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } return status; } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS); String uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_FULL_PREFIX) + Constants.SERVLET_FULL_PREFIX.length() + 1); boolean notScale = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_NOT_SCALE)); ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { String mimetype = fedoraAccess.getMimeTypeForStream(uuid, FedoraUtils.IMG_FULL_STREAM); if (mimetype == null) { mimetype = "image/jpeg"; } ImageMimeType loadFromMimeType = ImageMimeType.loadFromMimeType(mimetype); if (loadFromMimeType == ImageMimeType.JPEG || loadFromMimeType == ImageMimeType.PNG) { StringBuffer sb = new StringBuffer(); sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/IMG_FULL/content"); InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to close stream.", e); } finally { is = null; } } } } else { Image rawImg = KrameriusImageSupport.readImage(uuid, FedoraUtils.IMG_FULL_STREAM, this.fedoraAccess, 0, loadFromMimeType); BufferedImage scaled = null; if (!notScale) { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 1250, 1000); } else { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 2500, 2000); } KrameriusImageSupport.writeImageToStream(scaled, "JPG", os); resp.setContentType(ImageMimeType.JPEG.getValue()); resp.setStatus(HttpURLConnection.HTTP_OK); } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } catch (XPathExpressionException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to create XPath expression.", e); } finally { os.flush(); } } }
00
Code Sample 1: Object onSuccess() { this.mErrorExist = true; this.mErrorMdp = true; if (this.mNewMail.equals(mClient.getEmail()) || !this.mNewMail.equals(mClient.getEmail()) && !mClientManager.exists(this.mNewMail)) { this.mErrorExist = false; if (mNewMdp != null && mNewMdpConfirm != null) { if (this.mNewMdp.equals(this.mNewMdpConfirm)) { this.mErrorMdp = false; MessageDigest sha1Instance; try { sha1Instance = MessageDigest.getInstance("SHA1"); sha1Instance.reset(); sha1Instance.update(this.mNewMdp.getBytes()); byte[] digest = sha1Instance.digest(); BigInteger bigInt = new BigInteger(1, digest); String vHashPassword = bigInt.toString(16); mClient.setMdp(vHashPassword); } catch (NoSuchAlgorithmException e) { mLogger.error(e.getMessage(), e); } } } else { this.mErrorMdp = false; } if (!this.mErrorMdp) { mClient.setAdresse(this.mNewAdresse); mClient.setEmail(this.mNewMail); mClient.setNom(this.mNewNom); mClient.setPrenom((this.mNewPrenom != null ? this.mNewPrenom : "")); Client vClient = new Client(mClient); mClientManager.save(vClient); mComponentResources.discardPersistentFieldChanges(); return "Client/List"; } } return errorZone.getBody(); } Code Sample 2: public String getDefaultPaletteXML() { URL url = getClass().getResource("xml/palettes.xml"); StringBuffer contents = new StringBuffer(); try { InputStream inputStream = url.openStream(); int i; while (true) { i = inputStream.read(); if (i == -1) break; char c = (char) i; contents.append(c); } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return contents.toString(); }
00
Code Sample 1: public static Class[] findSubClasses(Class baseClass) { String packagePath = "/" + baseClass.getPackage().getName().replace('.', '/'); URL url = baseClass.getResource(packagePath); if (url == null) { return new Class[0]; } List<Class> derivedClasses = new ArrayList<Class>(); try { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { JarFile jarFile = ((JarURLConnection) connection).getJarFile(); Enumeration e = jarFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); String entryName = entry.getName(); if (entryName.endsWith(".class")) { String clazzName = entryName.substring(0, entryName.length() - 6); clazzName = clazzName.replace('/', '.'); try { Class clazz = Class.forName(clazzName); if (isConcreteSubclass(baseClass, clazz)) { derivedClasses.add(clazz); } } catch (Throwable ignoreIt) { } } } } else if (connection instanceof FileURLConnection) { File file = new File(url.getFile()); File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { String filename = files[i].getName(); if (filename.endsWith(".class")) { filename = filename.substring(0, filename.length() - 6); String clazzname = baseClass.getPackage().getName() + "." + filename; try { Class clazz = Class.forName(clazzname); if (isConcreteSubclass(baseClass, clazz)) { derivedClasses.add(clazz); } } catch (Throwable ignoreIt) { } } } } } catch (IOException ignoreIt) { } return derivedClasses.toArray(new Class[derivedClasses.size()]); } Code Sample 2: protected Object serveFile(MyServerSocket socket, String filenm, URL url) { PrintStream out = null; InputStream in = null; long len = 0; try { out = new PrintStream(socket.getOutputStream()); in = url.openStream(); len = in.available(); } catch (IOException e) { HttpHelper.httpWrap(HttpHelper.EXC, e.toString(), 0); } if (HttpHelper.isImage(filenm)) { out.print(HttpHelper.httpWrapPic(filenm, len)); } else if (filenm.endsWith(".html")) { Comms.copyStreamSED(in, out, MPRES); } else if (HttpHelper.isOtherFile(filenm)) { out.print(HttpHelper.httpWrapOtherFile(filenm, len)); } else { String type = MimeUtils.getMimeType(filenm); if (type.equals(MimeUtils.UNKNOWN_MIME_TYPE)) { out.print(HttpHelper.httpWrapMimeType(type, len)); } else { out.print(HttpHelper.httpWrapMimeType(type, len)); } } if (in == null) { Log.logThis("THE INPUT STREAM IS NULL...url=" + url); } else Files.copyStream(in, out); return null; }
00
Code Sample 1: protected Document fetchResource(String method, String parameter, Locale locale, final FloodLimit limit) throws IOException, SAXException { return getDocument(new CachedPage(getResourceLocation(method, parameter, locale)) { @Override protected Reader openConnection(URL url) throws IOException { try { if (limit != null) { limit.acquirePermit(); } return super.openConnection(url); } catch (InterruptedException e) { throw new IOException(e); } } ; }.get()); } 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(); } }
00
Code Sample 1: public static String md5(String string) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString((result[i] & 0xFF) | 0x100).toLowerCase().substring(1, 3)); } return hexString.toString(); } Code Sample 2: public int addCollectionInstruction() throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { String sql = "insert into Instructions (Type, Operator) " + "values (1, 0)"; conn = fido.util.FidoDataSource.getConnection(); stmt = conn.createStatement(); stmt.executeUpdate(sql); return getCurrentId(stmt); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
00
Code Sample 1: 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); } Code Sample 2: private NodeInfo loadNodeMeta(int id, int properties) { String query = mServer + "load.php" + ("?id=" + id) + ("&mask=" + properties); NodeInfo info = null; try { URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(false); conn.setRequestMethod("GET"); setCredentials(conn); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream stream = conn.getInputStream(); MimeType contentType = new MimeType(conn.getContentType()); if (contentType.getBaseType().equals("text/xml")) { try { JAXBContext context = JAXBContext.newInstance(NetProcessorInfo.class); Unmarshaller unm = context.createUnmarshaller(); NetProcessorInfo root = (NetProcessorInfo) unm.unmarshal(stream); if ((root != null) && (root.getNodes().length == 1)) { info = root.getNodes()[0]; } } catch (Exception ex) { } } stream.close(); } } catch (Exception ex) { } return info; }
00
Code Sample 1: public static byte[] resolveRef(String url) throws MalformedURLException, IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); URL addressurl = new URL(url); InputStream in = addressurl.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer, 0, bufferSize)) != -1) { out.write(buffer, 0, bytesRead); out.flush(); } return out.toByteArray(); } Code Sample 2: public void testResolveURL() throws Exception { System.out.println("resolveURL"); File bigFile = new File("./src/test/java/big.json"); File smallFile = new File("./src/test/java/sample1.json"); Object[] urls = new Object[] { "http://json-schema.org/schema", "http://json-schema.org/hyper-schema", "http://json-schema.org/json-ref", "http://json-schema.org/interfaces", "http://json-schema.org/geo", "http://json-schema.org/card", "http://json-schema.org/calendar", "http://json-schema.org/address", bigFile }; JSONSchemaURIResolverImpl uriResolver = new JSONSchemaURIResolverImpl(); JSONSchemaURIResolverImpl uriResolver2 = new JSONSchemaURIResolverImpl(); try { InputStream is = new URL((String) urls[0]).openStream(); is.close(); } catch (ConnectException cex) { for (int i = 2; i < urls.length; i++) { if (urls[i] instanceof String) { String url = (String) urls[i]; uriResolver.register(new URL(url), new File("./src/test/java/" + url.replace(":", "_").replace("/", "_") + ".schema.json")); } else if (urls[i] instanceof File) { uriResolver.register(((File) urls[i]).toURI().toURL(), urls[i]); } } } catch (Exception ex) { } for (int i = 2; i < urls.length; i++) { if (urls[i] instanceof String) { String url = (String) urls[i]; uriResolver2.register(new URL(url), new File("./src/test/java/" + url.replace(":", "_").replace("/", "_") + ".schema.json")); } else if (urls[i] instanceof File) { uriResolver2.register(((File) urls[i]).toURI().toURL(), urls[i]); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver.resolveURI(new URI((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver.resolveURL(new URL((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver2.resolveURI(new URI((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); assertTrue((new URL((String) source)).equals(uriResolver2.lastURL)); assertFalse((new URL((String) source)).equals(uriResolver2.lastMapped)); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver2.resolveURL(new URL((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); assertTrue((new URL((String) source)).equals(uriResolver2.lastURL)); assertFalse((new URL((String) source)).equals(uriResolver2.lastMapped)); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } uriResolver2.register(new URL("ftp://localhost/1"), bigFile); uriResolver2.register(new URL("ftp://localhost/2"), smallFile); uriResolver2.register(new URL("ftp://localhost/2#2"), smallFile); try { Reader r1 = uriResolver2.resolveURL(new URL("ftp://localhost/2"), null).getReader(); Reader r2 = uriResolver2.resolveURL(new URL("ftp://localhost/2#2"), null).getReader(); int ch = 0; while ((ch = r1.read()) != -1) { assertEquals(ch, r2.read()); } assertEquals(-1, r2.read()); } catch (Throwable th) { fail("Failed while testing identity of same mapped files. Error: " + th); } uriResolver2.register(new URL("ftp://localhost/1"), null); uriResolver2.register(new URL("ftp://localhost/2"), null); uriResolver2.register(new URL("ftp://localhost/2#2"), null); uriResolver2.register(new URL("ftp://localhost/1"), bigFile, true); uriResolver2.register(new URL("ftp://localhost/2"), smallFile, true); uriResolver2.register(new URL("ftp://localhost/2#2"), smallFile, true); uriResolver2.unregister(new URL("ftp://localhost/1"), true); uriResolver2.unregister(new URL("ftp://localhost/2"), true); uriResolver2.unregister(new URL("ftp://localhost/2#2"), true); }
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 static Document getSkeleton() { Document doc = null; String filesep = System.getProperty("file.separator"); try { java.net.URL url = Skeleton.class.getResource(filesep + "simplemassimeditor" + filesep + "resources" + filesep + "configskeleton.xml"); InputStream input = url.openStream(); DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); try { doc = parser.parse(input); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return doc; }
00
Code Sample 1: @Test public void testDocumentDownloadKnowledgeBase() throws IOException { if (uploadedKbDocumentID == null) { fail("Document Upload Test should run first"); } String downloadLink = GoogleDownloadLinkGenerator.generateTextDownloadLink(uploadedKbDocumentID); URL url = new URL(downloadLink); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream input = url.openStream(); FileWriter fw = new FileWriter("tmpOutput.kb"); Reader reader = new InputStreamReader(input); BufferedReader bufferedReader = new BufferedReader(reader); String strLine = ""; int count = 0; while (count < 10000) { strLine = bufferedReader.readLine(); if (strLine != null && strLine != "") { fw.write(strLine); } count++; } } Code Sample 2: public void extractPrincipalClasses(String[] info, int numFiles) { String methodName = ""; String finalClass = ""; String WA; String MC; String RA; int[] readCount = new int[numFiles]; int[] writeCount = new int[numFiles]; int[] methodCallCount = new int[numFiles]; int writeMax1; int writeMax2; int readMax; int methodCallMax; int readMaxIndex = 0; int writeMaxIndex1 = 0; int writeMaxIndex2; int methodCallMaxIndex = 0; try { MethodsDestClass = new BufferedWriter(new FileWriter("InfoFiles/MethodsDestclass.txt")); FileInputStream fstreamWriteAttr = new FileInputStream("InfoFiles/WriteAttributes.txt"); DataInputStream inWriteAttr = new DataInputStream(fstreamWriteAttr); BufferedReader writeAttr = new BufferedReader(new InputStreamReader(inWriteAttr)); FileInputStream fstreamMethodsCalled = new FileInputStream("InfoFiles/MethodsCalled.txt"); DataInputStream inMethodsCalled = new DataInputStream(fstreamMethodsCalled); BufferedReader methodsCalled = new BufferedReader(new InputStreamReader(inMethodsCalled)); FileInputStream fstreamReadAttr = new FileInputStream("InfoFiles/ReadAttributes.txt"); DataInputStream inReadAttr = new DataInputStream(fstreamReadAttr); BufferedReader readAttr = new BufferedReader(new InputStreamReader(inReadAttr)); while ((WA = writeAttr.readLine()) != null && (RA = readAttr.readLine()) != null && (MC = methodsCalled.readLine()) != null) { WA = writeAttr.readLine(); RA = readAttr.readLine(); MC = methodsCalled.readLine(); while (WA.compareTo("EndOfClass") != 0 && RA.compareTo("EndOfClass") != 0 && MC.compareTo("EndOfClass") != 0) { methodName = writeAttr.readLine(); readAttr.readLine(); methodsCalled.readLine(); WA = writeAttr.readLine(); MC = methodsCalled.readLine(); RA = readAttr.readLine(); while (true) { if (WA.compareTo("EndOfMethod") == 0 && RA.compareTo("EndOfMethod") == 0 && MC.compareTo("EndOfMethod") == 0) { break; } if (WA.compareTo("EndOfMethod") != 0) { if (WA.indexOf(".") > 0) { WA = WA.substring(0, WA.indexOf(".")); } } if (RA.compareTo("EndOfMethod") != 0) { if (RA.indexOf(".") > 0) { RA = RA.substring(0, RA.indexOf(".")); } } if (MC.compareTo("EndOfMethod") != 0) { if (MC.indexOf(".") > 0) { MC = MC.substring(0, MC.indexOf(".")); } } for (int i = 0; i < numFiles && info[i] != null; i++) { if (info[i].compareTo(WA) == 0) { writeCount[i]++; } if (info[i].compareTo(RA) == 0) { readCount[i]++; } if (info[i].compareTo(MC) == 0) { methodCallCount[i]++; } } if (WA.compareTo("EndOfMethod") != 0) { WA = writeAttr.readLine(); } if (MC.compareTo("EndOfMethod") != 0) { MC = methodsCalled.readLine(); } if (RA.compareTo("EndOfMethod") != 0) { RA = readAttr.readLine(); } } WA = writeAttr.readLine(); MC = methodsCalled.readLine(); RA = readAttr.readLine(); writeMax1 = writeCount[0]; writeMaxIndex1 = 0; for (int i = 1; i < numFiles; i++) { if (writeCount[i] > writeMax1) { writeMax1 = writeCount[i]; writeMaxIndex1 = i; } } writeCount[writeMaxIndex1] = 0; writeMax2 = writeCount[0]; writeMaxIndex2 = 0; for (int i = 1; i < numFiles; i++) { if (writeCount[i] > writeMax2) { writeMax2 = writeCount[i]; writeMaxIndex2 = i; } } readMax = readCount[0]; readMaxIndex = 0; for (int i = 1; i < numFiles; i++) { if (readCount[i] > readMax) { readMax = readCount[i]; readMaxIndex = i; } } methodCallMax = methodCallCount[0]; methodCallMaxIndex = 0; for (int i = 1; i < numFiles; i++) { if (methodCallCount[i] > methodCallMax) { methodCallMax = methodCallCount[i]; methodCallMaxIndex = i; } } boolean isNotEmpty = false; if (writeMax1 > 0 && writeMax2 == 0) { finalClass = info[writeMaxIndex1]; isNotEmpty = true; } else if (writeMax1 == 0) { if (readMax != 0) { finalClass = info[readMaxIndex]; isNotEmpty = true; } else if (methodCallMax != 0) { finalClass = info[methodCallMaxIndex]; isNotEmpty = true; } } if (isNotEmpty == true) { MethodsDestClass.write(methodName); MethodsDestClass.newLine(); MethodsDestClass.write(finalClass); MethodsDestClass.newLine(); isNotEmpty = false; } for (int j = 0; j < numFiles; j++) { readCount[j] = 0; writeCount[j] = 0; methodCallCount[j] = 0; } } } writeAttr.close(); methodsCalled.close(); readAttr.close(); MethodsDestClass.close(); int sizeInfoArray = 0; sizeInfoArray = infoArraySize(); boolean classWritten = false; principleClass = new String[100]; principleMethod = new String[100]; principleMethodsClass = new String[100]; String infoArray[] = new String[sizeInfoArray]; String field; int counter = 0; FileInputStream fstreamDestMethod = new FileInputStream("InfoFiles/MethodsDestclass.txt"); DataInputStream inDestMethod = new DataInputStream(fstreamDestMethod); BufferedReader destMethod = new BufferedReader(new InputStreamReader(inDestMethod)); PrincipleClassGroup = new BufferedWriter(new FileWriter("InfoFiles/PrincipleClassGroup.txt")); while ((field = destMethod.readLine()) != null) { infoArray[counter] = field; counter++; } for (int i = 0; i < numFiles; i++) { for (int j = 0; j < counter - 1 && info[i] != null; j++) { if (infoArray[j + 1].compareTo(info[i]) == 0) { if (classWritten == false) { PrincipleClassGroup.write(infoArray[j + 1]); PrincipleClassGroup.newLine(); principleClass[principleClassCount] = infoArray[j + 1]; principleClassCount++; classWritten = true; } PrincipleClassGroup.write(infoArray[j]); principleMethod[principleMethodCount] = infoArray[j]; principleMethodsClass[principleMethodCount] = infoArray[j + 1]; principleMethodCount++; PrincipleClassGroup.newLine(); } } if (classWritten == true) { PrincipleClassGroup.write("EndOfClass"); PrincipleClassGroup.newLine(); classWritten = false; } } destMethod.close(); PrincipleClassGroup.close(); readFileCount = readFileCount(); writeFileCount = writeFileCount(); methodCallFileCount = methodCallFileCount(); readArray = new String[readFileCount]; writeArray = new String[writeFileCount]; callArray = new String[methodCallFileCount]; initializeArrays(); constructFundamentalView(); constructInteractionView(); constructAssociationView(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copy(File source, File dest) throws Exception { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: private static String readStreamToString(InputStream is, boolean passInVelocity, String tplName, Map<String, Object> templateVarsMap) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); if (passInVelocity) { return tpl.formatStr(sw.toString(), templateVarsMap, tplName); } return sw.toString(); }
11
Code Sample 1: public void bubble() { boolean test = false; int kars = 0, tas = 0; while (true) { for (int j = 0; j < dizi.length - 1; j++) { kars++; if (dizi[j] > dizi[j + 1]) { int temp = dizi[j]; dizi[j] = dizi[j + 1]; dizi[j + 1] = temp; test = true; tas++; } } if (!test) { break; } else { test = false; } } System.out.print(kars + " " + tas); } Code Sample 2: public RobotList<Float> sort_incr_Float(RobotList<Float> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i)); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value > distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Float> sol = new RobotList<Float>(Float.class); for (int i = 0; i < length; i++) { sol.addLast(new Float(distri[i].value)); } return sol; }
11
Code Sample 1: public static void copyFile1(File srcFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); FileChannel source = fis.getChannel(); FileChannel destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); fis.close(); fos.close(); } Code Sample 2: public static void unzip(String destDir, String zipPath) { PrintWriter stdout = new PrintWriter(System.out, true); int read = 0; byte[] data = new byte[1024]; ZipEntry entry; try { ZipInputStream in = new ZipInputStream(new FileInputStream(zipPath)); stdout.println(zipPath); while ((entry = in.getNextEntry()) != null) { if (entry.getMethod() == ZipEntry.DEFLATED) { stdout.println(" Inflating: " + entry.getName()); } else { stdout.println(" Extracting: " + entry.getName()); } FileOutputStream out = new FileOutputStream(destDir + File.separator + entry.getName()); while ((read = in.read(data, 0, 1024)) != -1) { out.write(data, 0, read); } out.close(); } in.close(); stdout.println(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public static InputSource openInputSource(String resource) { InputSource src = null; URL url = findResource(resource); if (url != null) { try { InputStream in = url.openStream(); src = new InputSource(in); src.setSystemId(url.toExternalForm()); } catch (IOException e) { } } return src; } Code Sample 2: @SuppressWarnings("unchecked") private Map<String, Object> _request(String method, String path, Map<String, Object> body, JSONRecognizer... recognizers) throws IOException, TwinException { String uri = url + path; HttpRequest request; if (body == null) { BasicHttpRequest r = new BasicHttpRequest(method, uri); request = r; } else { BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, uri); StringEntity entity; try { entity = new StringEntity(JSON.encode(body), "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } entity.setContentType("application/json; charset=utf-8"); r.setEntity(entity); request = r; } HttpClient client = getClient(); try { HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request); HttpEntity entity = response.getEntity(); if (entity == null) return null; String contentType = entity.getContentType().getValue(); boolean isJson = (contentType != null) && ("application/json".equals(contentType) || contentType.startsWith("application/json;")); String result = null; InputStream in = entity.getContent(); try { Reader r = new InputStreamReader(in, "UTF-8"); StringBuilder sb = new StringBuilder(); char[] buf = new char[256]; int read; while ((read = r.read(buf, 0, buf.length)) >= 0) sb.append(buf, 0, read); r.close(); result = sb.toString(); } finally { try { in.close(); } catch (Exception e) { } } int code = response.getStatusLine().getStatusCode(); if (code >= 400) { if (isJson) { try { throw deserializeException((Map<String, Object>) JSON.decode(result)); } catch (IllegalArgumentException e) { throw TwinError.UnknownError.create("Couldn't parse error response: \n" + result, e); } } if (code == 404) throw TwinError.UnknownCommand.create("Got server response " + code + " for request " + uri); else throw TwinError.UnknownError.create("Got server response " + code + " for request " + uri + "\nBody is " + result); } if (!isJson) throw TwinError.UnknownError.create("Got wrong content type " + contentType + " for request " + uri + "\nBody is " + result); try { return (Map<String, Object>) JSON.decode(result, recognizers); } catch (Exception e) { throw TwinError.UnknownError.create("Malformed JSON result for request " + uri + ": \nBody is " + result, e); } } catch (ClientProtocolException e) { throw new IOException(e); } }
00
Code Sample 1: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getroutes/1"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetClient_", "<jsonobject> \n " + json.toString() + " \n </jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray = json.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringAgent = nameArray.getJSONObject(i).getString("Agent"); tempStringClient = nameArray.getJSONObject(i).getString("Client"); tempStringRoute = nameArray.getJSONObject(i).getString("Route"); tempStringZone = nameArray.getJSONObject(i).getString("Zone"); Log.i("_GetClient_", "<Agent" + i + ">" + tempStringAgent + "</Agent" + i + ">\n"); Log.i("_GetClient_", "<Client" + i + ">" + tempStringClient + "</Client" + i + ">\n"); Log.i("_GetClient_", "<Route" + i + ">" + tempStringRoute + "</Route" + i + ">\n"); Log.i("_GetClient_", "<Zone" + i + ">" + tempStringZone + "</Zone" + i + ">\n"); this.dm.insertIntoClients(tempStringAgent, tempStringClient, tempStringRoute, tempStringZone); tempString = nameArray.getJSONObject(i).getString("Client") + "\n" + nameArray.getJSONObject(i).getString("Route") + "\n" + nameArray.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, orderTimeStamps)); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public final void testT4CClientWriter() throws Exception { InputStream is = ClassLoader.getSystemResourceAsStream(this.testFileName); T4CClientReader reader = new T4CClientReader(is, rc); File tmpFile = File.createTempFile("barde", ".log", this.tmpDir); System.out.println("tmp=" + tmpFile.getAbsolutePath()); T4CClientWriter writer = new T4CClientWriter(new FileOutputStream(tmpFile), rc); for (Message m = reader.read(); m != null; m = reader.read()) writer.write(m); writer.close(); InputStream fa = ClassLoader.getSystemResourceAsStream(this.testFileName); FileInputStream fb = new FileInputStream(tmpFile); for (int ba = fa.read(); ba != -1; ba = fa.read()) assertEquals(ba, fb.read()); }
11
Code Sample 1: public void copy(String sourcePath, String targetPath) throws IOException { File sourceFile = new File(sourcePath); File targetFile = new File(targetPath); FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(sourceFile); fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) fileOutputStream.write(buffer, 0, bytesRead); } finally { if (fileInputStream != null) try { fileInputStream.close(); } catch (IOException exception) { JOptionPane.showMessageDialog(null, AcideLanguageManager.getInstance().getLabels().getString("s265") + sourcePath, AcideLanguageManager.getInstance().getLabels().getString("s266"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog().error(exception.getMessage()); } if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException exception) { JOptionPane.showMessageDialog(null, AcideLanguageManager.getInstance().getLabels().getString("s267") + targetPath, AcideLanguageManager.getInstance().getLabels().getString("268"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog().error(exception.getMessage()); } } } Code Sample 2: private void copyFile(String path) { try { File srcfile = new File(srcdir, path); File destfile = new File(destdir, path); File parent = destfile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } FileInputStream fis = new FileInputStream(srcfile); FileOutputStream fos = new FileOutputStream(destfile); int bytes_read = 0; byte buffer[] = new byte[512]; while ((bytes_read = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytes_read); } fis.close(); fos.close(); } catch (IOException e) { throw new BuildException("Error while copying file " + path); } }
00
Code Sample 1: public void updateUserInfo(AuthSession authSession, AuthUserExtendedInfo infoAuth) { log.info("Start update auth"); PreparedStatement ps = null; DatabaseAdapter db = null; try { db = DatabaseAdapter.getInstance(); String sql = "update WM_AUTH_USER " + "set " + "ID_FIRM=?, IS_USE_CURRENT_FIRM=?, " + "ID_HOLDING=?, IS_HOLDING=? " + "WHERE ID_AUTH_USER=? "; ps = db.prepareStatement(sql); if (infoAuth.getAuthInfo().getCompanyId() == null) { ps.setNull(1, Types.INTEGER); ps.setInt(2, 0); } else { ps.setLong(1, infoAuth.getAuthInfo().getCompanyId()); ps.setInt(2, infoAuth.getAuthInfo().isCompany() ? 1 : 0); } if (infoAuth.getAuthInfo().getHoldingId() == null) { ps.setNull(3, Types.INTEGER); ps.setInt(4, 0); } else { ps.setLong(3, infoAuth.getAuthInfo().getHoldingId()); ps.setInt(4, infoAuth.getAuthInfo().isHolding() ? 1 : 0); } ps.setLong(5, infoAuth.getAuthInfo().getAuthUserId()); ps.executeUpdate(); processDeletedRoles(db, infoAuth); processNewRoles(db, infoAuth.getRoles(), infoAuth.getAuthInfo().getAuthUserId()); db.commit(); } catch (Throwable e) { try { if (db != null) db.rollback(); } catch (Exception e001) { } final String es = "Error add user auth"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(db, ps); ps = null; db = null; log.info("End update auth"); } } Code Sample 2: public void search() throws Exception { URL searchurl = new URL("" + "http://www.ncbi.nlm.nih.gov/blast/Blast.cgi" + "?CMD=Put" + "&DATABASE=" + this.database + "&PROGRAM=" + this.program + "&QUERY=" + this.sequence.seqString()); BufferedReader reader = new BufferedReader(new InputStreamReader(searchurl.openStream(), "UTF-8")); String line = ""; while ((line = reader.readLine()) != null) { if (line.contains("Request ID")) this.rid += line.substring(70, 81); } reader.close(); }
00
Code Sample 1: protected void discoverFactories() { DataSourceRegistry registry = this; try { ClassLoader loader = DataSetURI.class.getClassLoader(); Enumeration<URL> urls; if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { if (s.trim().length() > 0) { List<String> extensions = null; List<String> mimeTypes = null; String factoryClassName = s; try { Class c = Class.forName(factoryClassName); DataSourceFactory f = (DataSourceFactory) c.newInstance(); try { Method m = c.getMethod("extensions", new Class[0]); extensions = (List<String>) m.invoke(f, new Object[0]); } catch (NoSuchMethodException ex) { } catch (InvocationTargetException ex) { ex.printStackTrace(); } try { Method m = c.getMethod("mimeTypes", new Class[0]); mimeTypes = (List<String>) m.invoke(f, new Object[0]); } catch (NoSuchMethodException ex) { } catch (InvocationTargetException ex) { ex.printStackTrace(); } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } if (extensions != null) { for (String e : extensions) { registry.registerExtension(factoryClassName, e, null); } } if (mimeTypes != null) { for (String m : mimeTypes) { registry.registerMimeType(factoryClassName, m); } } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void process() { try { update("Shutdown knowledge base ...", 0); DBHelper.shutdownDB(); update("Shutdown knowledge base ...", 9); String zipDir = P.DIR.getPKBDataPath(); update("Backup in progress ...", 10); List<String> fileList = getFilesToZip(zipDir); File file = new File(fileName); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(file)); byte[] readBuffer = new byte[2156]; int bytesIn = 0; for (int i = 0; i < fileList.size(); i++) { String filePath = fileList.get(i); File f = new File(filePath); FileInputStream fis = new FileInputStream(f); String zipEntryName = f.getPath().substring(zipDir.length() + 1); ZipEntry anEntry = new ZipEntry(zipEntryName); zout.putNextEntry(anEntry); while ((bytesIn = fis.read(readBuffer)) != -1) { zout.write(readBuffer, 0, bytesIn); } fis.close(); int percentage = (int) Math.round((i + 1) * 80.0 / fileList.size()); update("Backup in progress ...", 10 + percentage); } zout.close(); update("Restart knowledge base ...", 91); DBHelper.startDB(); update("Backup is done!", 100); } catch (Exception ex) { ex.printStackTrace(); update("Error occurs during backup!", 100); } }
00
Code Sample 1: public void copyFile(File sourceFile, File destFile) throws IOException { Log.level3("Copying " + sourceFile.getPath() + " to " + destFile.getPath()); 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(); } } Code Sample 2: HttpURLConnection getHttpURLConnection(String bizDocToExecute, boolean doom, boolean cmt) { StringBuffer servletURL = new StringBuffer(); servletURL.append(getBaseServletURL()); servletURL.append("?_BIZVIEW=").append(bizDocToExecute); if (doom) { servletURL.append("&_DOOM=TRUE"); } if (cmt) { servletURL.append("&_CMT=TRUE"); } Map<String, Object> inputParms = getInputParams(); if (inputParms != null) { Set<Entry<String, Object>> entrySet = inputParms.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); String value = entry.getValue().toString(); servletURL.append("&").append(name).append("=").append(value); } } HttpURLConnection connection = null; try { URL url = new URL(servletURL.toString()); connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Assert.fail("Failed to connect to the test servlet: " + e); } return connection; }
00
Code Sample 1: void getAddress(String lat, String lag) { try { URL url = new URL("http://maps.google.cn/maps/geo?key=abcdefg&q=" + lat + "," + lag); InputStream inputStream = url.openConnection().getInputStream(); InputStreamReader inputReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufReader = new BufferedReader(inputReader); String line = "", lines = ""; while ((line = bufReader.readLine()) != null) { lines += line; } if (!lines.equals("")) { JSONObject jsonobject = new JSONObject(lines); JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark").toString()); for (int i = 0; i < jsonArray.length(); i++) { mTextView.setText(mTextView.getText() + "\n" + jsonArray.getJSONObject(i).getString("address")); } } } catch (Exception e) { ; } } Code Sample 2: protected void copyFile(String from, String to, String workingDirectory) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File f = new File(monitorCallShellScriptUrl.getFile()); String directoryPath = f.getAbsolutePath(); String fileName = from; InputStream in = null; if (directoryPath.indexOf(".jar!") > -1) { URL urlJar = new URL(directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!'))); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); fileName = je.getName(); in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } else { in = new FileInputStream(f); } File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) fos.write(nextChar); fos.flush(); fos.close(); try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
11
Code Sample 1: public void updateProfile() throws ClassNotFoundException, SQLException { Connection connection = null; PreparedStatement ps1 = null; PreparedStatement ps2 = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(this.url); connection.setAutoCommit(false); String query2 = "UPDATE customers SET password=? WHERE name=?"; String query3 = "UPDATE customers_profile " + "SET first_name=?,middle_name=?,last_name=?,address1=?" + ",address2=?,city=?,post_box=?,email=?,country=? WHERE name=?"; ps1 = connection.prepareStatement(query3); ps2 = connection.prepareStatement(query2); ps1.setString(1, this.firstName); ps1.setString(2, this.middleName); ps1.setString(3, this.lastName); ps1.setString(4, this.address1); ps1.setString(5, this.address2); ps1.setString(6, this.city); ps1.setString(7, this.postBox); ps1.setString(8, this.email); ps1.setString(9, this.country); ps1.setString(10, this.name); ps2.setString(1, this.password); ps2.setString(2, this.name); ps1.executeUpdate(); ps2.executeUpdate(); } catch (Exception ex) { connection.rollback(); } finally { try { this.connection.close(); } catch (Exception ex) { } try { ps1.close(); } catch (Exception ex) { } try { ps2.close(); } catch (Exception ex) { } } } Code Sample 2: protected String doIt() throws java.lang.Exception { StringBuffer sql = null; int no = 0; String clientCheck = " AND AD_Client_ID=" + m_AD_Client_ID; String[] strFields = new String[] { "Value", "Name", "Description", "DocumentNote", "Help", "UPC", "SKU", "Classification", "ProductType", "Discontinued", "DiscontinuedBy", "ImageURL", "DescriptionURL" }; for (int i = 0; i < strFields.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(strFields[i]).append(" = (SELECT ").append(strFields[i]).append(" FROM M_Product p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product p WHERE " + strFields[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + strFields[i] + " - default from existing Product=" + no); } } String[] numFields = new String[] { "C_UOM_ID", "M_Product_Category_ID", "Volume", "Weight", "ShelfWidth", "ShelfHeight", "ShelfDepth", "UnitsPerPallet", "M_Product_Family_ID" }; for (int i = 0; i < numFields.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFields[i]).append(" = (SELECT ").append(numFields[i]).append(" FROM M_Product p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product p WHERE " + numFields[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFields[i] + " default from existing Product=" + no); } } String[] strFieldsPO = new String[] { "UPC", "PriceEffective", "VendorProductNo", "VendorCategory", "Manufacturer", "Discontinued", "DiscontinuedBy" }; for (int i = 0; i < strFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(strFieldsPO[i]).append(" = (SELECT ").append(strFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product_PO p WHERE " + strFieldsPO[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + strFieldsPO[i] + " default from existing Product PO=" + no); } } String[] numFieldsPO = new String[] { "C_UOM_ID", "C_Currency_ID", "RoyaltyAmt", "Order_Min", "Order_Pack", "CostPerOrder", "DeliveryTime_Promised" }; for (int i = 0; i < numFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFieldsPO[i]).append(" = (SELECT ").append(numFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product_PO p WHERE " + numFieldsPO[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFieldsPO[i] + " default from existing Product PO=" + no); } } numFieldsPO = new String[] { "PriceList", "PricePO" }; for (int i = 0; i < numFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFieldsPO[i]).append(" = (SELECT ").append(numFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND (").append(numFieldsPO[i]).append(" IS NULL OR ").append(numFieldsPO[i]).append("=0)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFieldsPO[i] + " default from existing Product PO=" + no); } } sql = new StringBuffer("UPDATE I_Product i " + "SET X12DE355 = " + "(SELECT X12DE355 FROM C_UOM u WHERE u.IsDefault='Y' AND u.AD_Client_ID IN (0,i.AD_Client_ID) AND ROWNUM=1) " + "WHERE X12DE355 IS NULL AND C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set UOM Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET C_UOM_ID = (SELECT C_UOM_ID FROM C_UOM u WHERE u.X12DE355=i.X12DE355 AND u.AD_Client_ID IN (0,i.AD_Client_ID)) " + "WHERE C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - Set UOM=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid UOM, ' " + "WHERE C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid UOM=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET ProductCategory_Value=(SELECT Value FROM M_Product_Category" + " WHERE IsDefault='Y' AND AD_Client_ID=").append(m_AD_Client_ID).append(" AND ROWNUM=1) " + "WHERE ProductCategory_Value IS NULL AND M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set Category Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET M_Product_Category_ID=(SELECT M_Product_Category_ID FROM M_Product_Category c" + " WHERE i.ProductCategory_Value=c.Value AND i.AD_Client_ID=c.AD_Client_ID) " + "WHERE M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - Set Category=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid ProdCategorty,' " + "WHERE M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid Category=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET ISO_Code=(SELECT ISO_Code FROM C_Currency c" + " INNER JOIN C_AcctSchema a ON (a.C_Currency_ID=c.C_Currency_ID)" + " INNER JOIN AD_ClientInfo fo ON (a.C_AcctSchema_ID=fo.C_AcctSchema1_ID)" + " WHERE fo.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_Currency_ID IS NULL AND ISO_Code IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set Currency Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET C_Currency_ID=(SELECT C_Currency_ID FROM C_Currency c" + " WHERE i.ISO_Code=c.ISO_Code AND c.AD_Client_ID IN (0,i.AD_Client_ID)) " + "WHERE C_Currency_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt- Set Currency=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Currency,' " + "WHERE C_Currency_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid Currency=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid ProductType,' " + "WHERE ProductType NOT IN ('I','S')" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid ProductType=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Value not unique,' " + "WHERE I_IsImported<>'Y'" + " AND Value IN (SELECT Value FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY Value HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique Value=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=UPC not unique,' " + "WHERE I_IsImported<>'Y'" + " AND UPC IN (SELECT UPC FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY UPC HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique UPC=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Mandatory Value,' " + "WHERE Value IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - No Mandatory Value=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET VendorProductNo=Value " + "WHERE C_BPartner_ID IS NOT NULL AND VendorProductNo IS NULL" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - VendorProductNo Set to Value=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=VendorProductNo not unique,' " + "WHERE I_IsImported<>'Y'" + " AND C_BPartner_ID IS NOT NULL" + " AND (C_BPartner_ID, VendorProductNo) IN " + " (SELECT C_BPartner_ID, VendorProductNo FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY C_BPartner_ID, VendorProductNo HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique VendorProductNo=" + no); } int C_TaxCategory_ID = 0; try { PreparedStatement pstmt = DB.prepareStatement("SELECT C_TaxCategory_ID FROM C_TaxCategory WHERE IsDefault='Y'" + clientCheck); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { C_TaxCategory_ID = rs.getInt(1); } rs.close(); pstmt.close(); } catch (SQLException e) { throw new Exception("doIt - TaxCategory", e); } log.fine("doIt - C_TaxCategory_ID=" + C_TaxCategory_ID); int noInsert = 0; int noUpdate = 0; int noInsertPO = 0; int noUpdatePO = 0; log.fine("doIt - start inserting/updating ..."); sql = new StringBuffer("SELECT I_Product_ID, M_Product_ID, C_BPartner_ID " + "FROM I_Product WHERE I_IsImported='N'").append(clientCheck); Connection conn = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); try { PreparedStatement pstmt_insertProduct = conn.prepareStatement("INSERT INTO M_Product (M_Product_ID," + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + "Value,Name,Description,DocumentNote,Help," + "UPC,SKU,C_UOM_ID,IsSummary,M_Product_Category_ID,C_TaxCategory_ID," + "ProductType,ImageURL,DescriptionURL,M_Product_Family_ID) " + "SELECT ?," + "AD_Client_ID,AD_Org_ID,'Y',CURRENT_TIMESTAMP,CreatedBy,CURRENT_TIMESTAMP,UpdatedBy," + "Value,Name,Description,DocumentNote,Help," + "UPC,SKU,C_UOM_ID,'N',M_Product_Category_ID," + C_TaxCategory_ID + "," + "ProductType,ImageURL,DescriptionURL,M_Product_Category_ID " + "FROM I_Product " + "WHERE I_Product_ID=?"); PreparedStatement pstmt_updateProduct = conn.prepareStatement("UPDATE M_PRODUCT " + "SET Value=aux.value" + ",Name=aux.Name" + ",Description=aux.Description" + ",DocumentNote=aux.DocumentNote" + ",Help=aux.Help" + ",UPC=aux.UPC" + ",SKU=aux.SKU" + ",C_UOM_ID=aux.C_UOM_ID" + ",M_Product_Category_ID=aux.M_Product_Category_ID" + ",Classification=aux.Classification" + ",ProductType=aux.ProductType" + ",Volume=aux.Volume" + ",Weight=aux.Weight" + ",ShelfWidth=aux.ShelfWidth" + ",ShelfHeight=aux.ShelfHeight" + ",ShelfDepth=aux.ShelfDepth" + ",UnitsPerPallet=aux.UnitsPerPallet" + ",Discontinued=aux.Discontinued" + ",DiscontinuedBy=aux.DiscontinuedBy" + ",Updated=current_timestamp" + ",UpdatedBy=aux.UpdatedBy" + " from (SELECT Value,Name,Description,DocumentNote,Help,UPC,SKU,C_UOM_ID,M_Product_Category_ID,Classification,ProductType,Volume,Weight,ShelfWidth,ShelfHeight,ShelfDepth,UnitsPerPallet,Discontinued,DiscontinuedBy,UpdatedBy FROM I_Product WHERE I_Product_ID=?) as aux" + " WHERE M_Product_ID=?"); PreparedStatement pstmt_updateProductPO = conn.prepareStatement("UPDATE M_Product_PO " + "SET IsCurrentVendor='Y'" + ",C_UOM_ID=aux1.C_UOM_ID" + ",C_Currency_ID=aux1.C_Currency_ID" + ",UPC=aux1.UPC" + ",PriceList=aux1.PriceList" + ",PricePO=aux1.PricePO" + ",RoyaltyAmt=aux1.RoyaltyAmt" + ",PriceEffective=aux1.PriceEffective" + ",VendorProductNo=aux1.VendorProductNo" + ",VendorCategory=aux1.VendorCategory" + ",Manufacturer=aux1.Manufacturer" + ",Discontinued=aux1.Discontinued" + ",DiscontinuedBy=aux1.DiscontinuedBy" + ",Order_Min=aux1.Order_Min" + ",Order_Pack=aux1.Order_Pack" + ",CostPerOrder=aux1.CostPerOrder" + ",DeliveryTime_Promised=aux1.DeliveryTime_Promised" + ",Updated=current_timestamp" + ",UpdatedBy=aux1.UpdatedBy" + " from (SELECT 'Y',C_UOM_ID,C_Currency_ID,UPC,PriceList,PricePO,RoyaltyAmt,PriceEffective,VendorProductNo,VendorCategory,Manufacturer,Discontinued,DiscontinuedBy,Order_Min,Order_Pack,CostPerOrder,DeliveryTime_Promised,UpdatedBy FROM I_Product WHERE I_Product_ID=?) as aux1" + " WHERE M_Product_ID=? AND C_BPartner_ID=?"); PreparedStatement pstmt_insertProductPO = conn.prepareStatement("INSERT INTO M_Product_PO (M_Product_ID,C_BPartner_ID, " + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + "IsCurrentVendor,C_UOM_ID,C_Currency_ID,UPC," + "PriceList,PricePO,RoyaltyAmt,PriceEffective," + "VendorProductNo,VendorCategory,Manufacturer," + "Discontinued,DiscontinuedBy,Order_Min,Order_Pack," + "CostPerOrder,DeliveryTime_Promised) " + "SELECT ?,?, " + "AD_Client_ID,AD_Org_ID,'Y',d,CreatedBy,CURRENT_TIMESTAMP,UpdatedBy," + "'Y',C_UOM_ID,C_Currency_ID,UPC," + "PriceList,PricePO,RoyaltyAmt,PriceEffective," + "VendorProductNo,VendorCategory,Manufacturer," + "Discontinued,DiscontinuedBy,Order_Min,Order_Pack," + "CostPerOrder,DeliveryTime_Promised " + "FROM I_Product " + "WHERE I_Product_ID=?"); PreparedStatement pstmt_setImported = conn.prepareStatement("UPDATE I_Product SET I_IsImported='Y', M_Product_ID=?, " + "Updated=CURRENT_TIMESTAMP, Processed='Y' WHERE I_Product_ID=?"); PreparedStatement pstmt = DB.prepareStatement(sql.toString()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int I_Product_ID = rs.getInt(1); int M_Product_ID = rs.getInt(2); int C_BPartner_ID = rs.getInt(3); boolean newProduct = M_Product_ID == 0; log.fine("I_Product_ID=" + I_Product_ID + ", M_Product_ID=" + M_Product_ID + ", C_BPartner_ID=" + C_BPartner_ID); if (newProduct) { M_Product_ID = DB.getNextID(m_AD_Client_ID, "M_Product", null); pstmt_insertProduct.setInt(1, M_Product_ID); pstmt_insertProduct.setInt(2, I_Product_ID); try { no = pstmt_insertProduct.executeUpdate(); log.finer("Insert Product = " + no); noInsert++; } catch (SQLException ex) { log.warning("Insert Product - " + ex.toString()); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Insert Product: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } else { pstmt_updateProduct.setInt(1, I_Product_ID); pstmt_updateProduct.setInt(2, M_Product_ID); try { no = pstmt_updateProduct.executeUpdate(); log.finer("Update Product = " + no); noUpdate++; } catch (SQLException ex) { log.warning("Update Product - " + ex.toString()); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Update Product: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } if (C_BPartner_ID != 0) { no = 0; if (!newProduct) { pstmt_updateProductPO.setInt(1, I_Product_ID); pstmt_updateProductPO.setInt(2, M_Product_ID); pstmt_updateProductPO.setInt(3, C_BPartner_ID); try { no = pstmt_updateProductPO.executeUpdate(); log.finer("Update Product_PO = " + no); noUpdatePO++; } catch (SQLException ex) { log.warning("Update Product_PO - " + ex.toString()); noUpdate--; conn.rollback(); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Update Product_PO: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } if (no == 0) { pstmt_insertProductPO.setInt(1, M_Product_ID); pstmt_insertProductPO.setInt(2, C_BPartner_ID); pstmt_insertProductPO.setInt(3, I_Product_ID); try { no = pstmt_insertProductPO.executeUpdate(); log.finer("Insert Product_PO = " + no); noInsertPO++; } catch (SQLException ex) { log.warning("Insert Product_PO - " + ex.toString()); noInsert--; conn.rollback(); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Insert Product_PO: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } } pstmt_setImported.setInt(1, M_Product_ID); pstmt_setImported.setInt(2, I_Product_ID); no = pstmt_setImported.executeUpdate(); conn.commit(); } rs.close(); pstmt.close(); pstmt_insertProduct.close(); pstmt_updateProduct.close(); pstmt_insertProductPO.close(); pstmt_updateProductPO.close(); pstmt_setImported.close(); conn.close(); conn = null; } catch (SQLException e) { try { if (conn != null) { conn.close(); } conn = null; } catch (SQLException ex) { } log.log(Level.SEVERE, "doIt", e); throw new Exception("doIt", e); } finally { if (conn != null) { conn.close(); } conn = null; } sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='N', Updated=CURRENT_TIMESTAMP " + "WHERE I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); StringBuffer infoReturn = new StringBuffer(""); infoReturn.append("<tr><td>@Errors@</td><td>").append(no).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@: @Inserted@</td><td>").append(noInsert).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@: @Updated@</td><td>").append(noUpdate).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@ @Purchase@: @Inserted@</td><td>").append(noInsertPO).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@ @Purchase@: @Updated@</td><td>").append(noUpdatePO).append("</td></tr>"); return infoReturn.toString(); }
00
Code Sample 1: @Override public void executeInterruptible() { encodingTerminated = false; File destinationFile = null; try { Runtime runtime = Runtime.getRuntime(); IconAndFileListElement element; while ((element = getNextFileElement()) != null) { File origFile = element.getFile(); destinationFile = new File(encodeFileCard.getDestinationFolder().getValue(), origFile.getName()); if (!destinationFile.getParentFile().exists()) { destinationFile.getParentFile().mkdirs(); } actualFileLabel.setText(origFile.getName()); actualFileModel.setMaximum((int) origFile.length()); actualFileModel.setValue(0); int bitrate; synchronized (bitratePattern) { Matcher bitrateMatcher = bitratePattern.matcher(encodeFileCard.getBitrate().getValue()); bitrateMatcher.find(); bitrate = Integer.parseInt(bitrateMatcher.group(1)); } List<String> command = new LinkedList<String>(); command.add(encoderFile.getCanonicalPath()); command.add("--mp3input"); command.add("-m"); command.add("j"); String sampleFreq = Settings.getSetting("encode.sample.freq"); if (Util.isNotEmpty(sampleFreq)) { command.add("--resample"); command.add(sampleFreq); } QualityElement quality = (QualityElement) ((JComboBox) encodeFileCard.getQuality().getValueComponent()).getSelectedItem(); command.add("-q"); command.add(Integer.toString(quality.getValue())); command.add("-b"); command.add(Integer.toString(bitrate)); command.add("--cbr"); command.add("-"); command.add(destinationFile.getCanonicalPath()); if (LOG.isDebugEnabled()) { StringBuilder commandLine = new StringBuilder(); boolean first = true; for (String part : command) { if (!first) commandLine.append(" "); commandLine.append(part); first = false; } LOG.debug("Command line: " + commandLine.toString()); } encodingProcess = runtime.exec(command.toArray(new String[0])); lastPosition = 0l; InputStream fileStream = null; try { fileStream = new PositionNotifierInputStream(new FileInputStream(origFile), origFile.length(), 2048, this); IOUtils.copy(fileStream, encodingProcess.getOutputStream()); encodingProcess.getOutputStream().close(); } finally { IOUtils.closeQuietly(fileStream); if (LOG.isDebugEnabled()) { InputStream processOut = null; try { processOut = encodingProcess.getInputStream(); StringWriter sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process output stream:\n" + sw); IOUtils.closeQuietly(processOut); processOut = encodingProcess.getErrorStream(); sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process error stream:\n" + sw); } finally { IOUtils.closeQuietly(processOut); } } } int result = encodingProcess.waitFor(); encodingProcess = null; if (result != 0) { LOG.warn("Encoder process returned error code " + result); } if (Boolean.parseBoolean(encodeFileCard.getCopyTag().getValue())) { MP3File mp3Input = new MP3File(origFile); MP3File mp3Output = new MP3File(destinationFile); boolean write = false; if (mp3Input.hasID3v2tag()) { ID3v2Tag id3v2Tag = new ID3v2Tag(); for (ID3v2Frame frame : mp3Input.getID3v2tag().getAllframes()) { id3v2Tag.addFrame(frame); } mp3Output.setID3v2tag(id3v2Tag); write = true; } if (mp3Input.hasID3v11tag()) { mp3Output.setID3v11tag(mp3Input.getID3v11tag()); write = true; } if (write) mp3Output.write(); } } actualFileLabel.setText(Messages.getString("operations.file.encode.execute.actualfile.terminated")); actualFileModel.setValue(actualFileModel.getMaximum()); } catch (Exception e) { LOG.error("Cannot encode files", e); if (!(e instanceof IOException && encodingTerminated)) MainWindowInterface.showError(e); if (destinationFile != null) destinationFile.delete(); } } 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: public static Document getDocument(String string, String defaultCharset) { DOMParser parser = new DOMParser(); try { URL url = new URL(string); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(10000); con.setUseCaches(false); con.addRequestProperty("_", UUID.randomUUID().toString()); String contentType = con.getContentType(); if (contentType == null) { return null; } String charsetSearch = contentType.replaceFirst("(?i).*charset=(.*)", "$1"); String contentTypeCharset = con.getContentEncoding(); BufferedReader reader = null; if (!contentType.equals(charsetSearch)) { contentTypeCharset = charsetSearch; } if (contentTypeCharset == null) { reader = new BufferedReader(new InputStreamReader(con.getInputStream(), defaultCharset)); } else { reader = new BufferedReader(new InputStreamReader(con.getInputStream(), contentTypeCharset)); } InputSource source = new InputSource(reader); parser.setFeature("http://xml.org/sax/features/namespaces", false); parser.parse(source); Document document = parser.getDocument(); String metaTagCharset = getMetaTagCharset(document); if (metaTagCharset != null && !metaTagCharset.equals(contentTypeCharset)) { HttpURLConnection reconnection = (HttpURLConnection) url.openConnection(); reconnection.setConnectTimeout(10000); reconnection.setUseCaches(false); reconnection.addRequestProperty("_", UUID.randomUUID().toString()); reader = new BufferedReader(new InputStreamReader(reconnection.getInputStream(), metaTagCharset)); source = new InputSource(reader); parser.setFeature("http://xml.org/sax/features/namespaces", false); parser.parse(source); document = parser.getDocument(); } reader.close(); return document; } catch (DOMException e) { if (!"UTF-8".equals(defaultCharset)) { return getDocument(string, "UTF-8"); } return null; } catch (Exception ex) { return null; } } Code Sample 2: public void testPreparedStatement0009() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } pstmt.close(); assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); con.commit(); pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); pstmt.close(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, rowsToAdd); con.commit(); stmt.close(); con.setAutoCommit(true); }
11
Code Sample 1: private void write(File src, File dst, byte id3v1Tag[], byte id3v2HeadTag[], byte id3v2TailTag[]) throws IOException { if (src == null || !src.exists()) throw new IOException(Debug.getDebug("missing src", src)); if (!src.getName().toLowerCase().endsWith(".mp3")) throw new IOException(Debug.getDebug("src not mp3", src)); if (dst == null) throw new IOException(Debug.getDebug("missing dst", dst)); if (dst.exists()) { dst.delete(); if (dst.exists()) throw new IOException(Debug.getDebug("could not delete dst", dst)); } boolean hasId3v1 = new MyID3v1().hasID3v1(src); long id3v1Length = hasId3v1 ? ID3_V1_TAG_LENGTH : 0; long id3v2HeadLength = new MyID3v2().findID3v2HeadLength(src); long id3v2TailLength = new MyID3v2().findID3v2TailLength(src, hasId3v1); OutputStream os = null; InputStream is = null; try { dst.getParentFile().mkdirs(); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); if (!skipId3v2Head && !skipId3v2 && id3v2HeadTag != null) os.write(id3v2HeadTag); is = new FileInputStream(src); is = new BufferedInputStream(is); is.skip(id3v2HeadLength); long total_to_read = src.length(); total_to_read -= id3v1Length; total_to_read -= id3v2HeadLength; total_to_read -= id3v2TailLength; byte buffer[] = new byte[1024]; long total_read = 0; while (total_read < total_to_read) { int remainder = (int) (total_to_read - total_read); int readSize = Math.min(buffer.length, remainder); int read = is.read(buffer, 0, readSize); if (read <= 0) throw new IOException("unexpected EOF"); os.write(buffer, 0, read); total_read += read; } if (!skipId3v2Tail && !skipId3v2 && id3v2TailTag != null) os.write(id3v2TailTag); if (!skipId3v1 && id3v1Tag != null) os.write(id3v1Tag); } finally { try { if (is != null) is.close(); } catch (Throwable e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (Throwable e) { Debug.debug(e); } } } Code Sample 2: protected void download(URL url, File destination, long beginRange, long endRange, long totalFileSize, boolean appendToFile) throws DownloadException { System.out.println(" DOWNLOAD REQUEST RECEIVED " + url.toString() + " \n\tbeginRange : " + beginRange + " - EndRange " + endRange + " \n\t to -> " + destination.getAbsolutePath()); try { if (destination.exists() && !appendToFile) { destination.delete(); } if (!destination.exists()) destination.createNewFile(); GetMethod get = new GetMethod(url.toString()); HttpClient httpClient = new HttpClient(); Header rangeHeader = new Header(); rangeHeader.setName("Range"); rangeHeader.setValue("bytes=" + beginRange + "-" + endRange); get.setRequestHeader(rangeHeader); httpClient.executeMethod(get); int statusCode = get.getStatusCode(); if (statusCode >= 400 && statusCode < 500) throw new DownloadException("The file does not exist in this location : message from server -> " + statusCode + " " + get.getStatusText()); InputStream input = get.getResponseBodyAsStream(); OutputStream output = new FileOutputStream(destination, appendToFile); try { int length = IOUtils.copy(input, output); System.out.println(" Length : " + length); } finally { input.close(); output.flush(); output.close(); } } catch (Exception e) { e.printStackTrace(); logger.error("Unable to figure out the length of the file from the URL : " + e.getMessage()); throw new DownloadException("Unable to figure out the length of the file from the URL : " + e.getMessage()); } }
00
Code Sample 1: public static String hash(final String text) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return Sha1.convertToHex(sha1hash); } catch (NoSuchAlgorithmException e) { return null; } catch (UnsupportedEncodingException e) { return null; } } Code Sample 2: private static String sort(final String item) { final char[] chars = item.toCharArray(); for (int i = 1; i < chars.length; i++) { for (int j = 0; j < chars.length - 1; j++) { if (chars[j] > chars[j + 1]) { final char temp = chars[j]; chars[j] = chars[j + 1]; chars[j + 1] = temp; } } } return String.valueOf(chars); }
00
Code Sample 1: public static String readRss(String feed, int num) { InputStream stream = null; try { feed = appendParam(feed, "num", "" + num); System.out.println("feed=" + feed); URL url = new URL(feed); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", RSS_USER_AGENT); stream = connection.getInputStream(); return CFileHelper.readInputStream(stream); } catch (Exception e) { throw new CException(e); } finally { CFileHelper.closeStream(stream); } } Code Sample 2: private static void getFileFtp(String user, String password, String host, int port, String fileName, String location) throws Exception { Log.info("\nretrieve " + fileName + NEW_LINE); FTPClient client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("FTP fail to connect"); } if (!client.login(user, password)) { throw new Exception("FTP fail to login"); } try { File locationFile = new File(location); File dest = new File(locationFile, fileName); if (dest.exists()) { dest.delete(); } else { locationFile.mkdirs(); } boolean status = client.changeWorkingDirectory("/"); Log.info("chdir-status:" + status + NEW_LINE); client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); client.setFileType(FTPClient.BINARY_FILE_TYPE); client.enterLocalActiveMode(); InputStream in = client.retrieveFileStream(fileName); if (in == null) { Log.error("Input stream is null\n"); throw new Exception("Fail to retrieve file " + fileName); } Thread.sleep(3000); saveInputStreamToFile(in, new File(location, fileName)); } finally { client.disconnect(); } }
00
Code Sample 1: public static String encryption(String oldPass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(oldPass.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } String pass32 = buf.toString(); return pass32; } Code Sample 2: public long copyFileWithPaths(String userBaseDir, String sourcePath, String destinPath) throws Exception { if (userBaseDir.endsWith(sep)) { userBaseDir = userBaseDir.substring(0, userBaseDir.length() - sep.length()); } String file1FullPath = new String(); if (sourcePath.startsWith(sep)) { file1FullPath = new String(userBaseDir + sourcePath); } else { file1FullPath = new String(userBaseDir + sep + sourcePath); } String file2FullPath = new String(); if (destinPath.startsWith(sep)) { file2FullPath = new String(userBaseDir + destinPath); } else { file2FullPath = new String(userBaseDir + sep + destinPath); } long plussQuotaSize = 0; BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File fileordir = new File(file1FullPath); if (fileordir.exists()) { if (fileordir.isFile()) { File file2 = new File(file2FullPath); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } if (fileordir.isDirectory()) { String[] entryList = fileordir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String file1FullPathEntry = new String(file1FullPath.concat(entryList[pos])); String file2FullPathEntry = new String(file2FullPath.concat(entryList[pos])); File file2 = new File(file2FullPathEntry); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPathEntry), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPathEntry), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Source file or dir not exist ! file1FullPath = (" + file1FullPath + ")"); } return plussQuotaSize; }
11
Code Sample 1: public static String md5(String input) { byte[] temp; try { MessageDigest messageDigest; messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(input.getBytes()); temp = messageDigest.digest(); } catch (Exception e) { return null; } return MyUtils.byte2HexStr(temp); } Code Sample 2: public String encripta(String senha) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return senha; } }
00
Code Sample 1: public static boolean insert(final Departamento ObjDepartamento) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into departamento " + "(nome, sala, telefone, id_orgao)" + " values (?, ?, ?, ?)"; pst = c.prepareStatement(sql); pst.setString(1, ObjDepartamento.getNome()); pst.setString(2, ObjDepartamento.getSala()); pst.setString(3, ObjDepartamento.getTelefone()); pst.setInt(4, (ObjDepartamento.getOrgao()).getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[DepartamentoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } } Code Sample 2: public boolean openConnection(String url, Properties props) throws SQLException { try { Class.forName(RunConfig.getInstance().getDriverNameJDBC()); if (url == null) url = RunConfig.getInstance().getConnectionUrlJDBC(); connection = DriverManager.getConnection(url, props); if (statementTable == null) statementTable = new Hashtable<String, PreparedStatement>(); if (resultTable == null) resultTable = new Hashtable<String, ResultSet>(); clearStatus(); return true; } catch (Exception e) { setStatus(e); return false; } }
00
Code Sample 1: public void doFilter(final ServletRequest arg0, final ServletResponse arg1, final FilterChain arg2) throws IOException, ServletException { if (!this.init) { final HttpServletResponse response = Dynamic._.Cast(arg1); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Mainfilter not initialized."); return; } if (this.mainFilter != null) { try { URL url = this.context.getResource("/WEB-INF/classes/log4j.properties"); URLConnection uc = url.openConnection(); if (uc.getLastModified() != lastLoadLog4j) { lastLoadLog4j = uc.getLastModified(); try { uc.getInputStream().close(); } catch (Exception ignore) { } PropertyConfigurator.configure(url); } else { try { uc.getInputStream().close(); } catch (Exception ignore) { } } } catch (final Exception e) { } this.mainFilter.doFilter(arg0, arg1); } else { final HttpServletResponse response = Dynamic._.Cast(arg1); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Mainfilter bad setup."); } } Code Sample 2: public static void readDefault() { ClassLoader l = Skeleton.class.getClassLoader(); URL url = l.getResource("weka/core/parser/JFlex/skeleton.default"); if (url == null) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } try { InputStreamReader reader = new InputStreamReader(url.openStream()); readSkel(new BufferedReader(reader)); } catch (IOException e) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } }
00
Code Sample 1: public static boolean copyDataToNewTable(EboContext p_eboctx, String srcTableName, String destTableName, String where, boolean log, int mode) throws boRuntimeException { srcTableName = srcTableName.toUpperCase(); destTableName = destTableName.toUpperCase(); Connection cn = null; Connection cndef = null; boolean ret = false; try { boolean srcexists = false; boolean destexists = false; final InitialContext ic = new InitialContext(); cn = p_eboctx.getConnectionData(); cndef = p_eboctx.getConnectionDef(); PreparedStatement pstm = cn.prepareStatement("SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME=?"); pstm.setString(1, srcTableName); ResultSet rslt = pstm.executeQuery(); if (rslt.next()) { srcexists = true; } rslt.close(); pstm.setString(1, destTableName); rslt = pstm.executeQuery(); if (rslt.next()) { destexists = true; } if (!destexists) { rslt.close(); pstm.close(); pstm = cn.prepareStatement("SELECT VIEW_NAME FROM USER_VIEWS WHERE VIEW_NAME=?"); pstm.setString(1, destTableName); rslt = pstm.executeQuery(); if (rslt.next()) { CallableStatement cstm = cn.prepareCall("DROP VIEW " + destTableName); cstm.execute(); cstm.close(); } } rslt.close(); pstm.close(); if (srcexists && !destexists) { if (log) { logger.finest(LoggerMessageLocalizer.getMessage("CREATING_AND_COPY_DATA_FROM") + " [" + srcTableName + "] " + LoggerMessageLocalizer.getMessage("TO") + " [" + destTableName + "]"); } CallableStatement cstm = cn.prepareCall("CREATE TABLE " + destTableName + " AS SELECT * FROM " + srcTableName + " " + (((where != null) && (where.length() > 0)) ? (" WHERE " + where) : "")); cstm.execute(); cstm.close(); if (log) { logger.finest(LoggerMessageLocalizer.getMessage("UPDATING_NGTDIC")); } cn.commit(); ret = true; } else if (srcexists && destexists) { if (log) { logger.finest(LoggerMessageLocalizer.getMessage("COPY_DATA_FROM") + " [" + srcTableName + "] " + LoggerMessageLocalizer.getMessage("TO") + " [" + destTableName + "]"); } PreparedStatement pstm2 = cn.prepareStatement("SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? "); pstm2.setString(1, destTableName); ResultSet rslt2 = pstm2.executeQuery(); StringBuffer fields = new StringBuffer(); PreparedStatement pstm3 = cn.prepareStatement("SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? and COLUMN_NAME=?"); while (rslt2.next()) { pstm3.setString(1, srcTableName); pstm3.setString(2, rslt2.getString(1)); ResultSet rslt3 = pstm3.executeQuery(); if (rslt3.next()) { if (fields.length() > 0) { fields.append(','); } fields.append('"').append(rslt2.getString(1)).append('"'); } rslt3.close(); } pstm3.close(); rslt2.close(); pstm2.close(); CallableStatement cstm; int recs = 0; if ((mode == 0) || (mode == 1)) { cstm = cn.prepareCall("INSERT INTO " + destTableName + "( " + fields.toString() + " ) ( SELECT " + fields.toString() + " FROM " + srcTableName + " " + (((where != null) && (where.length() > 0)) ? (" WHERE " + where) : "") + ")"); recs = cstm.executeUpdate(); cstm.close(); if (log) { logger.finest(LoggerMessageLocalizer.getMessage("DONE") + " [" + recs + "] " + LoggerMessageLocalizer.getMessage("RECORDS_COPIED")); } } cn.commit(); ret = true; } } catch (Exception e) { try { cn.rollback(); } catch (Exception z) { throw new boRuntimeException("boBuildDB.moveTable", "BO-1304", z); } throw new boRuntimeException("boBuildDB.moveTable", "BO-1304", e); } finally { try { cn.close(); } catch (Exception e) { } try { cndef.close(); } catch (Exception e) { } } return ret; } Code Sample 2: public String md5(Value request) throws FaultException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(request.strValue().getBytes("UTF8")); } catch (UnsupportedEncodingException e) { throw new FaultException("UnsupportedOperation", e); } catch (NoSuchAlgorithmException e) { throw new FaultException("UnsupportedOperation", e); } int radix; if ((radix = request.getFirstChild("radix").intValue()) < 2) { radix = 16; } return new BigInteger(1, md.digest()).toString(radix); }
11
Code Sample 1: private void trainSRLParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractSRLParser labeler = null; AbstractDecoder[] decoder = null; if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); labeler = new SRLParser(flag, s_featureXml); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); labeler = new SRLParser(flag, t_xml, s_lexiconFiles); } else if (flag == SRLParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train boost"); decoder = new AbstractDecoder[m_model.length]; for (int i = 0; i < decoder.length; i++) decoder[i] = new OneVsAllDecoder((OneVsAllModel) m_model[i]); labeler = new SRLParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = new SRLReader(s_trainFile, true); DepTree tree; int n; labeler.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { labeler.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- labeling: " + n); if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("- labeling"); labeler.saveTags(s_lexiconFiles); t_xml = labeler.getSRLFtrXml(); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE || flag == SRLParser.FLAG_TRAIN_BOOST) { a_yx = labeler.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); for (String lexicaFile : s_lexiconFiles) { zout.putArchiveEntry(new JarArchiveEntry(lexicaFile)); IOUtils.copy(new FileInputStream(lexicaFile), zout); zout.closeArchiveEntry(); } if (flag == SRLParser.FLAG_TRAIN_INSTANCE) t_map = labeler.getSRLFtrMap(); } } Code Sample 2: public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); }
11
Code Sample 1: private static void addFileToZip(String path, String srcFile, ZipOutputStream zip, String prefix, String suffix) throws Exception { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip, prefix, suffix); } else { if (isFileNameMatch(folder.getName(), prefix, suffix)) { FileInputStream fis = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); IOUtils.copy(fis, zip); fis.close(); } } } Code Sample 2: public void render(ServiceContext serviceContext) throws Exception { if (serviceContext.getTemplateName() == null) throw new Exception("no Template defined for service: " + serviceContext.getServiceInfo().getRefName()); File f = new File(serviceContext.getTemplateName()); serviceContext.getResponse().setContentLength((int) f.length()); InputStream in = new FileInputStream(f); IOUtils.copy(in, serviceContext.getResponse().getOutputStream(), 0, (int) f.length()); in.close(); }
11
Code Sample 1: public static byte[] expandPasswordToKey(String password, int keyLen, byte[] salt) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] mdBuf = new byte[digLen]; byte[] key = new byte[keyLen]; int cnt = 0; while (cnt < keyLen) { if (cnt > 0) { md5.update(mdBuf); } md5.update(password.getBytes()); md5.update(salt); md5.digest(mdBuf, 0, digLen); int n = ((digLen > (keyLen - cnt)) ? keyLen - cnt : digLen); System.arraycopy(mdBuf, 0, key, cnt, n); cnt += n; } return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKey: " + e); } } Code Sample 2: private static void userAuth(String challenge) throws IOException { try { MessageDigest md = MessageDigest.getInstance("BrokenMD4"); String passwd = null; if (System.getProperty("jarsync.password.gui") != null) { JPasswordField pass = new JPasswordField(); JPanel panel = new JPanel(new GridLayout(2, 1)); panel.add(new JLabel("Password:")); panel.add(pass); JOptionPane.showMessageDialog(null, panel, remoteUser + '@' + remoteHost + "'s Password", JOptionPane.QUESTION_MESSAGE); passwd = new String(pass.getPassword()); } else { System.out.print(remoteUser + '@' + remoteHost + "'s password: "); passwd = Util.readLine(System.in); System.out.println(); } md.update(new byte[4]); md.update(passwd.getBytes("US-ASCII")); md.update(challenge.getBytes("US-ASCII")); byte[] response = md.digest(); Util.writeASCII(out, remoteUser + " " + Util.base64(response) + '\n'); out.flush(); } catch (NoSuchAlgorithmException nsae) { throw new IOException("could not create message digest."); } }