label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; } Code Sample 2: public void _saveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String subcmd) throws WebAssetException, Exception { long maxsize = 50; long maxwidth = 3000; long maxheight = 3000; long minheight = 10; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); try { UploadPortletRequest uploadReq = PortalUtil.getUploadPortletRequest(req); String parent = ParamUtil.getString(req, "parent"); int countFiles = ParamUtil.getInteger(req, "countFiles"); int fileCounter = 0; Folder folder = (Folder) InodeFactory.getInode(parent, Folder.class); _checkUserPermissions(folder, user, PERMISSION_WRITE); String userId = user.getUserId(); String customMessage = "Some file does not match the filters specified by the folder: "; boolean filterError = false; for (int k = 0; k < countFiles; k++) { File file = new File(); String title = ParamUtil.getString(req, "title" + k); String friendlyName = ParamUtil.getString(req, "friendlyName" + k); Date publishDate = new Date(); String fileName = ParamUtil.getString(req, "fileName" + k); fileName = checkMACFileName(fileName); if (!FolderFactory.matchFilter(folder, fileName)) { customMessage += fileName + ", "; filterError = true; continue; } if (fileName.length() > 0) { String mimeType = FileFactory.getMimeType(fileName); String URI = folder.getPath() + fileName; String suffix = UtilMethods.getFileExtension(fileName); file.setTitle(title); file.setFileName(fileName); file.setFriendlyName(friendlyName); file.setPublishDate(publishDate); file.setModUser(userId); InodeFactory.saveInode(file); String filePath = FileFactory.getRealAssetsRootPath(); new java.io.File(filePath).mkdir(); java.io.File uploadedFile = uploadReq.getFile("uploadedFile" + k); Logger.debug(this, "bytes" + uploadedFile.length()); file.setSize((int) uploadedFile.length() - 2); file.setMimeType(mimeType); Host host = HostFactory.getCurrentHost(httpReq); Identifier ident = IdentifierFactory.getIdentifierByURI(URI, host); String message = ""; if ((FileFactory.existsFileName(folder, fileName))) { InodeFactory.deleteInode(file); message = "The uploaded file " + fileName + " already exists in this folder"; SessionMessages.add(req, "custommessage", message); } else { String fileInodePath = String.valueOf(file.getInode()); if (fileInodePath.length() == 1) { fileInodePath = fileInodePath + "0"; } fileInodePath = fileInodePath.substring(0, 1) + java.io.File.separator + fileInodePath.substring(1, 2); new java.io.File(filePath + java.io.File.separator + fileInodePath.substring(0, 1)).mkdir(); new java.io.File(filePath + java.io.File.separator + fileInodePath).mkdir(); java.io.File f = new java.io.File(filePath + java.io.File.separator + fileInodePath + java.io.File.separator + file.getInode() + "." + suffix); java.io.FileOutputStream fout = new java.io.FileOutputStream(f); FileChannel outputChannel = fout.getChannel(); FileChannel inputChannel = new java.io.FileInputStream(uploadedFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); outputChannel.force(false); outputChannel.close(); inputChannel.close(); Logger.debug(this, "SaveFileAction New File in =" + filePath + java.io.File.separator + fileInodePath + java.io.File.separator + file.getInode() + "." + suffix); if (suffix.equals("jpg") || suffix.equals("gif")) { com.dotmarketing.util.Thumbnail.resizeImage(filePath + java.io.File.separator + fileInodePath + java.io.File.separator, String.valueOf(file.getInode()), suffix); int height = javax.imageio.ImageIO.read(f).getHeight(); file.setHeight(height); Logger.debug(this, "File height=" + height); int width = javax.imageio.ImageIO.read(f).getWidth(); file.setWidth(width); Logger.debug(this, "File width=" + width); long size = (f.length() / 1024); WebAssetFactory.createAsset(file, userId, folder); } else { WebAssetFactory.createAsset(file, userId, folder); } WorkingCache.addToWorkingAssetToCache(file); _setFilePermissions(folder, file, user); fileCounter += 1; if ((subcmd != null) && subcmd.equals(com.dotmarketing.util.Constants.PUBLISH)) { try { PublishFactory.publishAsset(file, httpReq); if (fileCounter > 1) { SessionMessages.add(req, "message", "message.file_asset.save"); } else { SessionMessages.add(req, "message", "message.fileupload.save"); } } catch (WebAssetException wax) { Logger.error(this, wax.getMessage(), wax); SessionMessages.add(req, "error", "message.webasset.published.failed"); } } } } } if (filterError) { customMessage = customMessage.substring(0, customMessage.lastIndexOf(",")); SessionMessages.add(req, "custommessage", customMessage); } } catch (IOException e) { Logger.error(this, "Exception saving file: " + e.getMessage()); throw new ActionException(e.getMessage()); } }
11
Code Sample 1: private String getCoded(String pass) { String passSecret = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(pass.getBytes("UTF8")); byte s[] = m.digest(); for (int i = 0; i < s.length; i++) { passSecret += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6); } } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return passSecret; } Code Sample 2: public static String hash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest.getName()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } } Code Sample 2: public void run(IAction action) { Shell shell = new Shell(); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } }
00
Code Sample 1: void IconmenuItem5_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (getPath() != null && !getPath().equals("")) { jFileChooser1.setCurrentDirectory(new File(getPath())); jFileChooser1.setSelectedFile(new File(getPath())); } if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getPath().lastIndexOf(separator); String imgName = getPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setPath(newPath); if (getDefaultPath() == null || getDefaultPath().equals("")) { String msgString = "E' stata selezionata un'immagine da associare all'IconShape, ma non e' " + "stata selezionata ancora nessun'immagine di default. Imposto quella scelta anche come " + "immagine di default?"; if (JOptionPane.showConfirmDialog(null, msgString.substring(0, Math.min(msgString.length(), getFatherPanel().MAX_DIALOG_MSG_SZ)), "choose one", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { setDefaultPath(newPath); createDefaultImage(); } } createImage(); } } Code Sample 2: public Source get_source(String pageURL, Boolean checkInBase) { URL url; URLConnection conn; Reader inReader; Source source = null; String LastModified = ""; Boolean updateData = false; try { url = new URL(pageURL); conn = url.openConnection(); conn.setRequestProperty("Accept-Charset", "windows-1251"); if (checkInBase) { for (int i = 0; ; i++) { String name = conn.getHeaderFieldKey(i); String value = conn.getHeaderField(i); if (name == null && value == null) { break; } if ("Last-Modified".equals(name)) { LastModified = value; } } Ini.rs = Ini.stmt.executeQuery("select count(1) as qwe from " + " PUBLIC.PAGES " + "where url = '" + pageURL + "';"); Ini.rs.next(); if (Ini.rs.getInt("qwe") == 0) { Ini.stmt.executeUpdate("insert into PUBLIC.PAGES(url, lastUpdateDate) " + " values('" + pageURL + "', " + "'" + LastModified + "'" + ");"); } else { Ini.rs = Ini.stmt.executeQuery("select lastUpdateDate from " + " PUBLIC.PAGES " + "where url = '" + pageURL + "';"); Ini.rs.next(); if (!Ini.rs.getString("lastUpdateDate").equals(LastModified)) { updateData = true; } else { return null; } } } inReader = new InputStreamReader(conn.getInputStream(), "windows-1251"); source = new Source(inReader); source.setLogger(null); source.fullSequentialParse(); if (updateData) { Ini.stmt.executeUpdate("delete from PUBLIC.LINKDATA " + "where id in (" + "select id from PUBLIC.PAGES " + "where url = '" + pageURL + "'" + ")"); Ini.stmt.executeUpdate("delete from PUBLIC.PAGES " + "where url = '" + pageURL + "';"); Ini.stmt.executeUpdate("insert into PUBLIC.PAGES " + " values('" + pageURL + "', " + "'" + LastModified + "'" + ");"); } } catch (Exception ex) { Ini.logger.fatal("Error: ", ex); } return source; }
11
Code Sample 1: public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; } Code Sample 2: private void transform(CommandLine commandLine) throws IOException { Reader reader; if (commandLine.hasOption('i')) { reader = createFileReader(commandLine.getOptionValue('i')); } else { reader = createStandardInputReader(); } Writer writer; if (commandLine.hasOption('o')) { writer = createFileWriter(commandLine.getOptionValue('o')); } else { writer = createStandardOutputWriter(); } String mapRule = commandLine.getOptionValue("m"); try { SrxTransformer transformer = new SrxAnyTransformer(); Map<String, Object> parameterMap = new HashMap<String, Object>(); if (mapRule != null) { parameterMap.put(Srx1Transformer.MAP_RULE_NAME, mapRule); } transformer.transform(reader, writer, parameterMap); } finally { cleanupReader(reader); cleanupWriter(writer); } }
11
Code Sample 1: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); } Code Sample 2: public void executaAlteracoes() { Album album = Album.getAlbum(); Photo[] fotos = album.getFotos(); Photo f; int ultimoFotoID = -1; int albumID = album.getAlbumID(); sucesso = true; PainelWebFotos.setCursorWait(true); albumID = recordAlbumData(album, albumID); sucesso = recordFotoData(fotos, ultimoFotoID, albumID); String caminhoAlbum = Util.getFolder("albunsRoot").getPath() + File.separator + albumID; File diretorioAlbum = new File(caminhoAlbum); if (!diretorioAlbum.isDirectory()) { if (!diretorioAlbum.mkdir()) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.7]/ERRO: diretorio " + caminhoAlbum + " n�o pode ser criado. abortando"); return; } } for (int i = 0; i < fotos.length; i++) { f = fotos[i]; if (f.getCaminhoArquivo().length() > 0) { try { FileChannel canalOrigem = new FileInputStream(f.getCaminhoArquivo()).getChannel(); FileChannel canalDestino = new FileOutputStream(caminhoAlbum + File.separator + f.getFotoID() + ".jpg").getChannel(); canalDestino.transferFrom(canalOrigem, 0, canalOrigem.size()); canalOrigem = null; canalDestino = null; } catch (Exception e) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.8]/ERRO: " + e); sucesso = false; } } } prepareThumbsAndFTP(fotos, albumID, caminhoAlbum); prepareExtraFiles(album, caminhoAlbum); fireChangesToGUI(fotos); dispatchAlbum(); PainelWebFotos.setCursorWait(false); }
00
Code Sample 1: public void testSimpleHttpPostsWithContentLength() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } Code Sample 2: private void copyFile(File sourceFile, File destFile) throws IOException { if (log.isDebugEnabled()) { log.debug("CopyFile : Source[" + sourceFile.getAbsolutePath() + "] Dest[" + destFile.getAbsolutePath() + "]"); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: public void testSimpleHttpPostsChunked() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(20000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
00
Code Sample 1: 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(); } if (!socket.isConnected()) { 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()); } version = determineVersion(); writer.setTargetVersion(version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); } Code Sample 2: public void doCompress(File[] files, File out, List<String> excludedKeys) { Map<String, File> map = new HashMap<String, File>(); String parent = FilenameUtils.getBaseName(out.getName()); for (File f : files) { CompressionUtil.list(f, parent, map, excludedKeys); } if (!map.isEmpty()) { FileOutputStream fos = null; ArchiveOutputStream aos = null; InputStream is = null; try { fos = new FileOutputStream(out); aos = getArchiveOutputStream(fos); for (Map.Entry<String, File> entry : map.entrySet()) { File file = entry.getValue(); ArchiveEntry ae = getArchiveEntry(file, entry.getKey()); aos.putArchiveEntry(ae); if (file.isFile()) { IOUtils.copy(is = new FileInputStream(file), aos); IOUtils.closeQuietly(is); is = null; } aos.closeArchiveEntry(); } aos.finish(); } catch (IOException ex) { ex.printStackTrace(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(aos); IOUtils.closeQuietly(fos); } } }
11
Code Sample 1: private void readParameterTable() { if (this.parameters != null) return; parameters = new GribPDSParameter[NPARAMETERS]; int center; int subcenter; int number; try { BufferedReader br; if (filename != null && filename.length() > 0) { GribPDSParamTable tab = (GribPDSParamTable) fileTabMap.get(filename); if (tab != null) { this.parameters = tab.parameters; return; } } if (url != null) { InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); } else { br = new BufferedReader(new FileReader("tables\\" + filename)); } String line = br.readLine(); String[] tableDefArr = SmartStringArray.split(":", line); center = Integer.parseInt(tableDefArr[1].trim()); subcenter = Integer.parseInt(tableDefArr[2].trim()); number = Integer.parseInt(tableDefArr[3].trim()); while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() == 0 || line.startsWith("//")) continue; GribPDSParameter parameter = new GribPDSParameter(); tableDefArr = SmartStringArray.split(":", line); parameter.number = Integer.parseInt(tableDefArr[0].trim()); parameter.name = tableDefArr[1].trim(); if (tableDefArr[2].indexOf('[') == -1) { parameter.description = parameter.unit = tableDefArr[2].trim(); } else { String[] arr2 = SmartStringArray.split("[", tableDefArr[2]); parameter.description = arr2[0].trim(); parameter.unit = arr2[1].substring(0, arr2[1].lastIndexOf(']')).trim(); } if (!this.setParameter(parameter)) { System.err.println("Warning, bad parameter ignored (" + filename + "): " + parameter.toString()); } } if (filename != null && filename.length() > 0) { GribPDSParamTable loadedTable = new GribPDSParamTable(filename, center, subcenter, number, this.parameters); fileTabMap.put(filename, loadedTable); } } catch (IOException ioError) { System.err.println("An error occurred in GribPDSParamTable while " + "trying to open the parameter table " + filename + " : " + ioError); } } Code Sample 2: public boolean load() { if (getFilename() != null && getFilename().length() > 0) { try { File file = new File(PreferencesManager.getDirectoryLocation("macros") + File.separator + getFilename()); URL url = file.toURL(); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); String macro_text = ""; while (line != null) { macro_text = macro_text.concat(line); line = br.readLine(); if (line != null) { macro_text = macro_text.concat(System.getProperty("line.separator")); } } code = macro_text; } catch (Exception e) { System.err.println("Exception at StoredMacro.load(): " + e.toString()); return false; } } return true; }
00
Code Sample 1: protected int doExecuteUpdate(PreparedStatement statement) throws SQLException { connection.setAutoCommit(isAutoCommit()); int rs = -1; try { lastError = null; rs = statement.executeUpdate(); if (!isAutoCommit()) connection.commit(); } catch (Exception ex) { if (!isAutoCommit()) { lastError = ex; connection.rollback(); LogUtils.log(Level.SEVERE, "Transaction is being rollback. Error: " + ex.toString()); } } finally { if (statement != null) statement.close(); } return rs; } Code Sample 2: @Override public void render(Output output) throws IOException { output.setStatus(headersFile.getStatusCode(), headersFile.getStatusMessage()); for (Entry<String, Set<String>> header : headersFile.getHeadersMap().entrySet()) { Set<String> values = header.getValue(); for (String value : values) { output.addHeader(header.getKey(), value); } } if (file != null) { InputStream inputStream = new FileInputStream(file); try { output.open(); OutputStream out = output.getOutputStream(); IOUtils.copy(inputStream, out); } finally { inputStream.close(); output.close(); } } }
11
Code Sample 1: public void apop(String user, char[] secret) throws IOException, POP3Exception { if (timestamp == null) { throw new CommandNotSupportedException("No timestamp from server - APOP not possible"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(timestamp.getBytes()); if (secret == null) secret = new char[0]; byte[] digest = md.digest(new String(secret).getBytes("ISO-8859-1")); mutex.lock(); sendCommand("APOP", new String[] { user, digestToString(digest) }); POP3Response response = readSingleLineResponse(); if (!response.isOK()) { throw new POP3Exception(response); } state = TRANSACTION; } catch (NoSuchAlgorithmException e) { throw new POP3Exception("Installed JRE doesn't support MD5 - APOP not possible"); } finally { mutex.release(); } } Code Sample 2: public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
00
Code Sample 1: public static File copyFile(File file) { File src = file; File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } Code Sample 2: private void saveCampaign() throws HeadlessException { try { dbConnection.setAutoCommit(false); dbConnection.setSavepoint(); String sql = "UPDATE campaigns SET " + "queue = ? ," + "adjustRatioPeriod = ?, " + "asterisk = ?, " + "context = ?," + "extension = ?, " + "dialContext = ?, " + "dialPrefix = ?," + "dialTimeout = ?, " + "dialingMethod = ?," + "dialsPerFreeResourceRatio = ?, " + "maxIVRChannels = ?, " + "maxDialingThreads = ?," + "maxDialsPerFreeResourceRatio = ?," + "minDialsPerFreeResourceRatio = ?, " + "maxTries = ?, " + "firstRetryAfterMinutes = ?," + "secondRetryAfterMinutes = ?, " + "furtherRetryAfterMinutes = ?, " + "startDate = ?, " + "endDate = ?," + "popUpURL = ?, " + "contactBatchSize = ?, " + "retriesBatchPct = ?, " + "reschedulesBatchPct = ?, " + "allowReschedule = ?, " + "rescheduleToOnself = ?, " + "script = ?," + "agentsCanUpdateContacts = ?, " + "hideContactFields = ?, " + "afterCallWork = ?, " + "reserveAvailableAgents = ?, " + "useDNCList = ?, " + "enableAgentDNC = ?, " + "contactsFilter = ?, " + "DNCTo = ?," + "callRecordingPolicy = ?, " + "callRecordingPercent = ?, " + "callRecordingMaxAge = ?, " + "WHERE name = ?"; PreparedStatement statement = dbConnection.prepareStatement(sql); int i = 1; statement.setString(i++, txtQueue.getText()); statement.setInt(i++, Integer.valueOf(txtAdjustRatio.getText())); statement.setString(i++, ""); statement.setString(i++, txtContext.getText()); statement.setString(i++, txtExtension.getText()); statement.setString(i++, txtDialContext.getText()); statement.setString(i++, txtDialPrefix.getText()); statement.setInt(i++, 30000); statement.setInt(i++, cboDialingMethod.getSelectedIndex()); statement.setFloat(i++, Float.valueOf(txtInitialDialingRatio.getText())); statement.setInt(i++, Integer.valueOf(txtMaxIVRChannels.getText())); statement.setInt(i++, Integer.valueOf(txtDialLimit.getText())); statement.setFloat(i++, Float.valueOf(txtMaxDialingRatio.getText())); statement.setFloat(i++, Float.valueOf(txtMinDialingRatio.getText())); statement.setInt(i++, Integer.valueOf(txtMaxRetries.getText())); statement.setInt(i++, Integer.valueOf(txtFirstRetry.getText())); statement.setInt(i++, Integer.valueOf(txtSecondRetry.getText())); statement.setInt(i++, Integer.valueOf(txtFurtherRetries.getText())); statement.setDate(i++, Date.valueOf(txtStartDate.getText())); statement.setDate(i++, Date.valueOf(txtEndDate.getText())); statement.setString(i++, txtURL.getText()); statement.setInt(i++, Integer.valueOf(txtContactBatchSize.getText())); statement.setInt(i++, Integer.valueOf(txtRetryBatchPct.getText())); statement.setInt(i++, Integer.valueOf(txtRescheduleBatchPct.getText())); statement.setInt(i++, chkAgentCanReschedule.isSelected() ? 1 : 0); statement.setInt(i++, chkAgentCanRescheduleSelf.isSelected() ? 1 : 0); statement.setString(i++, txtScript.getText()); statement.setInt(i++, chkAgentCanUpdateContacts.isSelected() ? 1 : 0); statement.setString(i++, ""); statement.setInt(i++, Integer.valueOf(txtACW.getText())); statement.setInt(i++, Integer.valueOf(txtReserveAgents.getText())); statement.setInt(i++, cboDNCListPreference.getSelectedIndex()); statement.setInt(i++, 1); statement.setString(i++, ""); statement.setInt(i++, 0); statement.setInt(i++, cboRecordingPolicy.getSelectedIndex()); statement.setInt(i++, Integer.valueOf(txtRecordingPct.getText())); statement.setInt(i++, Integer.valueOf(txtRecordingMaxAge.getText())); statement.setString(i++, campaign); statement.executeUpdate(); dbConnection.commit(); } catch (SQLException ex) { try { dbConnection.rollback(); } catch (SQLException ex1) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex1); } JOptionPane.showMessageDialog(this.getRootPane(), ex.getLocalizedMessage(), "Error", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex); } }
00
Code Sample 1: @Override public void connect() throws IOException { URL url = getLocator().getURL(); if (url.getProtocol().equals("file")) { final String newUrlStr = URLUtils.createAbsoluteFileUrl(url.toExternalForm()); if (newUrlStr != null) { if (!newUrlStr.toString().equals(url.toExternalForm())) { logger.warning("Changing file URL to absolute for URL.openConnection, from " + url.toExternalForm() + " to " + newUrlStr); url = new URL(newUrlStr); } } } conn = url.openConnection(); if (!url.getProtocol().equals("ftp") && conn.getURL().getProtocol().equals("ftp")) { logger.warning("URL.openConnection() morphed " + url + " to " + conn.getURL()); throw new IOException("URL.openConnection() returned an FTP connection for a non-ftp url: " + url); } if (conn instanceof HttpURLConnection) { final HttpURLConnection huc = (HttpURLConnection) conn; huc.connect(); final int code = huc.getResponseCode(); if (!(code >= 200 && code < 300)) { huc.disconnect(); throw new IOException("HTTP response code: " + code); } logger.finer("URL: " + url); logger.finer("Response code: " + code); logger.finer("Full content type: " + conn.getContentType()); boolean contentTypeSet = false; if (stripTrailer(conn.getContentType()).equals("text/plain")) { final String ext = PathUtils.extractExtension(url.getPath()); if (ext != null) { final String result = MimeManager.getMimeType(ext); if (result != null) { contentTypeStr = ContentDescriptor.mimeTypeToPackageName(result); contentTypeSet = true; logger.fine("Received content type " + conn.getContentType() + "; overriding based on extension, to: " + result); } } } if (!contentTypeSet) contentTypeStr = ContentDescriptor.mimeTypeToPackageName(stripTrailer(conn.getContentType())); } else { conn.connect(); contentTypeStr = ContentDescriptor.mimeTypeToPackageName(conn.getContentType()); } contentType = new ContentDescriptor(contentTypeStr); sources = new URLSourceStream[1]; sources[0] = new URLSourceStream(); connected = true; } 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: public static void copyFile(File src, File dst) throws IOException { FileChannel sourceChannel = new FileInputStream(src).getChannel(); FileChannel destinationChannel = new FileOutputStream(dst).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileOutputStream lfosTargetFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfosTargetFile = new FileOutputStream(mstrTargetDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrSourceDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrSourceDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.retrieveFile(mstrFilename, lfosTargetFile)) { throw new Exception("Unable to download [ " + mstrSourceDirectory + "/" + mstrFilename + " to " + mstrTargetDirectory + File.separator + mstrFilename + " ] from server [ " + mstrRemoteServer + " ]"); } lfosTargetFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfosTargetFile != null) { try { lfosTargetFile.close(); } catch (Exception e) { } } } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public void filter(File source, File destination, MNamespace mNamespace) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(source)); BufferedWriter writer = new BufferedWriter(new FileWriter(destination)); int line = 0; int column = 0; Stack parseStateStack = new Stack(); parseStateStack.push(new ParseState(mNamespace)); for (Iterator i = codePieces.iterator(); i.hasNext(); ) { NamedCodePiece cp = (NamedCodePiece) i.next(); while (line < cp.getStartLine()) { line++; column = 0; writer.write(reader.readLine()); writer.newLine(); } while (column < cp.getStartPosition()) { writer.write(reader.read()); column++; } cp.write(writer, parseStateStack, column); while (line < cp.getEndLine()) { line++; column = 0; reader.readLine(); } while (column < cp.getEndPosition()) { column++; reader.read(); } } String data; while ((data = reader.readLine()) != null) { writer.write(data); writer.newLine(); } reader.close(); writer.close(); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public 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(); }
00
Code Sample 1: public static String upload_file(String sessionid, String localFilePath, String remoteTagPath) { String jsonstring = "If you see this message, there is some problem inside the function:upload_file()"; String srcPath = localFilePath; String uploadUrl = "https://s2.cloud.cm/rpc/json/?session_id=" + sessionid + "&c=Storage&m=upload_file&tag=" + remoteTagPath; String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end); dos.writeBytes(end); FileInputStream fis = new FileInputStream(srcPath); byte[] buffer = new byte[8192]; int count = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); jsonstring = br.readLine(); dos.close(); is.close(); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; } Code Sample 2: protected InputStream callApiMethod(String apiUrl, String xmlContent, String contentType, String method, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.setRequestMethod(method); request.setDoOutput(true); if (contentType != null) { request.setRequestProperty("Content-Type", contentType); } if (xmlContent != null) { PrintStream out = new PrintStream(new BufferedOutputStream(request.getOutputStream())); out.print(xmlContent); out.flush(); out.close(); } request.connect(); if (request.getResponseCode() != expected) { throw new BingMapsException(convertStreamToString(request.getErrorStream())); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingMapsException(e); } }
11
Code Sample 1: private void generateArchetype(final IProject project, final IDataModel model, final IProgressMonitor monitor, final boolean offline) throws CoreException, InterruptedException, IOException { if (getArchetypeArtifactId(model) != null) { final Properties properties = new Properties(); properties.put("archetypeArtifactId", getArchetypeArtifactId(model)); properties.put("archetypeGroupId", getArchetypeGroupId(model)); properties.put("archetypeVersion", getArchetypeVersion(model)); String artifact = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_ARTIFACT_ID); if (artifact == null || artifact.trim().length() == 0) { artifact = project.getName(); } properties.put("artifactId", artifact); String group = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_GROUP_ID); if (group == null || group.trim().length() == 0) { group = project.getName(); } properties.put("groupId", group); properties.put("version", model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_VERSION)); final StringBuffer sb = new StringBuffer(System.getProperty("user.home")).append(File.separator); sb.append(".m2").append(File.separator).append("repository"); final String local = sb.toString(); Logger.getLog().debug("Local Maven2 repository :: " + local); properties.put("localRepository", local); if (!offline) { final String sbRepos = getRepositories(); properties.put("remoteRepositories", sbRepos); } final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating project using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { String dfPom = getPomFile(group, artifact); ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (IOException e) { } } if (SiteManager.isHttpProxyEnable()) { addProxySettings(properties); } workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); String goalName = "archetype:create"; if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } goalName = updateGoal(goalName); workingCopy.setAttribute(ATTR_GOALS, goalName); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(monitor, workingCopy, project, timeout); monitor.setTaskName("Moving to workspace"); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), ArchetypePOMHelper.getProjectDirectory(project)); monitor.worked(1); performMavenInstall(monitor, project, offline); project.refreshLocal(2, monitor); } catch (final IOException ioe) { Logger.log(Logger.ERROR, "I/O exception. One probably solution is absence " + "of mvn2 archetypes or not the correct version, " + "in your local repository. Please, check existence " + "of this archetype."); Logger.getLog().error("I/O Exception arised creating mvn2 archetype", ioe); throw ioe; } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } } monitor.worked(1); } Code Sample 2: public static void copy(final File source, final File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); dest.setLastModified(source.lastModified()); } finally { close(in); close(out); } }
11
Code Sample 1: public static byte[] readResource(Class owningClass, String resourceName) { final URL url = getResourceUrl(owningClass, resourceName); if (null == url) { throw new MissingResourceException(owningClass.toString() + " key '" + resourceName + "'", owningClass.toString(), resourceName); } LOG.info("Loading resource '" + url.toExternalForm() + "' " + "from " + owningClass); final InputStream inputStream; try { inputStream = url.openStream(); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } return outputStream.toByteArray(); } Code Sample 2: public void write(File file) throws Exception { if (medooFile != null) { if (!medooFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(medooFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } }
00
Code Sample 1: public static InputStream getNotCacheResourceAsStream(final String fileName) { if ((fileName.indexOf("file:") >= 0) || (fileName.indexOf(":/") > 0)) { try { URL url = new URL(fileName); return new BufferedInputStream(url.openStream()); } catch (Exception e) { return null; } } return new ByteArrayInputStream(getNotCacheResource(fileName).getData()); } Code Sample 2: @Override public void testAction(ITestThread testThread) throws Throwable { try { final InputStream urlIn = new URL("http://jdistunit.sourceforge.net").openStream(); final int availableBytes = urlIn.available(); if (0 == availableBytes) { throw new IllegalStateException("Zero bytes on target host."); } in = new BufferedReader(new InputStreamReader(urlIn)); String line; while (null != (line = in.readLine())) { page.append(line); page.append('\n'); if (0 != lineDelay) { OS.sleep(lineDelay); } if (null != testThread && testThread.isActionStopped()) { break; } } } finally { if (null != in) { in.close(); in = null; } } }
11
Code Sample 1: public final synchronized boolean isValidLicenseFile() throws LicenseNotSetupException { if (!isSetup()) { throw new LicenseNotSetupException(); } boolean returnValue = false; Properties properties = getLicenseFile(); logger.debug("isValidLicenseFile: License to validate:"); logger.debug(properties); StringBuffer validationStringBuffer = new StringBuffer(); validationStringBuffer.append(LICENSE_KEY_KEY + ":" + properties.getProperty(LICENSE_KEY_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_STATUS_KEY + ":" + properties.getProperty(LICENSE_FILE_STATUS_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_USERS_KEY + ":" + properties.getProperty(LICENSE_FILE_USERS_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_MAC_KEY + ":" + properties.getProperty(LICENSE_FILE_MAC_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_HOST_NAME_KEY + ":" + properties.getProperty(LICENSE_FILE_HOST_NAME_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_OFFSET_KEY + ":" + properties.getProperty(LICENSE_FILE_OFFSET_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_EXP_DATE_KEY + ":" + properties.getProperty(LICENSE_FILE_EXP_DATE_KEY) + ","); validationStringBuffer.append(LICENSE_EXPIRES_KEY + ":" + properties.getProperty(LICENSE_EXPIRES_KEY)); logger.debug("isValidLicenseFile: Validation String Buffer: " + validationStringBuffer.toString()); String validationKey = (String) properties.getProperty(LICENSE_FILE_SHA_KEY); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(validationStringBuffer.toString().getBytes()); String newValidation = Base64.encode(messageDigest.digest()); if (newValidation.equals(validationKey)) { if (getMACAddress().equals(Settings.getInstance().getMACAddress())) { returnValue = true; } } } catch (Exception exception) { System.out.println("Exception in LicenseInstanceVO.isValidLicenseFile"); } return returnValue; } Code Sample 2: public String getHash(String key, boolean base64) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(key.getBytes()); if (base64) return new String(new Base64().encode(md.digest()), "UTF8"); else return new String(md.digest(), "UTF8"); }
11
Code Sample 1: public static String[] retrieveFasta(String id) throws Exception { URL url = new URL("http://www.uniprot.org/uniprot/" + id + ".fasta"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String header = reader.readLine(); StringBuffer seq = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { seq.append(line); } reader.close(); String[] first = header.split("OS="); return new String[] { id, first[0].split("\\s")[1], first[1].split("GN=")[0], seq.toString() }; } Code Sample 2: 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); } }
11
Code Sample 1: public static void unzipAndRemove(final String file) { String destination = file.substring(0, file.length() - 3); InputStream is = null; OutputStream os = null; try { is = new GZIPInputStream(new FileInputStream(file)); os = new FileOutputStream(destination); byte[] buffer = new byte[8192]; for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length); } catch (IOException e) { System.err.println("Fehler: Kann nicht entpacken " + file); } finally { if (os != null) try { os.close(); } catch (IOException e) { } if (is != null) try { is.close(); } catch (IOException e) { } } deleteFile(file); } Code Sample 2: private void saveFile(File destination) { InputStream in = null; OutputStream out = null; try { if (fileScheme) in = new BufferedInputStream(new FileInputStream(source.getPath())); else in = new BufferedInputStream(getContentResolver().openInputStream(source)); out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) out.write(buffer); Toast.makeText(this, R.string.saveas_file_saved, Toast.LENGTH_SHORT).show(); } catch (FileNotFoundException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
11
Code Sample 1: public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); } Code Sample 2: private void putAlgosFromJar(File jarfile, AlgoDir dir, Model model) throws FileNotFoundException, IOException { URLClassLoader urlLoader = new URLClassLoader(new URL[] { jarfile.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(jarfile)); JarEntry entry = jis.getNextJarEntry(); String name = null; String tmpdir = System.getProperty("user.dir") + File.separator + Application.getProperty("dir.tmp") + File.separator; byte[] buffer = new byte[1000]; while (entry != null) { name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); try { Class<?> cls = urlLoader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && ((cls.getModifiers() & Modifier.ABSTRACT) == 0)) { dir.addAlgorithm(cls); model.putClass(cls.getName(), cls); } else if (ISerializable.class.isAssignableFrom(cls)) { model.putClass(cls.getName(), cls); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else if (Constants.isAllowedImageType(name)) { int lastSep = name.lastIndexOf("/"); if (lastSep != -1) { String dirs = tmpdir + name.substring(0, lastSep); File d = new File(dirs); if (!d.exists()) d.mkdirs(); } String filename = tmpdir + name; File f = new File(filename); if (!f.exists()) { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); int read = -1; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.close(); } } entry = jis.getNextJarEntry(); } }
11
Code Sample 1: private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; } Code Sample 2: private void copy(File source, File target) throws IOException { FileChannel in = (new FileInputStream(source)).getChannel(); FileChannel out = (new FileOutputStream(target)).getChannel(); in.transferTo(0, source.length(), out); in.close(); out.close(); }
00
Code Sample 1: private void download(URL url, File outFile) throws IOException { System.out.println("Trying to download: " + url); InputStream in = null; OutputStream out = null; try { URLConnection conn = url.openConnection(); in = conn.getInputStream(); out = new BufferedOutputStream(new FileOutputStream(outFile)); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > -1) { out.write(buf, 0, len); } } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("Unable to close stream.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.error("Unable to close stream.", e); } } } } Code Sample 2: @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { long startTime = System.currentTimeMillis(); boolean validClient = true; boolean validSession = false; String sessionKey = req.getParameter("sid"); String storedKey = CLIENT_SESSION_KEYS.get(req.getRemoteAddr()); if (sessionKey != null && storedKey != null && sessionKey.equals(storedKey)) validSession = true; DataStore ds = DataStore.getConnection(); if (IPV6_DETECTED) { boolean doneWarning; synchronized (SJQServlet.class) { doneWarning = IPV6_WARNED; if (!IPV6_WARNED) IPV6_WARNED = true; } if (!doneWarning) LOG.warn("IPv6 interface detected; client restriction settings ignored [restrictions do not support IPv6 addresses]"); } else { String[] clntRestrictions = ds.getSetting("ValidClients", "").split(";"); List<IPMatcher> matchers = new ArrayList<IPMatcher>(); if (clntRestrictions.length == 1 && clntRestrictions[0].trim().length() == 0) { LOG.warn("All client connections are being accepted and processed, please consider setting up client restrictions in SJQ settings"); } else { for (String s : clntRestrictions) { s = s.trim(); try { matchers.add(new IPMatcher(s)); } catch (IPMatcherException e) { LOG.error("Invalid client restriction settings; client restrictions ignored!", e); matchers.clear(); break; } } validClient = matchers.size() > 0 ? false : true; for (IPMatcher m : matchers) { try { if (m.match(req.getRemoteAddr())) { validClient = true; break; } } catch (IPMatcherException e) { LOG.error("IPMatcherException", e); } } } } String clntProto = req.getParameter("proto"); if (clntProto == null || Integer.parseInt(clntProto) != SJQ_PROTO) throw new RuntimeException("Server is speaking protocol '" + SJQ_PROTO + "', but client is speaking protocol '" + clntProto + "'; install a client version that matches the server protocol version!"); resp.setHeader("Content-Type", "text/plain"); resp.setDateHeader("Expires", 0); resp.setDateHeader("Last-Modified", System.currentTimeMillis()); resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); resp.setHeader("Pragma", "no-cache"); String cmd = req.getParameter("cmd"); if (cmd == null) { DataStore.returnConnection(ds); return; } ActiveClientList list = ActiveClientList.getInstance(); BufferedWriter bw = new BufferedWriter(resp.getWriter()); if (cmd.equals("pop")) { if (!validClient) { LOG.warn("Client IP rejected: " + req.getRemoteAddr()); notAuthorized(resp, bw); } else { list.add(req.getRemoteHost()); ClientParser clnt = new ClientParser(new StringReader(ds.getClientConf(req.getRemoteHost()))); String offDay = clnt.getGlobalOption("OFFDAY"); String offHour = clnt.getGlobalOption("OFFHOUR"); Calendar now = Calendar.getInstance(); if (RangeInterpreter.inRange(now.get(Calendar.DAY_OF_WEEK), 1, 7, offDay) || RangeInterpreter.inRange(now.get(Calendar.HOUR_OF_DAY), 0, 23, offHour)) { LOG.warn("Client '" + req.getRemoteAddr() + "' currently disabled via OFFDAY/OFFHOUR settings."); bw.write("null"); } else { Task t = TaskQueue.getInstance().pop(req.getRemoteHost(), getPopCandidates(req.getRemoteHost(), clnt)); if (t == null) bw.write("null"); else { t.setResourcesUsed(Integer.parseInt(clnt.getTask(t.getTaskId()).getOption("RESOURCES"))); Object obj = null; if (t.getObjType().equals("media")) obj = Butler.SageApi.mediaFileAPI.GetMediaFileForID(Integer.parseInt(t.getObjId())); else if (t.getObjType().equals("sysmsg")) obj = SystemMessageUtils.getSysMsg(t.getObjId()); ClientTask cTask = clnt.getTask(t.getTaskId()); JSONObject jobj = cTask.toJSONObject(obj); String objType = null; try { if (jobj != null) objType = jobj.getString(Task.JSON_OBJ_TYPE); } catch (JSONException e) { throw new RuntimeException("Invalid ClienTask JSON object conversion!"); } if (obj == null || jobj == null) { LOG.error("Source object has disappeared! [" + t.getObjType() + "/" + t.getObjId() + "]"); TaskQueue.getInstance().updateTask(t.getObjId(), t.getTaskId(), Task.State.FAILED, t.getObjType()); bw.write("null"); } else if (objType.equals("media")) { try { long ratio = calcRatio(jobj.getString(Task.JSON_OBJ_ID), jobj.getString(Task.JSON_NORECORDING)); if (ratio > 0 && new FieldTimeUntilNextRecording(null, "<=", ratio + "S").run()) { LOG.info("Client '" + req.getRemoteAddr() + "' cannot pop task '" + t.getObjType() + "/" + t.getTaskId() + "/" + t.getObjId() + "'; :NORECORDING option prevents running of this task"); TaskQueue.getInstance().pushBack(t); bw.write("null"); } else bw.write(jobj.toString()); } catch (JSONException e) { throw new RuntimeException(e); } } else bw.write(jobj.toString()); } } } } else if (cmd.equals("update")) { if (!validClient) { LOG.warn("Client IP rejected: " + req.getRemoteAddr()); notAuthorized(resp, bw); } else { list.add(req.getRemoteHost()); try { Task t = new Task(new JSONObject(req.getParameter("data"))); TaskQueue.getInstance().updateTask(t); } catch (JSONException e) { throw new RuntimeException("Input error; client '" + req.getRemoteHost() + "', CMD: update", e); } } } else if (cmd.equals("showQ")) { if (validSession) bw.write(TaskQueue.getInstance().toJSONArray().toString()); else notAuthorized(resp, bw); } else if (cmd.equals("log")) { if (validSession) { String mediaId = req.getParameter("m"); String taskId = req.getParameter("t"); String objType = req.getParameter("o"); if ((mediaId != null && !mediaId.equals("0")) && (taskId != null && !taskId.equals("0"))) bw.write(ds.readLog(mediaId, taskId, objType)); else { BufferedReader r = new BufferedReader(new FileReader("sjq.log")); String line; while ((line = r.readLine()) != null) bw.write(line + "\n"); r.close(); } } else notAuthorized(resp, bw); } else if (cmd.equals("appState")) { if (validSession) bw.write(Butler.dumpAppTrace()); else notAuthorized(resp, bw); } else if (cmd.equals("writeLog")) { if (!validClient) { LOG.warn("Client IP reject: " + req.getRemoteAddr()); notAuthorized(resp, bw); } else { String mediaId = req.getParameter("m"); String taskId; if (!mediaId.equals("-1")) taskId = req.getParameter("t"); else taskId = req.getRemoteHost(); String objType = req.getParameter("o"); if (!mediaId.equals("0") && Boolean.parseBoolean(ds.getSetting("IgnoreTaskOutput", "false"))) { LOG.info("Dropping task output as per settings"); DataStore.returnConnection(ds); return; } String data = req.getParameter("data"); String[] msg = StringUtils.splitByWholeSeparator(data, "\r\n"); if (msg == null || msg.length == 1) msg = StringUtils.split(data, '\r'); if (msg == null || msg.length == 1) msg = StringUtils.split(data, '\n'); long now = System.currentTimeMillis(); for (String line : msg) ds.logForTaskClient(mediaId, taskId, line, now, objType); if (msg.length > 0) ds.flushLogs(); } } else if (cmd.equals("ruleset")) { if (validSession) bw.write(ds.getSetting("ruleset", "")); else notAuthorized(resp, bw); } else if (cmd.equals("saveRuleset")) { if (validSession) { ds.setSetting("ruleset", req.getParameter("data")); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("getClients")) { if (validSession) bw.write(ActiveClientList.getInstance().toJSONArray().toString()); else notAuthorized(resp, bw); } else if (cmd.equals("loadClnt")) { if (validSession) bw.write(ds.getClientConf(req.getParameter("id"))); else notAuthorized(resp, bw); } else if (cmd.equals("saveClnt")) { if (validSession) { if (ds.saveClientConf(req.getParameter("id"), req.getParameter("data"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("history")) { if (validSession) { int start, limit; try { start = Integer.parseInt(req.getParameter("start")); limit = Integer.parseInt(req.getParameter("limit")); } catch (NumberFormatException e) { start = 0; limit = -1; } bw.write(ds.getJobHistory(Integer.parseInt(req.getParameter("t")), start, limit, req.getParameter("sort")).toString()); } else notAuthorized(resp, bw); } else if (cmd.equals("getSrvSetting")) { if (validSession) bw.write(ds.getSetting(req.getParameter("var"), "")); else notAuthorized(resp, bw); } else if (cmd.equals("setSrvSetting")) { if (validSession) { ds.setSetting(req.getParameter("var"), req.getParameter("val")); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("setFileCleaner")) { if (validSession) { ds.setSetting("DelRegex", req.getParameter("orphan")); ds.setSetting("IfRegex", req.getParameter("parent")); ds.setSetting("IgnoreRegex", req.getParameter("ignore")); new Thread(new FileCleaner()).start(); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("getFileCleanerSettings")) { if (validSession) { bw.write(ds.getSetting("DelRegex", "") + "\n"); bw.write(ds.getSetting("IfRegex", "") + "\n"); bw.write(ds.getSetting("IgnoreRegex", "")); } else notAuthorized(resp, bw); } else if (cmd.equals("writeSrvSettings")) { if (validSession) { try { ds.setSettings(new JSONObject(req.getParameter("data"))); } catch (JSONException e) { throw new RuntimeException(e); } bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("readSrvSettings")) { if (validSession) bw.write(ds.readSettings().toString()); else notAuthorized(resp, bw); } else if (cmd.equals("login")) { String pwd = ds.getSetting("password", ""); try { MessageDigest msg = MessageDigest.getInstance("MD5"); msg.update(req.getParameter("password").getBytes()); String userPwd = new String(msg.digest()); if (pwd.length() > 0 && pwd.equals(userPwd)) { bw.write("Success"); int key = new java.util.Random().nextInt(); resp.addHeader("SJQ-Session-Token", Integer.toString(key)); CLIENT_SESSION_KEYS.put(req.getRemoteAddr(), Integer.toString(key)); } else bw.write("BadPassword"); } catch (NoSuchAlgorithmException e) { bw.write(e.getLocalizedMessage()); } } else if (cmd.equals("editPwd")) { try { MessageDigest msg = MessageDigest.getInstance("MD5"); String curPwd = ds.getSetting("password", ""); String oldPwd = req.getParameter("old"); msg.update(oldPwd.getBytes()); oldPwd = new String(msg.digest()); msg.reset(); String newPwd = req.getParameter("new"); String confPwd = req.getParameter("conf"); if (!curPwd.equals(oldPwd)) bw.write("BadOld"); else if (!newPwd.equals(confPwd) || newPwd.length() == 0) bw.write("BadNew"); else { msg.update(newPwd.getBytes()); newPwd = new String(msg.digest()); ds.setSetting("password", newPwd); bw.write("Success"); } } catch (NoSuchAlgorithmException e) { bw.write(e.getLocalizedMessage()); } } else if (cmd.equals("runStats")) { if (validSession) { JSONObject o = new JSONObject(); try { o.put("last", Long.parseLong(ds.getSetting("LastRun", "0"))); o.put("next", Long.parseLong(ds.getSetting("NextRun", "0"))); bw.write(o.toString()); } catch (JSONException e) { bw.write(e.getLocalizedMessage()); } } else notAuthorized(resp, bw); } else if (cmd.equals("runQLoader")) { if (validSession) { Butler.wakeQueueLoader(); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("delActiveQ")) { if (validSession) { if (TaskQueue.getInstance().delete(req.getParameter("m"), req.getParameter("t"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("clearActiveQ")) { if (validSession) { if (TaskQueue.getInstance().clear()) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("editPri")) { if (validSession) { try { int priority = Integer.parseInt(req.getParameter("p")); if (TaskQueue.getInstance().editPriority(req.getParameter("m"), req.getParameter("t"), priority)) bw.write("Success"); else bw.write("Failed"); } catch (NumberFormatException e) { bw.write("Failed"); } } else notAuthorized(resp, bw); } else if (cmd.equals("clearHistory")) { if (validSession) { if (ds.clear(Integer.parseInt(req.getParameter("t")))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("delHistRow")) { if (validSession) { if (ds.delTask(req.getParameter("m"), req.getParameter("t"), Integer.parseInt(req.getParameter("y")), req.getParameter("o"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("rmLog")) { if (validSession) { String mid = req.getParameter("m"); String tid = req.getParameter("t"); String oid = req.getParameter("o"); if (mid.equals("0") && tid.equals("0") && oid.equals("null")) { bw.write("Failed: Can't delete server log file (sjq.log) while SageTV is running!"); } else if (ds.clearLog(mid, tid, oid)) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("qryMediaFile")) { if (validSession) { JSONArray jarr = new JSONArray(); MediaFileAPI.List mediaList = Butler.SageApi.mediaFileAPI.GetMediaFiles(ds.getMediaMask()); String qry = req.getParameter("q"); int max = Integer.parseInt(req.getParameter("m")); for (MediaFileAPI.MediaFile mf : mediaList) { if ((qry.matches("\\d+") && Integer.toString(mf.GetMediaFileID()).startsWith(qry)) || mf.GetMediaTitle().matches(".*" + Pattern.quote(qry) + ".*") || fileSegmentMatches(mf, qry)) { JSONObject o = new JSONObject(); try { o.put("value", mf.GetFileForSegment(0).getAbsolutePath()); String subtitle = null; if (mf.GetMediaFileAiring() != null && mf.GetMediaFileAiring().GetShow() != null) subtitle = mf.GetMediaFileAiring().GetShow().GetShowEpisode(); String display; if (subtitle != null && subtitle.length() > 0) display = mf.GetMediaTitle() + ": " + subtitle; else display = mf.GetMediaTitle(); o.put("display", mf.GetMediaFileID() + " - " + display); jarr.put(o); if (jarr.length() >= max) break; } catch (JSONException e) { e.printStackTrace(System.out); } } } bw.write(jarr.toString()); } else notAuthorized(resp, bw); } else if (cmd.equals("debugMediaFile")) { if (validSession) { if (Butler.debugQueueLoader(req.getParameter("f"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("killTask")) { if (validSession) { if (TaskQueue.getInstance().killTask(req.getParameter("m"), req.getParameter("t"), req.getParameter("o"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("keepAlive")) { bw.write(Boolean.toString(!TaskQueue.getInstance().isTaskKilled(req.getParameter("m"), req.getParameter("t"), req.getParameter("o")))); } bw.close(); DataStore.returnConnection(ds); LOG.info("Servlet POST request completed [" + (System.currentTimeMillis() - startTime) + "ms]"); return; }
00
Code Sample 1: public void testDoubleNaN() { double value = 0; boolean wasEqual = false; String message = "DB operation completed"; String ddl1 = "DROP TABLE t1 IF EXISTS;" + "CREATE TABLE t1 ( d DECIMAL, f DOUBLE, l BIGINT, i INTEGER, s SMALLINT, t TINYINT, " + "dt DATE DEFAULT CURRENT_DATE, ti TIME DEFAULT CURRENT_TIME, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP );"; try { stmnt.execute(ddl1); PreparedStatement ps = connection.prepareStatement("INSERT INTO t1 (d,f,l,i,s,t,dt,ti,ts) VALUES (?,?,?,?,?,?,?,?,?)"); ps.setString(1, "0.2"); ps.setDouble(2, 0.2); ps.setLong(3, java.lang.Long.MAX_VALUE); ps.setInt(4, Integer.MAX_VALUE); ps.setInt(5, Short.MAX_VALUE); ps.setInt(6, 0); ps.setDate(7, new java.sql.Date(System.currentTimeMillis())); ps.setTime(8, new java.sql.Time(System.currentTimeMillis())); ps.setTimestamp(9, new java.sql.Timestamp(System.currentTimeMillis())); ps.execute(); ps.setInt(1, 0); ps.setDouble(2, java.lang.Double.NaN); ps.setLong(3, java.lang.Long.MIN_VALUE); ps.setInt(4, Integer.MIN_VALUE); ps.setInt(5, Short.MIN_VALUE); ps.setInt(6, 0); ps.setTimestamp(7, new java.sql.Timestamp(System.currentTimeMillis() + 1)); ps.setTime(8, new java.sql.Time(System.currentTimeMillis() + 1)); ps.setDate(9, new java.sql.Date(System.currentTimeMillis() + 1)); ps.execute(); ps.setInt(1, 0); ps.setDouble(2, java.lang.Double.POSITIVE_INFINITY); ps.setInt(4, Integer.MIN_VALUE); ps.setObject(5, Boolean.TRUE); ps.setBoolean(5, true); ps.setObject(5, new Short((short) 2), Types.SMALLINT); ps.setObject(6, new Integer(2), Types.TINYINT); ps.setObject(7, new java.sql.Date(System.currentTimeMillis() + 2)); ps.setObject(8, new java.sql.Time(System.currentTimeMillis() + 2)); ps.setObject(9, new java.sql.Timestamp(System.currentTimeMillis() + 2)); ps.execute(); ps.setObject(1, new Float(0), Types.INTEGER); ps.setObject(4, new Float(1), Types.INTEGER); ps.setDouble(2, java.lang.Double.NEGATIVE_INFINITY); ps.execute(); ResultSet rs = stmnt.executeQuery("SELECT d, f, l, i, s*2, t FROM t1"); boolean result = rs.next(); value = rs.getDouble(2); int integerValue = rs.getInt(4); if (rs.next()) { value = rs.getDouble(2); wasEqual = Double.isNaN(value); integerValue = rs.getInt(4); integerValue = rs.getInt(1); } if (rs.next()) { value = rs.getDouble(2); wasEqual = wasEqual && value == Double.POSITIVE_INFINITY; } if (rs.next()) { value = rs.getDouble(2); wasEqual = wasEqual && value == Double.NEGATIVE_INFINITY; } rs = stmnt.executeQuery("SELECT MAX(i) FROM t1"); if (rs.next()) { int max = rs.getInt(1); System.out.println("Max value for i: " + max); } { stmnt.execute("drop table CDTYPE if exists"); rs = stmnt.executeQuery("CREATE TABLE cdType (ID INTEGER NOT NULL, name VARCHAR(50), PRIMARY KEY(ID))"); rs = stmnt.executeQuery("SELECT MAX(ID) FROM cdType"); if (rs.next()) { int max = rs.getInt(1); System.out.println("Max value for ID: " + max); } else { System.out.println("Max value for ID not returned"); } stmnt.executeUpdate("INSERT INTO cdType VALUES (10,'Test String');"); stmnt.executeQuery("CALL IDENTITY();"); try { stmnt.executeUpdate("INSERT INTO cdType VALUES (10,'Test String');"); } catch (SQLException e1) { stmnt.execute("ROLLBACK"); connection.rollback(); } } } catch (SQLException e) { fail(e.getMessage()); } System.out.println("testDoubleNaN complete"); assertEquals(true, wasEqual); } Code Sample 2: public boolean check(Object credentials) { try { byte[] digest = null; if (credentials instanceof Password || credentials instanceof String) { synchronized (__md5Lock) { if (__md == null) __md = MessageDigest.getInstance("MD5"); __md.reset(); __md.update(credentials.toString().getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } if (digest == null || digest.length != _digest.length) return false; for (int i = 0; i < digest.length; i++) if (digest[i] != _digest[i]) return false; return true; } else if (credentials instanceof MD5) { MD5 md5 = (MD5) credentials; if (_digest.length != md5._digest.length) return false; for (int i = 0; i < _digest.length; i++) if (_digest[i] != md5._digest[i]) return false; return true; } else if (credentials instanceof Credential) { return ((Credential) credentials).check(this); } else { Log.warn("Can't check " + credentials.getClass() + " against MD5"); return false; } } catch (Exception e) { Log.warn(e); return false; } }
00
Code Sample 1: private String determineGuardedHtml() { StringBuffer buf = new StringBuffer(); if (m_guardedButtonPresent) { buf.append("\n<span id='" + getHtmlIdPrefix() + PUSH_PAGE_SUFFIX + "' style='display:none'>\n"); String location = m_guardedHtmlLocation != null ? m_guardedHtmlLocation : (String) Config.getProperty(Config.PROP_PRESENTATION_DEFAULT_GUARDED_HTML_LOCATION); String html = (String) c_guardedHtmlCache.get(location); if (html == null) { if (log.isDebugEnabled()) log.debug(this.NAME + ".determineGuardedHtml: Reading the Guarded Html Fragment: " + location); URL url = getUrl(location); if (url != null) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf1 = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { buf1.append(line); buf1.append('\n'); } html = buf1.toString(); } catch (IOException e) { log.warn(this.NAME + ".determineGuardedHtml: Failed to read the Guarded Html Fragment: " + location, e); } finally { try { if (in != null) in.close(); } catch (IOException ex) { log.warn(this.NAME + ".determineGuardedHtml: Failed to close the Guarded Html Fragment: " + location, ex); } } } else { log.warn("Failed to read the Guarded Html Fragment: " + location); } if (html == null) html = "Transaction in Progress"; c_guardedHtmlCache.put(location, html); } buf.append(html); buf.append("\n</span>\n"); } return buf.toString(); } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) throw new IOException("Source and destination cannot be the same file path"); FileChannel srcChannel = new FileInputStream(source).getChannel(); if (!dest.exists()) dest.createNewFile(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: @Override public Class<?> loadClass(final String name) throws ClassNotFoundException { final String baseName = StringUtils.substringBefore(name, "$"); if (baseName.startsWith("java") && !whitelist.contains(baseName) && !additionalWhitelist.contains(baseName)) { throw new NoClassDefFoundError(name + " is a restricted class for GAE"); } if (!name.startsWith("com.gargoylesoftware")) { return super.loadClass(name); } super.loadClass(name); final InputStream is = getResourceAsStream(name.replaceAll("\\.", "/") + ".class"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { IOUtils.copy(is, bos); final byte[] bytes = bos.toByteArray(); return defineClass(name, bytes, 0, bytes.length); } catch (final IOException e) { throw new RuntimeException(e); } } Code Sample 2: private String getData(String requestUrl) throws AuthenticationException, IOException { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String header; try { header = oauthAuthenticator.getHttpAuthorizationHeader(url.toString(), "GET", profile.getOAuthToken(), profile.getOAuthTokenSecret()); } catch (OAuthException e) { throw new AuthenticationException(e); } conn.setRequestProperty("Authorization", header); if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AuthenticationException(); } InputStreamReader reader = new InputStreamReader(conn.getInputStream()); char[] buffer = new char[1024]; int bytesRead = 0; StringBuilder data = new StringBuilder(); while ((bytesRead = reader.read(buffer)) != -1) { data.append(buffer, 0, bytesRead); } reader.close(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage() + "\n" + data); } return data.toString(); }
00
Code Sample 1: public InputStream getEntry(String entryPath) throws IOException { if (!entries.contains(entryPath)) { return null; } JarInputStream jis = new JarInputStream(new BufferedInputStream(url.openStream())); do { ZipEntry ze = jis.getNextEntry(); if (ze == null) { break; } if (ze.getName().equals(entryPath)) { return jis; } } while (true); assert (false); return null; } Code Sample 2: public static void copy(File source, File dest) throws java.io.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(); } }
00
Code Sample 1: public void process(String t) { try { MessageDigest md5 = MessageDigest.getInstance(MD5_DIGEST); md5.reset(); md5.update(t.getBytes()); callback.display(null, digestToHexString(md5.digest())); } catch (Exception ex) { callback.display(null, "[failed]"); } } Code Sample 2: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; } Code Sample 2: 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(); }
00
Code Sample 1: public String getNextSequence(Integer id) throws ApplicationException { java.sql.PreparedStatement preStat = null; java.sql.ResultSet rs = null; boolean noRecordMatch = false; String prefix = ""; String suffix = ""; Long startID = null; Integer length = null; Long currID = null; Integer increment = null; int nextID; String formReferenceID = null; synchronized (lock) { synchronized (dbConn) { try { preStat = dbConn.prepareStatement("SELECT PREFIX,SUFFIX,START_NO,LENGTH,CURRENT_NO,INCREMENT FROM FORM_RECORD WHERE ID=?"); setPrepareStatement(preStat, 1, id); rs = preStat.executeQuery(); if (rs.next()) { prefix = rs.getString(1); suffix = rs.getString(2); startID = new Long(rs.getLong(3)); length = new Integer(rs.getInt(4)); currID = new Long(rs.getLong(5)); increment = new Integer(rs.getInt(6)); if (Utility.isEmpty(startID) || Utility.isEmpty(length) || Utility.isEmpty(currID) || Utility.isEmpty(increment) || startID.intValue() < 0 || length.intValue() < startID.toString().length() || currID.intValue() < startID.intValue() || increment.intValue() < 1 || new Integer(increment.intValue() + currID.intValue()).toString().length() > length.intValue()) { noRecordMatch = true; } else { if (!Utility.isEmpty(prefix)) { formReferenceID = prefix; } String strCurrID = currID.toString(); for (int i = 0; i < length.intValue() - strCurrID.length(); i++) { formReferenceID += "0"; } formReferenceID += strCurrID; if (!Utility.isEmpty(suffix)) { formReferenceID += suffix; } } } else { noRecordMatch = true; } } catch (Exception e) { log.error(e, e); try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } throw new ApplicationException("errors.framework.get_next_seq", e); } finally { try { rs.close(); } catch (Exception ignore) { } finally { rs = null; } try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } if (!noRecordMatch && formReferenceID != null) { try { int updateCnt = 0; nextID = currID.intValue() + increment.intValue(); do { preStat = dbConn.prepareStatement("UPDATE FORM_RECORD SET CURRENT_NO=? WHERE ID=?"); setPrepareStatement(preStat, 1, new Integer(nextID)); setPrepareStatement(preStat, 2, id); updateCnt = preStat.executeUpdate(); if (updateCnt == 0) { Thread.sleep(50); } } while (updateCnt == 0); dbConn.commit(); } catch (Exception e) { log.error(e, e); try { dbConn.rollback(); } catch (Exception ignore) { } throw new ApplicationException("errors.framework.get_next_seq", e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } } } return formReferenceID; } } } Code Sample 2: private URL retrieveFirstURL(URL url, RSLink link) { link.setStatus(RSLink.STATUS_WAITING); URL result = null; HttpURLConnection httpConn = null; BufferedReader inr = null; Pattern formStartPattern = Pattern.compile("<form.+action=\""); Pattern freeUserPattern = Pattern.compile("input type=\"submit\" value=\"Free user\""); Pattern formEndPattern = Pattern.compile("</form>"); Pattern urlString = Pattern.compile("http://[a-zA-Z0-9\\.\\-/_]+"); try { httpConn = (HttpURLConnection) url.openConnection(); httpConn.setDoOutput(false); httpConn.setDoInput(true); inr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); String line = null; String urlLine = null; boolean freeUser = false; Matcher matcher = null; while ((line = inr.readLine()) != null) { if (urlLine == null) { matcher = formStartPattern.matcher(line); if (matcher.find()) { urlLine = line; } } else { matcher = formEndPattern.matcher(line); if (matcher.find()) { urlLine = null; } else { matcher = freeUserPattern.matcher(line); if (matcher.find()) { freeUser = true; break; } } } } if (freeUser) { matcher = urlString.matcher(urlLine); if (matcher.find()) { result = new URL(matcher.group()); } } } catch (MalformedURLException ex) { log("Malformed URL Exception!"); } catch (IOException ex) { log("I/O Exception!"); } finally { try { if (inr != null) inr.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Can not close some connections:\n" + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); } if (httpConn != null) httpConn.disconnect(); link.setStatus(RSLink.STATUS_NOTHING); return result; } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private 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!"); }
11
Code Sample 1: private String getMAC(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } 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: @Override public String post(final FetchInfos fetchInfos, final String data) throws HttpException { URL url = null; try { url = new URL(fetchInfos.getUri()); } catch (MalformedURLException exception) { throw new HttpException("uri is malformed '" + fetchInfos.getUri() + "'", exception); } HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); } catch (IOException exception) { fetchInfos.setResult(FETCHING_RESULT.IO_ERROR); throw new HttpException("get '" + fetchInfos.getUri() + "' failed", exception); } InputStream input = null; try { connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); final DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); input = connection.getInputStream(); if ("gzip".equals(connection.getHeaderField("content-encoding"))) { input = new GZIPInputStream(input); } if (HttpServiceImpl.LOGGER.isDebugEnabled()) { this.logConnection(connection); input = new LoggingInputStream(input); } } catch (SocketTimeoutException exception) { fetchInfos.setResult(FETCHING_RESULT.TIME_OUT); throw new HttpException("get '" + fetchInfos.getUri() + "' timeout", exception); } catch (IOException exception) { fetchInfos.setResult(FETCHING_RESULT.IO_ERROR); throw new HttpException("get '" + fetchInfos.getUri() + "' failed", exception); } fetchInfos.setResult(FETCHING_RESULT.OK); String response = null; try { response = this.toString(input); } catch (IOException exception) { throw new HttpException("converting inputstream to string failed", exception); } return response; } 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()); }
00
Code Sample 1: public static String readFromURL(String url_) { StringBuffer buffer = new StringBuffer(); try { URL url = new URL(url_); System.setProperty("http.agent", ""); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); connection.setDoInput(true); InputStream inStream = connection.getInputStream(); BufferedReader input = new BufferedReader(new InputStreamReader(inStream, "utf8")); String line = ""; while ((line = input.readLine()) != null) { buffer.append(line + "\n"); } } catch (Exception e) { System.out.println(e.toString()); } return buffer.toString(); } Code Sample 2: public void sendPOIGpxLocation() { this.myloc = new Position(45.56, 5.9); this.left = myloc.getY() - 0.025; this.right = myloc.getY() + 0.025; this.top = myloc.getX() + 0.03; this.bottom = myloc.getX() - 0.03; assertEquals("left test", left, (5.9 - 0.025)); assertEquals("right test", right, (5.9 + 0.025)); assertEquals("top test", top, (45.56 - 0.025)); assertEquals("bottom test", left, (45.56 + 0.025)); this.poisCheck.add("amenity"); try { if (this.poisCheck.get(0).compareTo("None") == 0) { model.setPointsOfInterest(new Items()); } else { this.url = new URL("http://www.informationfreeway.org/api/0.6/node[" + poisCheck.get(0) + "=*][bbox=" + left + "," + bottom + "," + right + "," + top + "]"); assertEquals("url informationfreeway.org test", url, "http://www.informationfreeway.org/api/0.6/node[amenity=*]" + "[bbox=" + left + "," + bottom + "," + right + "," + top + "]"); SAXParser pars = null; ParsePoiGpx gpxHandler = new ParsePoiGpx(poisCheck, this.model.getContext()); pars = SAXParserFactory.newInstance().newSAXParser(); pars.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true); pars.parse(url.openStream(), gpxHandler); this.pois = gpxHandler.getPOIResultsItems(); assertTrue("there is some pois", !this.pois.equals(0)); assertFalse("there is some pois", this.pois.equals(0)); } } catch (Exception e) { e.printStackTrace(); assertFalse(!e.getCause().equals(null)); } }
00
Code Sample 1: private CharBuffer decodeToFile(ReplayInputStream inStream, String backingFilename, String encoding) throws IOException { CharBuffer charBuffer = null; BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, encoding)); File backingFile = new File(backingFilename); this.decodedFile = File.createTempFile(backingFile.getName(), WRITE_ENCODING, backingFile.getParentFile()); FileOutputStream fos; fos = new FileOutputStream(this.decodedFile); IOUtils.copy(reader, fos, WRITE_ENCODING); fos.close(); charBuffer = getReadOnlyMemoryMappedBuffer(this.decodedFile).asCharBuffer(); return charBuffer; } Code Sample 2: public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
00
Code Sample 1: public String loadURLString(java.net.URL url) { try { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String s = ""; while (br.ready() && s != null) { s = br.readLine(); if (s != null) { buf.append(s); buf.append("\n"); } } return buf.toString(); } catch (IOException ex) { return ""; } catch (NullPointerException npe) { return ""; } } Code Sample 2: public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
11
Code Sample 1: public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String dest1 = dest.getAbsolutePath() + File.separatorChar + list[i]; String src1 = src.getAbsolutePath() + File.separatorChar + list[i]; copyFiles(src1, dest1); } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing 'file' Arg"); return; } int mfid = NumberUtils.toInt(arg); Object sageFile = MediaFileAPI.GetMediaFileForID(mfid); if (sageFile == null) { resp.sendError(404, "Sage File not found " + mfid); return; } int seconds = NumberUtils.toInt(req.getParameter("ss"), -1); long offset = NumberUtils.toLong(req.getParameter("sb"), -1); if (seconds < 0 && offset < 0) { resp.sendError(501, "Missing 'ss' or 'sb' args"); return; } int width = NumberUtils.toInt(req.getParameter("w"), 320); int height = NumberUtils.toInt(req.getParameter("h"), 320); File dir = new File(Phoenix.getInstance().getUserCacheDir(), "videothumb/" + mfid); if (!dir.exists()) { dir.mkdirs(); } String prefix = ""; if (offset > 0) { prefix = "O" + offset; } else { prefix = "S" + seconds; } File f = new File(dir, prefix + "_" + width + "_" + height + ".jpg").getCanonicalFile(); if (!f.exists()) { try { generateThumbnailNew(sageFile, f, seconds, offset, width, height); } catch (Exception e) { e.printStackTrace(); resp.sendError(503, "Failed to generate thumbnail\n " + e.getMessage()); return; } } if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } resp.setContentType("image/jpeg"); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } }
00
Code Sample 1: public String readTemplateToString(String fileName) { URL url = null; url = classLoader.getResource(fileName); StringBuffer content = new StringBuffer(); if (url == null) { String error = "Template file could not be found: " + fileName; throw new RuntimeException(error); } try { BufferedReader breader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String strLine = ""; while ((strLine = breader.readLine()) != null) { content.append(strLine).append("\n"); } breader.close(); } catch (Exception e) { throw new RuntimeException("Problem while loading file: " + fileName); } return content.toString(); } Code Sample 2: private void upgradeSchema() throws IOException { Statement stmt = null; try { int i = getSchema(); if (i < SCHEMA_VERSION) { conn.setAutoCommit(false); stmt = conn.createStatement(); while (i < SCHEMA_VERSION) { String qry; switch(i) { case 1: qry = "CREATE TABLE log (id INTEGER PRIMARY KEY, context VARCHAR(16) NOT NULL, level VARCHAR(16) NOT NULL, time LONG INT NOT NULL, msg LONG VARCHAR NOT NULL, parent INT)"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '2' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 2: qry = "CREATE TABLE monitor (id INTEGER PRIMARY KEY NOT NULL, status INTEGER NOT NULL)"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '3' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 3: qry = "CREATE TABLE favs (id INTEGER PRIMARY KEY NOT NULL)"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '4' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 4: qry = "DROP TABLE log"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '5' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 5: qry = "UPDATE settings SET val = '120000' WHERE var = 'SleepTime'"; stmt.executeUpdate(qry); qry = "UPDATE settings set val = '6' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; } i++; } conn.commit(); } } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e2) { LOG.trace(SQL_ERROR, e2); LOG.error(e2); } LOG.trace(SQL_ERROR, e); LOG.fatal(e); throw new IOException("Error upgrading data store", e); } finally { try { if (stmt != null) { stmt.close(); } conn.setAutoCommit(true); } catch (SQLException e) { LOG.trace(SQL_ERROR, e); throw new IOException("Unable to cleanup SQL resources", e); } } }
11
Code Sample 1: private void copyPhoto(final IPhoto photo, final Map.Entry<String, Integer> size) { final File fileIn = new File(storageService.getPhotoPath(photo, storageService.getOriginalDir())); final File fileOut = new File(storageService.getPhotoPath(photo, size.getKey())); InputStream fileInputStream; OutputStream fileOutputStream; try { fileInputStream = new FileInputStream(fileIn); fileOutputStream = new FileOutputStream(fileOut); IOUtils.copy(fileInputStream, fileOutputStream); fileInputStream.close(); fileOutputStream.close(); } catch (final IOException e) { log.error("file io exception", e); return; } } Code Sample 2: private static void copySmallFile(final File sourceFile, final File targetFile) throws PtException { LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to " + "'" + targetFile.getAbsolutePath() + "'."); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new PtException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to " + "'" + targetFile.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(inChannel, outChannel); } }
00
Code Sample 1: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } } Code Sample 2: private static BreakIterator createBreakInstance(Locale where, int kind, String rulesName, String dictionaryName) { ResourceBundle bundle = ICULocaleData.getResourceBundle("BreakIteratorRules", where); String[] classNames = bundle.getStringArray("BreakIteratorClasses"); String rules = bundle.getString(rulesName); if (classNames[kind].equals("RuleBasedBreakIterator")) { return new RuleBasedBreakIterator(rules); } else if (classNames[kind].equals("DictionaryBasedBreakIterator")) { try { Object t = bundle.getObject(dictionaryName); URL url = (URL) t; InputStream dictionary = url.openStream(); return new DictionaryBasedBreakIterator(rules, dictionary); } catch (IOException e) { } catch (MissingResourceException e) { } return new RuleBasedBreakIterator(rules); } else { throw new IllegalArgumentException("Invalid break iterator class \"" + classNames[kind] + "\""); } }
00
Code Sample 1: public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } } Code Sample 2: public boolean login(String strUrl, String loginName, String loginPwd) throws ApplicationException { String starter = "-----------------------------"; String returnChar = "\r\n"; String lineEnd = "--"; String urlString = strUrl; String input = null; List txtList = new ArrayList(); List fileList = new ArrayList(); String targetFile = null; String actionStatus = null; StringBuffer returnMessage = new StringBuffer(); List head = new ArrayList(); final String boundary = String.valueOf(System.currentTimeMillis()); URL url = null; URLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; boolean isLogin = false; txtList.add(new HtmlFormText("loginName", loginName)); txtList.add(new HtmlFormText("loginPwd", loginPwd)); txtList.add(new HtmlFormText("navMode", "I")); txtList.add(new HtmlFormText("action", "login")); try { url = new URL(urlString); conn = url.openConnection(); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "multipart/form-data, boundary=" + "---------------------------" + boundary); if (input != null) { String auth = "Basic " + new sun.misc.BASE64Encoder().encode(input.getBytes()); conn.setRequestProperty("Authorization", auth); } dos = new DataOutputStream(conn.getOutputStream()); dos.write((starter + boundary + returnChar).getBytes()); for (int i = 0; i < txtList.size(); i++) { HtmlFormText htmltext = (HtmlFormText) txtList.get(i); dos.write(htmltext.getTranslated()); if (i + 1 < txtList.size()) { dos.write((starter + boundary + returnChar).getBytes()); } else if (fileList.size() > 0) { dos.write((starter + boundary + returnChar).getBytes()); } } dos.write((starter + boundary + "--" + returnChar).getBytes()); dos.flush(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String cookieVal = conn.getHeaderField(HEADER_SETCOOKIE); if (cookieVal != null) { cookie = cookieVal.substring(0, cookieVal.indexOf(";")); } String tempstr; int line = 0; while (null != ((tempstr = br.readLine()))) { if (!tempstr.equals("")) { if ("window.location.replace(\"/Home.do\");".indexOf(returnMessage.append(formatLine(tempstr)).toString()) != -1) { isLogin = true; break; } line++; } } txtList.clear(); fileList.clear(); } catch (Exception e) { log.error(e, e); throw new ApplicationException(FormErrorConstant.DB_APP_BASE_URL_ERROR); } finally { try { dos.close(); } catch (Exception e) { } try { br.close(); } catch (Exception e) { } } return isLogin; }
00
Code Sample 1: final void saveProject(Project project, final File file) { if (projectsList.contains(project)) { if (project.isDirty() || !file.getParentFile().equals(workspaceDirectory)) { try { if (!file.exists()) { if (!file.createNewFile()) throw new IOException("cannot create file " + file.getAbsolutePath()); } File tmpFile = File.createTempFile("JFPSM", ".tmp"); ZipOutputStream zoStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file))); zoStream.setMethod(ZipOutputStream.DEFLATED); ZipEntry projectXMLEntry = new ZipEntry("project.xml"); projectXMLEntry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(projectXMLEntry); CustomXMLEncoder encoder = new CustomXMLEncoder(new BufferedOutputStream(new FileOutputStream(tmpFile))); encoder.writeObject(project); encoder.close(); int bytesIn; byte[] readBuffer = new byte[1024]; FileInputStream fis = new FileInputStream(tmpFile); while ((bytesIn = fis.read(readBuffer)) != -1) zoStream.write(readBuffer, 0, bytesIn); fis.close(); ZipEntry entry; String floorDirectory; for (FloorSet floorSet : project.getLevelSet().getFloorSetsList()) for (Floor floor : floorSet.getFloorsList()) { floorDirectory = "levelset/" + floorSet.getName() + "/" + floor.getName() + "/"; for (MapType type : MapType.values()) { entry = new ZipEntry(floorDirectory + type.getFilename()); entry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(entry); ImageIO.write(floor.getMap(type).getImage(), "png", zoStream); } } final String tileDirectory = "tileset/"; for (Tile tile : project.getTileSet().getTilesList()) for (int textureIndex = 0; textureIndex < tile.getMaxTextureCount(); textureIndex++) if (tile.getTexture(textureIndex) != null) { entry = new ZipEntry(tileDirectory + tile.getName() + textureIndex + ".png"); entry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(entry); ImageIO.write(tile.getTexture(textureIndex), "png", zoStream); } zoStream.close(); tmpFile.delete(); } catch (IOException ioe) { throw new RuntimeException("The project " + project.getName() + " cannot be saved!", ioe); } } } else throw new IllegalArgumentException("The project " + project.getName() + " is not handled by this project set!"); } Code Sample 2: public static Chunk updateLastSend(Chunk c) throws Exception { DBConnectionManager dbm = null; Connection conn = null; PreparedStatement stmt = null; Chunk ret = null; String SQL = "UPDATE CHUNK SET SENT=? WHERE FILEHASH=? AND STARTOFF=? AND LENGTH=?"; log.debug("update chunk last sent for chunk " + c.getHash() + " startoff " + c.getStartOffset()); try { dbm = DBConnectionManager.getInstance(); conn = dbm.getConnection("satmule"); stmt = conn.prepareStatement(SQL); stmt.setDate(1, new java.sql.Date(c.getLastSend().getTime())); stmt.setString(2, c.getHash()); stmt.setLong(3, c.getStartOffset()); stmt.setLong(4, c.getSize()); stmt.executeUpdate(); conn.commit(); stmt.close(); dbm.freeConnection("satmule", conn); } catch (Exception e) { log.error("Error while updating chunk " + c.getHash() + "offset:" + c.getStartOffset() + "SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (conn == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { conn.rollback(); excep = new Exception("SQL Error : " + SQL + " error: " + e); dbm.freeConnection("satmule", conn); } throw excep; } return ret; }
00
Code Sample 1: public void test_calculateLastModifiedSizeContent() { File file; String content = "Hello, world!"; String expected; FileETag etag; try { file = File.createTempFile("temp", "txt"); file.deleteOnExit(); FileOutputStream out = new FileOutputStream(file); out.write(content.getBytes()); out.flush(); out.close(); SimpleDateFormat date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); long lastModified = date.parse("06/21/2007 11:19:36").getTime(); file.setLastModified(lastModified); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(content.getBytes()); StringBuffer buffer = new StringBuffer(); buffer.append(lastModified); buffer.append(content.length()); expected = new String(Hex.encodeHex(messageDigest.digest(buffer.toString().getBytes()))); etag = new FileETag(); etag.setFlags(FileETag.FLAG_CONTENT | FileETag.FLAG_MTIME | FileETag.FLAG_SIZE); String value = etag.calculate(file); assertEquals("Unexpected value", expected, value); } catch (FileNotFoundException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (IOException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (ParseException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); fail("Unexpected exception"); } } Code Sample 2: public static String createStringFromHtml(MyUrl url) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.getUrl().openStream(), "UTF-8")); String line; String xmlAsString = ""; while ((line = reader.readLine()) != null) { xmlAsString += line; } reader.close(); return xmlAsString; } catch (Exception e) { return null; } }
00
Code Sample 1: 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!"); } Code Sample 2: private void removeCollection(long oid, Connection conn) throws XMLDBException { try { String sql = "DELETE FROM X_DOCUMENT WHERE X_DOCUMENT.XDB_COLLECTION_OID = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setLong(1, oid); pstmt.executeUpdate(); pstmt.close(); sql = "DELETE FROM XDB_COLLECTION WHERE XDB_COLLECTION.XDB_COLLECTION_OID = ?"; pstmt = conn.prepareStatement(sql); pstmt.setLong(1, oid); pstmt.executeUpdate(); pstmt.close(); removeChildCollection(oid, conn); } catch (java.sql.SQLException se) { try { conn.rollback(); } catch (java.sql.SQLException se2) { se2.printStackTrace(); } se.printStackTrace(); } }
11
Code Sample 1: public static ISimpleChemObjectReader createReader(URL url, String urlString, String type) throws CDKException { if (type == null) { type = "mol"; } ISimpleChemObjectReader cor = null; try { Reader input = new BufferedReader(getReader(url)); FormatFactory formatFactory = new FormatFactory(8192); IChemFormat format = formatFactory.guessFormat(input); if (format != null) { if (format instanceof RGroupQueryFormat) { cor = new RGroupQueryReader(); cor.setReader(input); } else if (format instanceof CMLFormat) { cor = new CMLReader(urlString); cor.setReader(url.openStream()); } else if (format instanceof MDLV2000Format) { cor = new MDLV2000Reader(getReader(url)); cor.setReader(input); } } } catch (Exception exc) { exc.printStackTrace(); } if (cor == null) { if (type.equals(JCPFileFilter.cml) || type.equals(JCPFileFilter.xml)) { cor = new CMLReader(urlString); } else if (type.equals(JCPFileFilter.sdf)) { cor = new MDLV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.mol)) { cor = new MDLV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.inchi)) { try { cor = new INChIReader(new URL(urlString).openStream()); } catch (Exception e) { e.printStackTrace(); } } else if (type.equals(JCPFileFilter.rxn)) { cor = new MDLRXNV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.smi)) { cor = new SMILESReader(getReader(url)); } } if (cor == null) { throw new CDKException(GT._("Could not determine file format")); } if (cor instanceof MDLV2000Reader) { try { BufferedReader in = new BufferedReader(getReader(url)); String line; while ((line = in.readLine()) != null) { if (line.equals("$$$$")) { String message = GT._("It seems you opened a mol or sdf" + " file containing several molecules. " + "Only the first one will be shown"); JOptionPane.showMessageDialog(null, message, GT._("sdf-like file"), JOptionPane.INFORMATION_MESSAGE); break; } } } catch (IOException ex) { ex.printStackTrace(); } } return cor; } Code Sample 2: public static String urlPost(Map<String, String> paraMap, String urlStr) throws IOException { String strParam = ""; for (Map.Entry<String, String> entry : paraMap.entrySet()) { strParam = strParam + (entry.getKey() + "=" + entry.getValue()) + "&"; } URL url = new URL(urlStr); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); out.write(strParam); out.flush(); out.close(); String sCurrentLine; String sTotalString; sCurrentLine = ""; sTotalString = ""; InputStream l_urlStream; l_urlStream = connection.getInputStream(); BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream)); while ((sCurrentLine = l_reader.readLine()) != null) { sTotalString += sCurrentLine + "\r\n"; } System.out.println(sTotalString); return sTotalString; }
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: @SuppressWarnings("unchecked") public static void main(String[] args) { System.out.println("Starting encoding test...."); Properties p = new Properties(); try { InputStream pStream = ClassLoader.getSystemResourceAsStream("sample_weather.properties"); p.load(pStream); } catch (Exception e) { System.err.println("Could not load properties file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } if (WeatherUpdater.DEBUG) { System.out.println("hostname: " + p.getProperty("weather.hostname")); } if (WeatherUpdater.DEBUG) { System.out.println("database: " + p.getProperty("weather.database")); } if (WeatherUpdater.DEBUG) { System.out.println("username: " + p.getProperty("weather.username")); } if (WeatherUpdater.DEBUG) { System.out.println("password: " + p.getProperty("weather.password")); } SqlAccount sqlAccount = new SqlAccount(p.getProperty("weather.hostname"), p.getProperty("weather.database"), p.getProperty("weather.username"), p.getProperty("weather.password")); DatabaseInterface dbi = null; try { dbi = new DatabaseInterface(sqlAccount); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Established connection to database."); String query = "SELECT * FROM Current_Weather WHERE ZipCode = '99702'"; ResultTable results; System.out.println("Executing query: " + query); try { results = dbi.executeQuery(query); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Got results from query."); System.out.println("Converted results into the following table:"); System.out.println(results); System.out.println(); Class<? extends ResultEncoder> encoder_class; Class<? extends ResultDecoder> decoder_class; try { encoder_class = (Class<? extends ResultEncoder>) Class.forName(p.getProperty("mysms.coding.resultEncoder")); decoder_class = (Class<? extends ResultDecoder>) Class.forName(p.getProperty("mysms.coding.resultDecoder")); } catch (Exception e) { System.err.println("Could not find specified encoder: " + p.getProperty("result.encoder")); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Found class of encoder: " + encoder_class); System.out.println("Found class of decoder: " + decoder_class); ResultEncoder encoder; ResultDecoder decoder; try { encoder = encoder_class.newInstance(); if (encoder_class.equals(decoder_class) && decoder_class.isInstance(encoder)) { decoder = (ResultDecoder) encoder; } else { decoder = decoder_class.newInstance(); } } catch (Exception e) { System.err.println("Could not create instances of encoder and decoder."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Created instances of encoder and decoder."); if (decoder.equals(encoder)) { System.out.println("Decoder and encoder are same object."); } ByteBuffer buffer; try { buffer = encoder.encode(null, results); } catch (Exception e) { System.err.println("Could not encode results."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Encoded results to ByteBuffer with size: " + buffer.capacity()); File temp; try { temp = File.createTempFile("encoding_test", ".results"); temp.deleteOnExit(); FileChannel out = new FileOutputStream(temp).getChannel(); out.write(buffer); out.close(); } catch (Exception e) { System.err.println("Could not write buffer to file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Wrote buffer to file: \"" + temp.getName() + "\" with length: " + temp.length()); ByteBuffer re_buffer; try { FileInputStream in = new FileInputStream(temp.getAbsolutePath()); byte[] temp_buffer = new byte[(int) temp.length()]; int totalRead = 0; int numRead = 0; while (totalRead < temp_buffer.length) { numRead = in.read(temp_buffer, totalRead, temp_buffer.length - totalRead); if (numRead < 0) { break; } else { totalRead += numRead; } } re_buffer = ByteBuffer.wrap(temp_buffer); in.close(); } catch (Exception e) { System.err.println("Could not read from temporary file into buffer."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Read file back into buffer with length: " + re_buffer.capacity()); ResultTable re_results; try { re_results = decoder.decode(null, re_buffer); } catch (Exception e) { System.err.println("Could not decode buffer into a ResultTable."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Decoded buffer back into the following table:"); System.out.println(re_results); System.out.println(); System.out.println("... encoding test complete."); }
11
Code Sample 1: public static void copyFile(File source, File destination, long copyLength) throws IOException { if (!source.exists()) { String message = "File " + source + " does not exist"; throw new FileNotFoundException(message); } if (destination.getParentFile() != null && !destination.getParentFile().exists()) { forceMkdir(destination.getParentFile()); } if (destination.exists() && !destination.canWrite()) { String message = "Unable to open file " + destination + " for writing."; throw new IOException(message); } if (source.getCanonicalPath().equals(destination.getCanonicalPath())) { String message = "Unable to write file " + source + " on itself."; throw new IOException(message); } if (copyLength == 0) { truncateFile(destination, 0); } FileInputStream input = null; FileOutputStream output = null; try { input = new FileInputStream(source); output = new FileOutputStream(destination); long lengthLeft = copyLength; byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, lengthLeft + 1)]; int read; while (lengthLeft > 0) { read = input.read(buffer); if (read == -1) { break; } lengthLeft -= read; output.write(buffer, 0, read); } output.flush(); output.getFD().sync(); } finally { IOUtil.closeQuietly(input); IOUtil.closeQuietly(output); } destination.setLastModified(source.lastModified()); } Code Sample 2: public void invoke(InputStream is) throws AgentException { try { addHeader("Content-Type", "application/zip"); addHeader("Content-Length", String.valueOf(is.available())); connection.setDoOutput(true); connection.connect(); OutputStream os = connection.getOutputStream(); boolean success = false; try { IOUtils.copy(is, os); success = true; } finally { try { os.flush(); os.close(); } catch (IOException x) { if (success) throw x; } } connection.disconnect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new AgentException("Failed to execute REST call at " + connection.getURL() + ": " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (ConnectException e) { throw new AgentException("Failed to connect to beehive at " + connection.getURL()); } catch (IOException e) { throw new AgentException("Failed to connect to beehive", e); } }
11
Code Sample 1: private void copy(File from, File to) throws IOException { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); byte[] line = new byte[16384]; int bytes = -1; while ((bytes = in.read(line)) != -1) out.write(line, 0, bytes); in.close(); out.close(); } Code Sample 2: public static long writeInputStreamToOutputStream(final InputStream in, final OutputStream out) { long size = 0; try { size = IOUtils.copyLarge(in, out); } catch (IOException e1) { e1.printStackTrace(); } return size; }
00
Code Sample 1: public static String toPWD(String pwd) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(pwd.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } Code Sample 2: protected void configureGraphicalViewer() { super.configureGraphicalViewer(); GraphicalViewer viewer = getGraphicalViewer(); viewer.setEditPartFactory(createEditPartFactory()); ScalableRootEditPart rootEditPart = new ScalableRootEditPart(); viewer.setRootEditPart(rootEditPart); ZoomManager manager = rootEditPart.getZoomManager(); double[] zoomLevels = new double[] { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 10.0, 20.0 }; manager.setZoomLevels(zoomLevels); ArrayList zoomContributions = new ArrayList(); zoomContributions.add(ZoomManager.FIT_ALL); zoomContributions.add(ZoomManager.FIT_HEIGHT); zoomContributions.add(ZoomManager.FIT_WIDTH); manager.setZoomLevelContributions(zoomContributions); getActionRegistry().registerAction(new ZoomInAction(manager)); getActionRegistry().registerAction(new ZoomOutAction(manager)); getGraphicalViewer().setKeyHandler(new GraphicalViewerKeyHandler(getGraphicalViewer())); String menuId = this.getClass().getName() + ".EditorContext"; MenuManager menuMgr = new MenuManager(menuId, menuId); openPropertyAction = new OpenPropertyViewAction(viewer); openOutlineAction = new OpenOutlineViewAction(viewer); saveAsImageAction = new SaveAsImageAction(viewer); createDiagramAction(viewer); getSite().registerContextMenu(menuId, menuMgr, viewer); PrintAction printAction = new PrintAction(this); printAction.setImageDescriptor(UMLPlugin.getImageDescriptor("icons/print.gif")); getActionRegistry().registerAction(printAction); final DeleteAction deleteAction = new DeleteAction((IWorkbenchPart) this); deleteAction.setSelectionProvider(getGraphicalViewer()); getActionRegistry().registerAction(deleteAction); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { deleteAction.update(); } }); menuMgr.add(new Separator("edit")); menuMgr.add(getActionRegistry().getAction(ActionFactory.DELETE.getId())); menuMgr.add(getActionRegistry().getAction(ActionFactory.UNDO.getId())); menuMgr.add(getActionRegistry().getAction(ActionFactory.REDO.getId())); menuMgr.add(new Separator("zoom")); menuMgr.add(getActionRegistry().getAction(GEFActionConstants.ZOOM_IN)); menuMgr.add(getActionRegistry().getAction(GEFActionConstants.ZOOM_OUT)); fillDiagramPopupMenu(menuMgr); menuMgr.add(new Separator("print")); menuMgr.add(saveAsImageAction); menuMgr.add(printAction); menuMgr.add(new Separator("views")); menuMgr.add(openPropertyAction); menuMgr.add(openOutlineAction); menuMgr.add(new Separator("generate")); menuMgr.add(new Separator("additions")); viewer.setContextMenu(menuMgr); viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer).setParent(getCommonKeyHandler())); }
00
Code Sample 1: protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); } Code Sample 2: public boolean createUser(String username, String password, String name) throws Exception { boolean user_created = false; try { statement = connect.prepareStatement("SELECT COUNT(*) from toepen.users WHERE username = ? LIMIT 1"); statement.setString(1, username); resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); long ctime = System.currentTimeMillis() / 1000; statement = connect.prepareStatement("INSERT INTO toepen.users " + "(username, password, name, ctime) " + "VALUES (?, ?, ?, ?)"); statement.setString(1, username); statement.setString(2, password_hash); statement.setString(3, name); statement.setLong(4, ctime); if (statement.executeUpdate() > 0) { user_created = true; } } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_created; } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
11
Code Sample 1: private static MapEntry<String, Properties> loadFpmConf() throws ConfigurationReadException { MapEntry<String, Properties> ret = null; Scanner sc = new Scanner(CONF_PATHS).useDelimiter(SEP_P); String prev = ""; while (sc.hasNext() && !hasLoaded) { Properties fpmConf = null; boolean relative = false; String path = sc.next(); if (path.startsWith(PREV_P)) { path = path.replace(PREV_P, prev.substring(0, prev.length() - 1)); } else if (path.startsWith(REL_P)) { path = path.replace(REL_P + FS, ""); relative = true; } else if (path.contains(HOME_P)) { path = path.replace(HOME_P, USER_HOME); } prev = path; path = path.concat(MAIN_CONF_FILE); try { InputStream is = null; if (relative) { is = ClassLoader.getSystemResourceAsStream(path); path = getSystemConfDir(); Strings.getOne().createPath(path); path += MAIN_CONF_FILE; FileOutputStream os = new FileOutputStream(path); IOUtils.copy(is, os); os.flush(); os.close(); os = null; } else { is = new FileInputStream(path); } fpmConf = new Properties(); fpmConf.load(is); if (fpmConf.isEmpty()) { throw new ConfigurationReadException(); } ret = new MapEntry<String, Properties>(path, fpmConf); hasLoaded = true; } catch (FileNotFoundException e) { fpmConf = null; singleton = null; hasLoaded = false; } catch (IOException e) { throw new ConfigurationReadException(); } } return ret; } Code Sample 2: private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: public BufferedImage extract() throws DjatokaException { boolean useRegion = false; int left = 0; int top = 0; int width = 50; int height = 50; boolean useleftDouble = false; Double leftDouble = 0.0; boolean usetopDouble = false; Double topDouble = 0.0; boolean usewidthDouble = false; Double widthDouble = 0.0; boolean useheightDouble = false; Double heightDouble = 0.0; if (params.getRegion() != null) { StringTokenizer st = new StringTokenizer(params.getRegion(), "{},"); String token; if ((token = st.nextToken()).contains(".")) { topDouble = Double.parseDouble(token); usetopDouble = true; } else top = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { leftDouble = Double.parseDouble(token); useleftDouble = true; } else left = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { heightDouble = Double.parseDouble(token); useheightDouble = true; } else height = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { widthDouble = Double.parseDouble(token); usewidthDouble = true; } else width = Integer.parseInt(token); useRegion = true; } try { if (is != null) { File f = File.createTempFile("tmp", ".jp2"); f.deleteOnExit(); FileOutputStream fos = new FileOutputStream(f); sourceFile = f.getAbsolutePath(); IOUtils.copyStream(is, fos); is.close(); fos.close(); } } catch (IOException e) { throw new DjatokaException(e); } try { Jp2_source inputSource = new Jp2_source(); Kdu_compressed_source input = null; Jp2_family_src jp2_family_in = new Jp2_family_src(); Jp2_locator loc = new Jp2_locator(); jp2_family_in.Open(sourceFile, true); inputSource.Open(jp2_family_in, loc); inputSource.Read_header(); input = inputSource; Kdu_codestream codestream = new Kdu_codestream(); codestream.Create(input); Kdu_channel_mapping channels = new Kdu_channel_mapping(); if (inputSource.Exists()) channels.Configure(inputSource, false); else channels.Configure(codestream); int ref_component = channels.Get_source_component(0); Kdu_coords ref_expansion = getReferenceExpansion(ref_component, channels, codestream); Kdu_dims image_dims = new Kdu_dims(); codestream.Get_dims(ref_component, image_dims); Kdu_coords imageSize = image_dims.Access_size(); Kdu_coords imagePosition = image_dims.Access_pos(); if (useleftDouble) left = imagePosition.Get_x() + (int) Math.round(leftDouble * imageSize.Get_x()); if (usetopDouble) top = imagePosition.Get_y() + (int) Math.round(topDouble * imageSize.Get_y()); if (useheightDouble) height = (int) Math.round(heightDouble * imageSize.Get_y()); if (usewidthDouble) width = (int) Math.round(widthDouble * imageSize.Get_x()); if (useRegion) { imageSize.Set_x(width); imageSize.Set_y(height); imagePosition.Set_x(left); imagePosition.Set_y(top); } int reduce = 1 << params.getLevelReductionFactor(); imageSize.Set_x(imageSize.Get_x() * ref_expansion.Get_x()); imageSize.Set_y(imageSize.Get_y() * ref_expansion.Get_y()); imagePosition.Set_x(imagePosition.Get_x() * ref_expansion.Get_x() / reduce - ((ref_expansion.Get_x() / reduce - 1) / 2)); imagePosition.Set_y(imagePosition.Get_y() * ref_expansion.Get_y() / reduce - ((ref_expansion.Get_y() / reduce - 1) / 2)); Kdu_dims view_dims = new Kdu_dims(); view_dims.Assign(image_dims); view_dims.Access_size().Set_x(imageSize.Get_x()); view_dims.Access_size().Set_y(imageSize.Get_y()); int region_buf_size = imageSize.Get_x() * imageSize.Get_y(); int[] region_buf = new int[region_buf_size]; Kdu_region_decompressor decompressor = new Kdu_region_decompressor(); decompressor.Start(codestream, channels, -1, params.getLevelReductionFactor(), 16384, image_dims, ref_expansion, new Kdu_coords(1, 1), false, Kdu_global.KDU_WANT_OUTPUT_COMPONENTS); Kdu_dims new_region = new Kdu_dims(); Kdu_dims incomplete_region = new Kdu_dims(); Kdu_coords viewSize = view_dims.Access_size(); incomplete_region.Assign(image_dims); int[] imgBuffer = new int[viewSize.Get_x() * viewSize.Get_y()]; int[] kduBuffer = null; while (decompressor.Process(region_buf, image_dims.Access_pos(), 0, 0, region_buf_size, incomplete_region, new_region)) { Kdu_coords newOffset = new_region.Access_pos(); Kdu_coords newSize = new_region.Access_size(); newOffset.Subtract(view_dims.Access_pos()); kduBuffer = region_buf; int imgBuffereIdx = newOffset.Get_x() + newOffset.Get_y() * viewSize.Get_x(); int kduBufferIdx = 0; int xDiff = viewSize.Get_x() - newSize.Get_x(); for (int j = 0; j < newSize.Get_y(); j++, imgBuffereIdx += xDiff) { for (int i = 0; i < newSize.Get_x(); i++) { imgBuffer[imgBuffereIdx++] = kduBuffer[kduBufferIdx++]; } } } BufferedImage image = new BufferedImage(imageSize.Get_x(), imageSize.Get_y(), BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, viewSize.Get_x(), viewSize.Get_y(), imgBuffer, 0, viewSize.Get_x()); if (params.getRotationDegree() > 0) { image = ImageProcessingUtils.rotate(image, params.getRotationDegree()); } decompressor.Native_destroy(); channels.Native_destroy(); if (codestream.Exists()) codestream.Destroy(); inputSource.Native_destroy(); input.Native_destroy(); jp2_family_in.Native_destroy(); return image; } catch (KduException e) { e.printStackTrace(); throw new DjatokaException(e); } catch (Exception e) { e.printStackTrace(); throw new DjatokaException(e); } } Code Sample 2: public void onUploadClicked(Event event) { Media[] medias = null; try { medias = Fileupload.get("Select one or more files to upload to " + "the current directory.", "Upload Files", 5); } catch (Exception e) { log.error("An exception occurred when displaying the file " + "upload dialog", e); } if (medias == null) { return; } for (Media media : medias) { String name = media.getName(); CSPath potentialFile = model.getPathForFile(name); if (media.isBinary()) { CSPathOutputStream writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathOutputStream(potentialFile); IOUtils.copy(media.getStreamData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } else { CSPathWriter writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathWriter(potentialFile); IOUtils.write(media.getStringData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } model.fileCleanup(potentialFile); updateFileGrid(); } }
00
Code Sample 1: public String getContentsFromVariant(SelectedVariant selected) { if (selected == null) { return null; } ActivatedVariablePolicy policy = selected.getPolicy(); Variant variant = selected.getVariant(); if (variant == null) { return null; } Content content = variant.getContent(); if (content instanceof EmbeddedContent) { EmbeddedContent embedded = (EmbeddedContent) content; return embedded.getData(); } else { MarinerURL marinerURL = computeURL((Asset) selected.getOldObject()); URL url; try { url = context.getAbsoluteURL(marinerURL); } catch (MalformedURLException e) { logger.warn("asset-mariner-url-retrieval-error", new Object[] { policy.getName(), ((marinerURL == null) ? "" : marinerURL.getExternalForm()) }, e); return null; } String text = null; try { if (logger.isDebugEnabled()) { logger.debug("Retrieving contents of URL " + url); } URLConnection connection = url.openConnection(); int contentLength = connection.getContentLength(); if (contentLength > 0) { String charset = connection.getContentEncoding(); if (charset == null) { charset = "UTF-8"; } InputStreamReader is = new InputStreamReader(connection.getInputStream(), charset); BufferedReader br = new BufferedReader(is); char[] buf = new char[contentLength]; int length = br.read(buf, 0, buf.length); text = String.copyValueOf(buf, 0, length); } } catch (IOException e) { logger.warn("asset-url-retrieval-error", new Object[] { policy.getName(), url }, e); } return text; } } Code Sample 2: public boolean write(Node node, LSOutput output) throws LSException { OutputStream out = output.getByteStream(); try { if (out == null) { String systemId = output.getSystemId(); try { URL url = new URL(systemId); URLConnection connection = url.openConnection(); connection.setDoOutput(true); if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).setRequestMethod("PUT"); } out = connection.getOutputStream(); } catch (MalformedURLException e) { File file = new File(systemId); out = new FileOutputStream(file); } } serialize(node, out); out.flush(); return true; } catch (IOException e) { throw new DomLSException(LSException.SERIALIZE_ERR, e); } }
11
Code Sample 1: private static final void cloneFile(File origin, File target) throws IOException { FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(origin).getChannel(); destChannel = new FileOutputStream(target).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) srcChannel.close(); if (destChannel != null) destChannel.close(); } } Code Sample 2: private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
11
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: public void render(HttpServletRequest request, HttpServletResponse response, File file, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } if (file.length() > Integer.MAX_VALUE) { throw new IllegalArgumentException("Cannot send file greater than 2GB"); } response.setContentLength((int) file.length()); IOUtils.copy(new FileInputStream(file), response.getOutputStream()); }
00
Code Sample 1: private boolean streamDownload(URL url, File file) { try { InputStream in = url.openConnection().getInputStream(); BufferedInputStream bis = new BufferedInputStream(in); OutputStream out = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(out); int chunkSize = 63 * 1024; byte[] ba = new byte[chunkSize]; while (true) { int bytesRead = readBlocking(bis, ba, 0, chunkSize); if (bytesRead > 0) { if (bos != null) bos.write(ba, 0, bytesRead); } else { bos.close(); break; } } } catch (IOException e) { System.out.println("Error writing file " + file); return false; } System.out.println("OK writing file " + file); return true; } Code Sample 2: private boolean write(File file) { String filename = file.getPath(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteArrayOutputStream); try { StringBuffer xml = null; if (MainFrame.getInstance().getAnimation() != null) { MainFrame.getInstance().getAnimation().xml(out, "\t"); } else { xml = MainFrame.getInstance().getModel().xml("\t"); } if (file.exists()) { BufferedReader reader = new BufferedReader(new FileReader(filename)); BufferedWriter writer = new BufferedWriter(new FileWriter(filename + "~")); char[] buffer = new char[65536]; int charsRead = 0; while ((charsRead = reader.read(buffer)) > 0) writer.write(buffer, 0, charsRead); reader.close(); writer.close(); } BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write("<jpatch version=\"" + VersionInfo.ver + "\">\n"); if (xml != null) writer.write(xml.toString()); else writer.write(byteArrayOutputStream.toString()); writer.write("</jpatch>\n"); writer.close(); MainFrame.getInstance().getUndoManager().setChange(false); if (MainFrame.getInstance().getAnimation() != null) MainFrame.getInstance().getAnimation().setFile(file); else MainFrame.getInstance().getModel().setFile(file); MainFrame.getInstance().setFilename(file.getName()); return true; } catch (IOException ioException) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Unable to save file \"" + filename + "\"\n" + ioException, "Error", JOptionPane.ERROR_MESSAGE); return false; } }
11
Code Sample 1: @Override public void handle(HttpExchange http) throws IOException { Headers reqHeaders = http.getRequestHeaders(); Headers respHeader = http.getResponseHeaders(); respHeader.add("Content-Type", "text/plain"); http.sendResponseHeaders(200, 0); PrintWriter console = new PrintWriter(System.err); PrintWriter web = new PrintWriter(http.getResponseBody()); PrintWriter out = new PrintWriter(new YWriter(web, console)); out.println("### " + new Date() + " ###"); out.println("Method: " + http.getRequestMethod()); out.println("Protocol: " + http.getProtocol()); out.println("RemoteAddress.HostName: " + http.getRemoteAddress().getHostName()); for (String key : reqHeaders.keySet()) { out.println("* \"" + key + "\""); for (String v : reqHeaders.get(key)) { out.println("\t" + v); } } InputStream in = http.getRequestBody(); if (in != null) { out.println(); IOUtils.copyTo(new InputStreamReader(in), out); in.close(); } out.flush(); out.close(); } Code Sample 2: public static File copyFile(File file, String dirName) { File destDir = new File(dirName); if (!destDir.exists() || !destDir.isDirectory()) { destDir.mkdirs(); } File src = file; File dest = new File(dirName, src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
00
Code Sample 1: private boolean getCached(Get g) throws IOException { boolean ret = false; File f = getCachedFile(g); if (f.exists()) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(f); os = new FileOutputStream(getDestFile(g)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; } Code Sample 2: @Override public int deleteStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); int result = statement.executeUpdate(sql.toString()); if (result == 0) log.warn(sql + " result row count is 0"); getConnection().commit(); return result; } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); throw new RuntimeException(); } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
11
Code Sample 1: private void copyImage(ProjectElement e) throws Exception { String fn = e.getName(); if (!fn.toLowerCase().endsWith(".png")) { if (fn.contains(".")) { fn = fn.substring(0, fn.lastIndexOf('.')) + ".png"; } else { fn += ".png"; } } File img = new File(resFolder, fn); File imgz = new File(resoutFolder.getAbsolutePath(), fn + ".zlib"); boolean copy = true; if (img.exists() && config.containsKey(img.getName())) { long modified = Long.parseLong(config.get(img.getName())); if (modified >= img.lastModified()) { copy = false; } } if (copy) { convertImage(e.getFile(), img); config.put(img.getName(), String.valueOf(img.lastModified())); } DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(imgz))); BufferedInputStream in = new BufferedInputStream(new FileInputStream(img)); int read; while ((read = in.read()) != -1) { out.write(read); } out.close(); in.close(); imageFiles.add(imgz); imageNames.put(imgz, e.getName()); } 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 void loginWuploader() throws IOException { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to Wupload"); HttpPost httppost = new HttpPost("http://www.wupload.in/account/login"); httppost.setHeader("Referer", "http://www.wupload.in/"); httppost.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("email", uname)); formparams.add(new BasicNameValuePair("password", pwd)); formparams.add(new BasicNameValuePair("redirect", "/")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("PHPSESSID")) { sessioncookie = "PHPSESSID=" + escookie.getValue(); System.out.println(sessioncookie); } if (escookie.getName().equalsIgnoreCase("email")) { mailcookie = "email=" + escookie.getValue(); login = true; System.out.println(mailcookie); } if (escookie.getName().equalsIgnoreCase("nickname")) { namecookie = "nickname=" + escookie.getValue(); System.out.println(namecookie); } if (escookie.getName().equalsIgnoreCase("isAffiliate")) { affiliatecookie = "isAffiliate=" + escookie.getValue(); System.out.println(affiliatecookie); } if (escookie.getName().equalsIgnoreCase("role")) { rolecookie = "role=" + escookie.getValue(); System.out.println(rolecookie); } } if (login) { System.out.println("Login Success"); getFolderCookies(); } else { System.out.println("Login failed"); } } Code Sample 2: public void writeBack(File destinationFile, boolean makeCopy) throws IOException { if (makeCopy) { FileChannel sourceChannel = new java.io.FileInputStream(getFile()).getChannel(); FileChannel destinationChannel = new java.io.FileOutputStream(destinationFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } else { getFile().renameTo(destinationFile); } if (getExifTime() != null && getOriginalTime() != null && !getExifTime().equals(getOriginalTime())) { String adjustArgument = "-ts" + m_dfJhead.format(getExifTime()); ProcessBuilder pb = new ProcessBuilder(m_tm.getJheadCommand(), adjustArgument, destinationFile.getAbsolutePath()); pb.directory(destinationFile.getParentFile()); System.out.println(pb.command().get(0) + " " + pb.command().get(1) + " " + pb.command().get(2)); final Process p = pb.start(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } }
00
Code Sample 1: protected void init() { if (this.strUrl != null) { InputStream in = null; try { URL url = ClassLoader.getSystemClassLoader().getResource(strUrl); if (url != null) { in = url.openStream(); if (in != null) { props.load(in); } } } catch (IOException e) { Logger.defaultLogger().error("Error during framework properties loading", e); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } } } Code Sample 2: public static void copy_file(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } 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); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: protected void shutdown(final boolean unexpected) { ControlerState oldState = this.state; this.state = ControlerState.Shutdown; if (oldState == ControlerState.Running) { 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); } this.controlerListenerManager.fireControlerShutdownEvent(unexpected); if (this.dumpDataAtEnd) { Knowledges kk; if (this.config.scenario().isUseKnowledges()) { kk = (this.getScenario()).getKnowledges(); } else { kk = this.getScenario().retrieveNotEnabledKnowledges(); } new PopulationWriter(this.population, this.network, kk).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)); ActivityFacilities facilities = this.getFacilities(); if (facilities != null) { new FacilitiesWriter((ActivityFacilitiesImpl) facilities).write(this.controlerIO.getOutputFilename("output_facilities.xml.gz")); } if (((NetworkFactoryImpl) this.network.getFactory()).isTimeVariant()) { new NetworkChangeEventsWriter().write(this.controlerIO.getOutputFilename("output_change_events.xml.gz"), ((NetworkImpl) this.network).getNetworkChangeEvents()); } if (this.config.scenario().isUseHouseholds()) { new HouseholdsWriterV10(this.scenarioData.getHouseholds()).writeFile(this.controlerIO.getOutputFilename(FILENAME_HOUSEHOLDS)); } if (this.config.scenario().isUseLanes()) { new LaneDefinitionsWriter20(this.scenarioData.getScenarioElement(LaneDefinitions20.class)).write(this.controlerIO.getOutputFilename(FILENAME_LANES)); } 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 getResponseAsStream(String _url, Object _stringOrStream, OutputStream _stream, Map _headers, Map _params, String _contentType, int _timeout) throws IOException { if (_url == null || _url.length() <= 0) throw new IllegalArgumentException("Url can not be null."); String temp = _url.toLowerCase(); if (!temp.startsWith("http://") && !temp.startsWith("https://")) _url = "http://" + _url; HttpMethod method = null; if (_stringOrStream == null && (_params == null || _params.size() <= 0)) method = new GetMethod(_url); else method = new PostMethod(_url); HttpMethodParams params = ((HttpMethodBase) method).getParams(); if (params == null) { params = new HttpMethodParams(); ((HttpMethodBase) method).setParams(params); } if (_timeout < 0) params.setSoTimeout(0); else params.setSoTimeout(_timeout); if (_contentType != null && _contentType.length() > 0) { if (_headers == null) _headers = new HashMap(); _headers.put("Content-Type", _contentType); } if (_headers != null) { Iterator iter = _headers.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); method.setRequestHeader((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof PostMethod && (_params != null && _params.size() > 0)) { Iterator iter = _params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); ((PostMethod) method).addParameter((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof EntityEnclosingMethod && _stringOrStream != null) { if (_stringOrStream instanceof InputStream) { RequestEntity entity = new InputStreamRequestEntity((InputStream) _stringOrStream); ((EntityEnclosingMethod) method).setRequestEntity(entity); } else { RequestEntity entity = new StringRequestEntity(_stringOrStream.toString(), _contentType, null); ((EntityEnclosingMethod) method).setRequestEntity(entity); } } HttpClient httpClient = new HttpClient(new org.apache.commons.httpclient.SimpleHttpConnectionManager()); try { int status = httpClient.executeMethod(method); if (status != HttpStatus.SC_OK) { if (status >= 500 && status < 600) throw new IOException("Remote service<" + _url + "> respose a error, status:" + status); } InputStream instream = method.getResponseBodyAsStream(); IOUtils.copy(instream, _stream); instream.close(); } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } }
00
Code Sample 1: public static String getDigest(String seed, String code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } } Code Sample 2: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
11
Code Sample 1: @Override public String getData(String blipApiPath, String authHeader) { try { URL url = new URL(BLIP_API_URL + blipApiPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (authHeader != null) { conn.addRequestProperty("Authorization", "Basic " + authHeader); } BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuffer content = new StringBuffer(); System.out.println("Resp code " + conn.getResponseCode()); while ((line = reader.readLine()) != null) { System.out.println(">> " + line); content.append(line); } reader.close(); return content.toString(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } } Code Sample 2: public void startElement(String uri, String tag, String qName, org.xml.sax.Attributes attributes) throws SAXException { wabclient.Attributes prop = new wabclient.Attributes(attributes); try { if (tag.equals("window")) startWindow(prop); else if (tag.equals("splitpanel")) startSplitPanel(prop); else if (tag.equals("desktoppane")) startDesktopPane(prop); else if (tag.equals("tabcontrol")) startTabcontrol(prop); else if (tag.equals("panel")) startPanel(prop); else if (tag.equals("statusbar")) startStatusbar(prop); else if (tag.equals("toolbar")) startToolbar(prop); else if (tag.equals("toolbarbutton")) startToolbarbutton(prop); else if (tag.equals("menu")) startMenu(prop); else if (tag.equals("menuitem")) startMenuitem(prop); else if (tag.equals("separator")) menu.addSeparator(); else if (tag.equals("choice")) startChoice(prop); else if (tag.equals("list")) startList(prop); else if (tag.equals("option")) startOption(prop); else if (tag.equals("label")) startLabel(prop); else if (tag.equals("button")) startButton(prop); else if (tag.equals("groupbox")) startGroupbox(prop); else if (tag.equals("radiobutton")) startRadioButton(prop); else if (tag.equals("checkbox")) startCheckbox(prop); else if (tag.equals("image")) startImage(prop); else if (tag.equals("textarea")) startTextArea(prop); else if (tag.equals("singlelineedit")) startSingleLineEdit(prop); else if (tag.equals("treeview")) startTreeview(prop); else if (tag.equals("treeitem")) startTreeitem(prop); else if (tag.equals("table")) startTable(prop); else if (tag.equals("header")) startHeader(prop); else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.addRow(); } else if (tag.equals("column")) { columnNumber++; if (prop == null) { System.err.println("table.column without properties"); return; } String value = prop.getValue("value", ""); model.setValueAt(value, rowNumber - 1, columnNumber - 1); } else if (tag.equals("rmbmenuitem")) { if (prop == null) { System.err.println("datawindow.menuitem without properties"); return; } String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); JMenuItem mi = new JMenuItem(label); mi.setActionCommand(action); mi.addActionListener(win); rmbmenu.add(mi); } else if (tag.equals("rmbseparator")) { rmbmenu.addSeparator(); } else if (tag.equals("script")) { win.beginScript(); String url = prop.getValue("src"); if (url.length() > 0) { try { BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String buffer; while (true) { buffer = r.readLine(); if (buffer == null) break; win.script += buffer + "\n"; } r.close(); win.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[win] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } }
00
Code Sample 1: @Override public void execute() throws BuildException { if (this.toFile == null && this.toDir == null) throw new BuildException("Missing Destination File/Dir"); if (this.toFile != null && this.toDir != null) throw new BuildException("Both Defined Destination File/Dir"); if (this.urlStr == null) throw new BuildException("Missing URL"); URL base = null; try { if (baseStr != null) base = new URL(this.baseStr + (baseStr.endsWith("/") ? "" : "/")); } catch (MalformedURLException e) { throw new BuildException(e); } String tokens[] = this.urlStr.split("[ \t\n]+"); try { for (String nextURL : tokens) { nextURL = nextURL.trim(); if (nextURL.length() == 0) continue; URL url = null; try { url = new URL(base, nextURL); } catch (MalformedURLException e) { throw new BuildException(e); } File dest = null; if (this.toDir != null) { String file = url.getFile(); int i = file.lastIndexOf('/'); if (i != -1 && i + 1 != file.length()) file = file.substring(i + 1); dest = new File(this.toDir, file); } else { dest = this.toFile; } if (dest.exists()) continue; byte buff[] = new byte[2048]; FileOutputStream out = new FileOutputStream(dest); InputStream in = url.openStream(); int n = 0; while ((n = in.read(buff)) != -1) { out.write(buff, 0, n); } in.close(); out.flush(); out.close(); System.out.println("Downloaded " + url + " to " + dest); } } catch (IOException e) { throw new BuildException(e); } } Code Sample 2: public File takeFile(File f, String prefix, String suffix) throws IOException { File nf = createNewFile(prefix, suffix); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); FileOutputStream fos = new FileOutputStream(nf); FileChannel foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); f.delete(); return nf; }
00
Code Sample 1: public static boolean verifyPassword(String digest, String password) { String alg = null; int size = 0; if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) { digest = digest.substring(5); alg = "MD5"; size = 16; } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) { digest = digest.substring(6); alg = "MD5"; size = 16; } try { MessageDigest sha = MessageDigest.getInstance(alg); if (sha == null) { return false; } byte[][] hs = split(Base64.decode(digest), size); byte[] hash = hs[0]; byte[] salt = hs[1]; sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); return MessageDigest.isEqual(hash, pwhash); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } } Code Sample 2: public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest.getName()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; }
11
Code Sample 1: public ScoreModel(URL url) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; list = new ArrayList<ScoreModelItem>(); map = new HashMap<String, ScoreModelItem>(); line = in.readLine(); int n = 1; String[] rowAttrib; ScoreModelItem item; while ((line = in.readLine()) != null) { rowAttrib = line.split(";"); item = new ScoreModelItem(n, Double.valueOf(rowAttrib[3]), Double.valueOf(rowAttrib[4]), Double.valueOf(rowAttrib[2]), Double.valueOf(rowAttrib[5]), rowAttrib[1]); list.add(item); map.put(item.getHash(), item); n++; } in.close(); } Code Sample 2: private static String getProviderName(URL url, PrintStream err) { InputStream in = null; try { in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String result = null; while (true) { String line = reader.readLine(); if (line == null) { break; } int commentPos = line.indexOf('#'); if (commentPos >= 0) { line = line.substring(0, commentPos); } line = line.trim(); int len = line.length(); if (len != 0) { if (result != null) { print(err, "checkconfig.multiproviders", url.toString()); return null; } result = line; } } if (result == null) { print(err, "checkconfig.missingprovider", url.toString()); return null; } return result; } catch (IOException e) { print(err, "configconfig.read", url.toString(), e); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
00
Code Sample 1: public void testCodingCompletedFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 5); encoder.write(wrap("stuff")); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("more stuff"); wrtout.flush(); wrtout.close(); try { FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 10); fail("IllegalStateException should have been thrown"); } catch (IllegalStateException ex) { } finally { tmpFile.delete(); } } Code Sample 2: public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { InputStream urlStream = url.openStream(); AudioFileFormat fileFormat = null; try { fileFormat = getFMT(urlStream, false); } finally { if (fileFormat == null) { urlStream.close(); } } return new AudioInputStream(urlStream, fileFormat.getFormat(), fileFormat.getFrameLength()); }
11
Code Sample 1: 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); } } Code Sample 2: private static void copy(File source, File target) throws IOException { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(source)); os = new BufferedOutputStream(new FileOutputStream(target)); int b; while ((b = is.read()) > -1) os.write(b); } finally { try { if (is != null) is.close(); } catch (IOException ignore) { } try { if (os != null) os.close(); } catch (IOException ignore) { } } }
00
Code Sample 1: public int deleteFile(Integer[] fileID) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; Connection conn = null; int nbrow = 0; try { DataSource ds = getDataSource(DEFAULT_DATASOURCE); conn = ds.getConnection(); conn.setAutoCommit(false); if (log.isDebugEnabled()) { log.debug("FileDAOImpl.deleteFile() " + DELETE_FILES_LOGIC); } for (int i = 0; i < fileID.length; i++) { pstmt = conn.prepareStatement(DELETE_FILES_LOGIC); pstmt.setInt(1, fileID[i].intValue()); nbrow = pstmt.executeUpdate(); } } catch (SQLException e) { conn.rollback(); log.error("FileDAOImpl.deleteFile() : erreur technique", e); throw e; } finally { conn.commit(); closeRessources(conn, pstmt, rs); } return nbrow; } Code Sample 2: public static void fastBackup(File file) { FileChannel in = null; FileChannel out = null; FileInputStream fin = null; FileOutputStream fout = null; try { in = (fin = new FileInputStream(file)).getChannel(); out = (fout = new FileOutputStream(file.getAbsolutePath() + ".bak")).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { Logging.getErrorLog().reportError("Fast backup failure (" + file.getAbsolutePath() + "): " + e.getMessage()); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file input stream", e); } } if (fout != null) { try { fout.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file output stream", e); } } if (in != null) { try { in.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file channel", e); } } if (out != null) { try { out.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file channel", e); } } } }
11
Code Sample 1: protected static boolean copyFile(File src, File dest) { try { if (!dest.exists()) { dest.createNewFile(); } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); byte[] temp = new byte[1024 * 8]; int readSize = 0; do { readSize = fis.read(temp); fos.write(temp, 0, readSize); } while (readSize == temp.length); temp = null; fis.close(); fos.flush(); fos.close(); } catch (Exception e) { return false; } return true; } Code Sample 2: public static void copy(File source, File sink) throws IOException { if (source == null) throw new NullPointerException("Source file must not be null"); if (sink == null) throw new NullPointerException("Target file must not be null"); if (!source.exists()) throw new IOException("Source file " + source.getPath() + " does not exist"); if (!source.isFile()) throw new IOException("Source file " + source.getPath() + " is not a regular file"); if (!source.canRead()) throw new IOException("Source file " + source.getPath() + " can not be read (missing acces right)"); if (!sink.exists()) throw new IOException("Target file " + sink.getPath() + " does not exist"); if (!sink.isFile()) throw new IOException("Target file " + sink.getPath() + " is not a regular file"); if (!sink.canWrite()) throw new IOException("Target file " + sink.getPath() + " is write protected"); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(source); output = new FileOutputStream(sink); byte[] buffer = new byte[1024]; while (input.available() > 0) { int bread = input.read(buffer); if (bread > 0) output.write(buffer, 0, bread); } } finally { if (input != null) try { input.close(); } catch (IOException x) { } if (output != null) try { output.close(); } catch (IOException x) { } } }
00
Code Sample 1: public String doUpload(@ParamName(name = "file") MultipartFile file, @ParamName(name = "uploadDirectory") String _uploadDirectory) throws IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); String tempUploadDir = MewitProperties.getTemporaryUploadDirectory(); if (!tempUploadDir.endsWith("/") && !tempUploadDir.endsWith("\\")) { tempUploadDir += "\\"; } String fileName = null; int position = file.getOriginalFilename().lastIndexOf("."); if (position <= 0) { fileName = java.util.UUID.randomUUID().toString(); } else { fileName = java.util.UUID.randomUUID().toString() + file.getOriginalFilename().substring(position); } File outputFile = new File(tempUploadDir, fileName); log(INFO, "writing the content of uploaded file to: " + outputFile); FileOutputStream fos = new FileOutputStream(outputFile); IOUtils.copy(file.getInputStream(), fos); file.getInputStream().close(); fos.close(); return doUploadFile(sessionId, outputFile, file.getOriginalFilename()); } Code Sample 2: protected void handleConnection(Socket server) throws IOException { OutputStream out = server.getOutputStream(); PrintWriter pout = new PrintWriter(out, true); BufferedReader in = SocketUtil.getReader(server); String failureReason = null; int failureCode = 0; String httpVersion = "HTTP/1.0"; String uri = null; String command = in.readLine(); URL url = null; if (command != null) { StringTokenizer tokenizer = new StringTokenizer(command); if (tokenizer.countTokens() != 3) { failureCode = 400; failureReason = "Illformed Request-Line"; } else { String method = tokenizer.nextToken(); if (!method.equalsIgnoreCase("get")) { failureCode = 501; failureReason = "Only supports GET method"; } else { uri = tokenizer.nextToken(); httpVersion = tokenizer.nextToken(); try { url = getURL(uri); } catch (IOException e) { failureCode = 404; failureReason = "resource not found"; } } } } else { failureCode = 400; failureReason = "Null request"; } if (url != null) { InputStream stream = null; try { URLConnection connection = url.openConnection(); byte[] chunk = new byte[1024]; int read = 0; pout.println(httpVersion + " 200 "); pout.println("Content-Type: " + connection.getContentType()); pout.println("Content-Length: " + connection.getContentLength()); pout.println("Content-Encoding: " + connection.getContentEncoding()); pout.println(); stream = connection.getInputStream(); read = stream.read(chunk); while (read != -1) { out.write(chunk, 0, read); read = stream.read(chunk); } } catch (IOException e) { failureCode = 500; failureReason = "problem reading the resource content"; } finally { if (stream != null) { stream.close(); } } } else { failureCode = 404; failureReason = "resource not found"; } if (failureCode != 0) { pout.println(httpVersion + " " + failureCode + " " + failureReason); pout.println(); } doDelay(); server.close(); }
00
Code Sample 1: public void connect() throws ClientProtocolException, IOException { HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); inputStream = entity.getContent(); Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { HeaderElement[] codecs = contentEncodingHeader.getElements(); for (HeaderElement encoding : codecs) { if (encoding.getName().equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(inputStream); } } } inputStream = new BufferedInputStream(inputStream, 2048); } Code Sample 2: @Override public void dispatchContent(InputStream is) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Sending content message over JMS"); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(is, bos); this.send(new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { BytesMessage message = session.createBytesMessage(); message.writeBytes(bos.toByteArray()); return message; } }); }
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: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment) throws IOException, MessagingException { writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\""); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName + "\";" + "\n size=" + Long.toString(attachment.mSize)); writeHeader(writer, "Content-ID", attachment.mContentId); writer.append("\r\n"); InputStream inStream = null; try { Uri fileUri = Uri.parse(attachment.mContentUri); inStream = context.getContentResolver().openInputStream(fileUri); writer.flush(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(inStream, base64Out); base64Out.close(); } catch (FileNotFoundException fnfe) { } catch (IOException ioe) { throw new MessagingException("Invalid attachment.", ioe); } } Code Sample 2: public static void createModelZip(String filename, String tempdir, boolean overwrite) throws Exception { FileTools.checkOutput(filename, overwrite); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); }
11
Code Sample 1: public static boolean copy(File source, File dest) { 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); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } Code Sample 2: public void invoke(InputStream is) throws AgentException { try { addHeader("Content-Type", "application/zip"); addHeader("Content-Length", String.valueOf(is.available())); connection.setDoOutput(true); connection.connect(); OutputStream os = connection.getOutputStream(); boolean success = false; try { IOUtils.copy(is, os); success = true; } finally { try { os.flush(); os.close(); } catch (IOException x) { if (success) throw x; } } connection.disconnect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new AgentException("Failed to execute REST call at " + connection.getURL() + ": " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (ConnectException e) { throw new AgentException("Failed to connect to beehive at " + connection.getURL()); } catch (IOException e) { throw new AgentException("Failed to connect to beehive", e); } }
00
Code Sample 1: public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; } Code Sample 2: @Override public String compute_hash(String plaintext) { MessageDigest d; try { d = MessageDigest.getInstance(get_algorithm_name()); d.update(plaintext.getBytes()); byte[] hash = d.digest(); StringBuffer sb = new StringBuffer(); for (byte b : hash) sb.append(String.format("%02x", b)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public void downSync(Vector v) throws SQLException { try { con = allocateConnection(tableName); PreparedStatement update = con.prepareStatement("update cal_Event set owner=?,subject=?,text=?,place=?," + "contactperson=?,startdate=?,enddate=?,starttime=?,endtime=?,allday=?," + "syncstatus=?,dirtybits=? where OId=? and syncstatus=?"); PreparedStatement insert = con.prepareStatement("insert into cal_Event (owner,subject,text,place," + "contactperson,startdate,enddate,starttime,endtime,allday,syncstatus," + "dirtybits) values(?,?,?,?,?,?,?,?,?,?,?,?)"); PreparedStatement insert1 = con.prepareStatement(DBUtil.getQueryCurrentOID(con, "cal_Event", "newoid")); PreparedStatement delete1 = con.prepareStatement("delete from cal_Event_Remind where event=?"); PreparedStatement delete2 = con.prepareStatement("delete from cal_Event where OId=? " + "and (syncstatus=? or syncstatus=?)"); for (int i = 0; i < v.size(); i++) { try { DO = (EventDO) v.elementAt(i); if (DO.getSyncstatus() == INSERT) { insert.setBigDecimal(1, DO.getOwner()); insert.setString(2, DO.getSubject()); insert.setString(3, DO.getText()); insert.setString(4, DO.getPlace()); insert.setString(5, DO.getContactperson()); insert.setDate(6, DO.getStartdate()); insert.setDate(7, DO.getEnddate()); insert.setTime(8, DO.getStarttime()); insert.setTime(9, DO.getEndtime()); insert.setBoolean(10, DO.getAllday()); insert.setInt(11, RESET); insert.setInt(12, RESET); con.executeUpdate(insert, null); con.reset(); rs = con.executeQuery(insert1, null); if (rs.next()) DO.setOId(rs.getBigDecimal("newoid")); con.reset(); } else if (DO.getSyncstatus() == UPDATE) { update.setBigDecimal(1, DO.getOwner()); update.setString(2, DO.getSubject()); update.setString(3, DO.getText()); update.setString(4, DO.getPlace()); update.setString(5, DO.getContactperson()); update.setDate(6, DO.getStartdate()); update.setDate(7, DO.getEnddate()); update.setTime(8, DO.getStarttime()); update.setTime(9, DO.getEndtime()); update.setBoolean(10, DO.getAllday()); update.setInt(11, RESET); update.setInt(12, RESET); update.setBigDecimal(13, DO.getOId()); update.setInt(14, RESET); con.executeUpdate(update, null); con.reset(); } else if (DO.getSyncstatus() == DELETE) { try { con.setAutoCommit(false); delete1.setBigDecimal(1, DO.getOId()); con.executeUpdate(delete1, null); delete2.setBigDecimal(1, DO.getOId()); delete2.setInt(2, RESET); delete2.setInt(3, DELETE); if (con.executeUpdate(delete2, null) < 1) { con.rollback(); } else { con.commit(); } } catch (Exception e) { con.rollback(); throw e; } finally { con.reset(); } } } catch (Exception e) { if (DO != null) logError("Sync-EventDO.owner = " + DO.getOwner().toString() + " oid = " + (DO.getOId() != null ? DO.getOId().toString() : "NULL"), e); } } if (rs != null) { rs.close(); } } catch (SQLException e) { if (DEBUG) logError("", e); throw e; } finally { release(); } } Code Sample 2: 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(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { Log.debug(fnfe); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: public void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: @Test public void testGrantLicense() throws Exception { context.turnOffAuthorisationSystem(); Item item = Item.create(context); String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); LicenseUtils.grantLicense(context, item, defaultLicense); StringWriter writer = new StringWriter(); IOUtils.copy(item.getBundles("LICENSE")[0].getBitstreams()[0].retrieve(), writer); String license = writer.toString(); assertThat("testGrantLicense 0", license, equalTo(defaultLicense)); context.restoreAuthSystemState(); }
00
Code Sample 1: private void moveFile(File orig, File target) throws IOException { byte buffer[] = new byte[1000]; int bread = 0; FileInputStream fis = new FileInputStream(orig); FileOutputStream fos = new FileOutputStream(target); while (bread != -1) { bread = fis.read(buffer); if (bread != -1) fos.write(buffer, 0, bread); } fis.close(); fos.close(); orig.delete(); } Code Sample 2: @Test public void testCustomerResource() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); System.out.println("**** CustomerResource No Query params ***"); HttpGet get = new HttpGet("http://localhost:9095/customers"); HttpResponse response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } System.out.println("**** CustomerResource With Query params ***"); get = new HttpGet("http://localhost:9095/customers?start=1&size=3"); response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } System.out.println("**** CustomerResource With UriInfo and Query params ***"); get = new HttpGet("http://localhost:9095/customers/uriinfo?start=2&size=2"); response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } }
11
Code Sample 1: protected static boolean copyFile(File src, File dest) { try { if (!dest.exists()) { dest.createNewFile(); } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); byte[] temp = new byte[1024 * 8]; int readSize = 0; do { readSize = fis.read(temp); fos.write(temp, 0, readSize); } while (readSize == temp.length); temp = null; fis.close(); fos.flush(); fos.close(); } catch (Exception e) { return false; } return true; } Code Sample 2: public static void copyFile(final File source, final 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(); } } }
00
Code Sample 1: public boolean backup() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/android.bluebox/databases/bluebox.db"; String backupDBPath = "/Android/bluebox.bak"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: public String encryptToMD5(String info) { byte[] digesta = null; try { MessageDigest alga = MessageDigest.getInstance("MD5"); alga.update(info.getBytes()); digesta = alga.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String rs = byte2hex(digesta); return rs; }
11
Code Sample 1: public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); } Code Sample 2: public void testReaderWriterUC2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); }
11
Code Sample 1: public static IChemModel readInChI(URL url) throws CDKException { IChemModel chemModel = new ChemModel(); try { IMoleculeSet moleculeSet = new MoleculeSet(); chemModel.setMoleculeSet(moleculeSet); StdInChIParser parser = new StdInChIParser(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { if (line.toLowerCase().startsWith("inchi=")) { IAtomContainer atc = parser.parseInchi(line); moleculeSet.addAtomContainer(atc); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new CDKException(e.getMessage()); } return chemModel; } Code Sample 2: public void access() { Authenticator.setDefault(new MyAuthenticator()); try { URL url = new URL("http://localhost/ws/test"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
00
Code Sample 1: public static String getHash(String key) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); return new BigInteger(digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { return key; } } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); 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 GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
11
Code Sample 1: private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText(Messages.getString("gui.AdministracionResorces.6")); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { 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(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonImagen; } Code Sample 2: private static boolean copyFile(File src, File dest) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } if (fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
11
Code Sample 1: @Override public void download(String remoteFilePath, String localFilePath) { InputStream remoteStream = null; try { remoteStream = client.get(remoteFilePath); } catch (IOException e) { e.printStackTrace(); } OutputStream localStream = null; try { localStream = new FileOutputStream(new File(localFilePath)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { IOUtils.copy(remoteStream, localStream); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private synchronized void ensureParsed() throws IOException, BadIMSCPException { if (cp != null) return; if (on_disk == null) { on_disk = createTemporaryFile(); OutputStream to_disk = new FileOutputStream(on_disk); IOUtils.copy(in.getInputStream(), to_disk); to_disk.close(); } try { ZipFilePackageParser parser = utils.getIMSCPParserFactory().createParser(); parser.parse(on_disk); cp = parser.getPackage(); } catch (BadParseException x) { throw new BadIMSCPException("Cannot parse content package", x); } } Code Sample 2: @Test @Ignore public void testToJson() throws IOException { JsonSerializer js = new StreamingJsonSerializer(new ObjectMapper()); BulkOperation op = js.createBulkOperation(createTestData(10000), false); IOUtils.copy(op.getData(), System.out); }
00
Code Sample 1: @Override public void execute(JobExecutionContext context) throws JobExecutionException { super.execute(context); debug("Start execute job " + this.getClass().getName()); try { String name = "nixspam-ip.dump.gz"; String f = this.path_app_root + "/" + this.properties.get("dir") + "/"; try { org.apache.commons.io.FileUtils.forceMkdir(new File(f)); } catch (IOException ex) { fatal("IOException", ex); } f += "/" + name; String url = "http://www.dnsbl.manitu.net/download/" + name; debug("(1) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); com.utils.IOUtil.unzip(f, f.replace(".gz", "")); File file_to_read = new File(f.replaceAll(".gz", "")); BigFile lines = null; try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Excpetion", e); return; } try { Statement stat = conn_url.createStatement(); stat.executeUpdate(properties.get("query_delete")); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } boolean ok = true; int i = 0; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.substring(line.indexOf(" ")); line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } boolean del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); name = "spam-ip.com_" + DateTimeUtil.getNowWithFormat("MM-dd-yyyy") + ".csv"; f = this.path_app_root + "/" + this.properties.get("dir") + "/"; org.apache.commons.io.FileUtils.forceMkdir(new File(f)); f += "/" + name; url = "http://spam-ip.com/csv_dump/" + name; debug("(2) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); file_to_read = new File(f); try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Exception", e); return; } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } ok = true; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.split(",")[1]; line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); if (ok) { debug("Import della BlackList Concluso tot righe: " + i); try { conn_url.commit(); } catch (SQLException e) { fatal("SQLException", e); } } else { fatal("Problemi con la Blacklist"); } try { conn_url.setAutoCommit(true); } catch (SQLException e) { fatal("SQLException", e); } try { Statement stat = this.conn_url.createStatement(); stat.executeUpdate("VACUUM"); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } } catch (IOException ex) { fatal("IOException", ex); } debug("End execute job " + this.getClass().getName()); } Code Sample 2: private static boolean validateSshaPwd(String sSshaPwd, String sUserPwd) { boolean b = false; if (sSshaPwd != null && sUserPwd != null) { if (sSshaPwd.startsWith(SSHA_PREFIX)) { sSshaPwd = sSshaPwd.substring(SSHA_PREFIX.length()); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); BASE64Decoder decoder = new BASE64Decoder(); byte[] ba = decoder.decodeBuffer(sSshaPwd); byte[] hash = new byte[FIXED_HASH_SIZE]; byte[] salt = new byte[FIXED_SALT_SIZE]; System.arraycopy(ba, 0, hash, 0, FIXED_HASH_SIZE); System.arraycopy(ba, FIXED_HASH_SIZE, salt, 0, FIXED_SALT_SIZE); md.update(sUserPwd.getBytes()); md.update(salt); byte[] baPwdHash = md.digest(); b = MessageDigest.isEqual(hash, baPwdHash); } catch (Exception exc) { exc.printStackTrace(); } } } return b; }
11
Code Sample 1: public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } } Code Sample 2: public void write(URL exportUrl, OutputStream output) throws Exception { if (exportUrl == null || output == null) { throw new RuntimeException("null passed in for required parameters"); } MediaContent mc = new MediaContent(); mc.setUri(exportUrl.toString()); MediaSource ms = service.getMedia(mc); InputStream input = ms.getInputStream(); IOUtils.copy(input, output); }
11
Code Sample 1: public static String getMD5(String password) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (byte aB : b) { sb.append((Integer.toHexString((aB & 0xFF) | 0x100)).substring(1, 3)); } return sb.toString(); } Code Sample 2: public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; 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 < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { log.error("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
11
Code Sample 1: public static int unzipFile(File file_input, File dir_output) { ZipInputStream zip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); zip_in_stream = new ZipInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; do { try { ZipEntry zip_entry = zip_in_stream.getNextEntry(); if (zip_entry == null) break; File output_file = new File(dir_output, zip_entry.getName()); FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = zip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } } while (true); try { zip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: protected void zipDirectory(File dir, File zipfile) throws IOException, IllegalArgumentException { if (!dir.isDirectory()) throw new IllegalArgumentException("Compress: not a directory: " + dir); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytes_read; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); } out.close(); }
11
Code Sample 1: static void createCompleteXML(File file) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(errorFile); fos = new FileOutputStream(file); byte[] data = new byte[Integer.parseInt(BlueXStatics.prop.getProperty("allocationUnit"))]; int offset; while ((offset = fis.read(data)) != -1) fos.write(data, 0, offset); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } FileWriter fw = null; try { fw = new FileWriter(file, true); fw.append("</detail>"); fw.append("\n</exception>"); fw.append("\n</log>"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); } catch (Exception e) { } } } Code Sample 2: private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
00
Code Sample 1: private static boolean initLOG4JProperties(String homeDir) { String Log4jURL = homeDir + LOG4J_URL; try { URL log4jurl = getURL(Log4jURL); InputStream inStreamLog4j = log4jurl.openStream(); Properties propertiesLog4j = new Properties(); try { propertiesLog4j.load(inStreamLog4j); PropertyConfigurator.configure(propertiesLog4j); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { logger.info("Failed to initialize LOG4J with properties file."); return false; } return true; } Code Sample 2: private void getRdfResponse(StringBuilder sb, String url) { try { String inputLine = null; BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while ((inputLine = reader.readLine()) != null) { sb.append(inputLine); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }