List of usage examples for java.io BufferedReader BufferedReader
public BufferedReader(Reader in)
From source file:org.kuali.student.git.importer.ApplyManualBranchCleanup.java
/** * @param args/*from w ww.jav a 2 s.c o m*/ */ public static void main(String[] args) { if (args.length < 4 || args.length > 7) { usage(); } File inputFile = new File(args[0]); if (!inputFile.exists()) usage(); boolean bare = false; if (args[2].trim().equals("1")) { bare = true; } String remoteName = args[3].trim(); String refPrefix = Constants.R_HEADS; if (args.length == 5) refPrefix = args[4].trim(); String userName = null; String password = null; if (args.length == 6) userName = args[5].trim(); if (args.length == 7) password = args[6].trim(); try { Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[1]).getAbsoluteFile(), false, bare); Git git = new Git(repo); RevWalk rw = new RevWalk(repo); ObjectInserter objectInserter = repo.newObjectInserter(); BufferedReader fileReader = new BufferedReader(new FileReader(inputFile)); String line = fileReader.readLine(); int lineNumber = 1; BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate(); List<RefSpec> branchesToDelete = new ArrayList<>(); while (line != null) { if (line.startsWith("#") || line.length() == 0) { // skip over comments and blank lines line = fileReader.readLine(); lineNumber++; continue; } String parts[] = line.trim().split(":"); String branchName = parts[0]; Ref branchRef = repo.getRef(refPrefix + "/" + branchName); if (branchRef == null) { log.warn("line: {}, No branch matching {} exists, skipping.", lineNumber, branchName); line = fileReader.readLine(); lineNumber++; continue; } String tagName = null; if (parts.length > 1) tagName = parts[1]; if (tagName != null) { if (tagName.equals("keep")) { log.info("keeping existing branch for {}", branchName); line = fileReader.readLine(); lineNumber++; continue; } if (tagName.equals("tag")) { /* * Shortcut to say make the tag start with the same name as the branch. */ tagName = branchName; } // create a tag RevCommit commit = rw.parseCommit(branchRef.getObjectId()); ObjectId tag = GitRefUtils.insertTag(tagName, commit, objectInserter); batch.addCommand(new ReceiveCommand(null, tag, Constants.R_TAGS + tagName, Type.CREATE)); log.info("converting branch {} into a tag {}", branchName, tagName); } if (remoteName.equals("local")) { batch.addCommand( new ReceiveCommand(branchRef.getObjectId(), null, branchRef.getName(), Type.DELETE)); } else { // if the branch is remote then remember its name so we can batch delete after we have the full list. branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + branchName)); } line = fileReader.readLine(); lineNumber++; } fileReader.close(); // run the batch update batch.execute(rw, new TextProgressMonitor()); if (!remoteName.equals("local")) { // push the tag to the remote right now log.info("pushing tags to {}", remoteName); PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags() .setProgressMonitor(new TextProgressMonitor()); if (userName != null) pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password)); Iterable<PushResult> results = pushCommand.call(); for (PushResult pushResult : results) { if (!pushResult.equals(Result.NEW)) { log.warn("failed to push tag " + pushResult.getMessages()); } } // delete the branches from the remote log.info("pushing branch deletes to remote: {}", remoteName); results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete) .setProgressMonitor(new TextProgressMonitor()).call(); } objectInserter.release(); rw.release(); } catch (Exception e) { log.error("unexpected Exception ", e); } }
From source file:com.l2jfree.security.Base64.java
public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter String to encode: "); System.out.println(Base64.encodeBytes(bf.readLine().getBytes())); }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.FormFileUploaderClientApplication.java
/** * Run the program./*from www . ja v a2s. com*/ * * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value. */ public static void main(String[] args) { // takes file path from first program's argument if (args.length < 1) { logger.error("****** Path to input file must be first argument to program! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } String filePath = args[0]; File uploadFile = new File(filePath); if (!uploadFile.exists()) { logger.error("****** File does not exist at expected locations! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } if (args.length > 1) { serverUrl = args[1]; } logger.info("File to upload: " + filePath); CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverUrl); FileBody bin = new FileBody(uploadFile); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, bin).build(); httppost.setEntity(reqEntity); logger.info("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { logger.info("HTTP Response Status Line: " + response.getStatusLine()); // Expecting a 200 Status Code if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String reason = response.getStatusLine().getReasonPhrase(); logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode() + "] -- Reason (if available): " + reason); } else { HttpEntity resEntity = response.getEntity(); InputStream is = resEntity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String output; StringBuilder sb = new StringBuilder("Response data received:"); while ((output = in.readLine()) != null) { sb.append(System.getProperty("line.separator")); sb.append(output); } logger.info(sb.toString()); in.close(); EntityUtils.consume(resEntity); } } finally { response.close(); } } catch (Exception e) { logger.error("Caught exception: " + e.getMessage(), e); } finally { try { httpclient.close(); } catch (IOException e) { logger.warn("Exception closing HTTP client: " + e.getMessage(), e); } logger.info("DONE"); } }
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * /*from ww w .j a va 2s . c om*/ * @param args * @throws Exception */ public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); System.out.println("Certificate is not yet trusted."); // e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.npower.dm.util.ConvertMailProfile.java
/** * @param args//from w w w .j av a 2s.co m */ public static void main(String[] args) throws Exception { File outputFile = new File("c:/temp/mail.xml"); FileWriter writer = new FileWriter(outputFile); File csvFile = new File("c:/temp/mail.csv"); BufferedReader reader = new BufferedReader(new FileReader(csvFile)); String line = reader.readLine(); while (line != null) { line = reader.readLine(); if (StringUtils.isEmpty(line)) { continue; } String[] cols = StringUtils.split(line, ','); Map<String, String> values = new HashMap<String, String>(); values.put("name", cols[0]); values.put("smtp.host", cols[1]); values.put("pop.host", cols[2]); writeXML(writer, values); } writer.close(); reader.close(); }
From source file:LamportBasicVersion.java
public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException { totalMessageCount = 0;/*from w w w . j ava 2s. com*/ //For parsing the file and storing the information String line; String configurationFile = "configuration.txt"; int lineCountInFile = 0; myProcessId = Integer.parseInt(args[0]); FileReader fileReader = new FileReader(configurationFile); BufferedReader bufferedReader = new BufferedReader(fileReader); while ((line = bufferedReader.readLine()) != null) { if ((!(line.startsWith("#"))) && (!(line.isEmpty()))) { lineCountInFile = lineCountInFile + 1; String[] splitLine = line.split(" "); switch (lineCountInFile) { case 1: numberOfProcesses = Integer.parseInt(splitLine[0]); interRequestDelay = Integer.parseInt(splitLine[1]); csExecutionTime = Integer.parseInt(splitLine[2]); maxNumberOfRequest = Integer.parseInt(splitLine[3]); machineNames = new String[Integer.parseInt(splitLine[0])]; portNumbers = new int[Integer.parseInt(splitLine[0])]; break; default: machineNames[lineCountInFile - 2] = splitLine[1]; portNumbers[lineCountInFile - 2] = Integer.parseInt(splitLine[2]); break; } } } conditionArray = new int[numberOfProcesses]; finishFlagArray = new int[numberOfProcesses]; //Initializing vector class VectorClass.initialize(numberOfProcesses); //Fill the arrays with zero false value for (int o = 0; o < numberOfProcesses; o++) { conditionArray[o] = 0; finishFlagArray[o] = 0; } // Write output to file filename = filename + Integer.toString(myProcessId) + ".out"; file = new File(filename); file.createNewFile(); writer = new FileWriter(file); // Write clocks to file filenameClock = filenameClock + Integer.toString(myProcessId) + ".out"; fileClock = new File(filenameClock); fileClock.createNewFile(); //writerClock = new FileWriter(fileClock); fw = new FileWriter(fileClock); bw = new BufferedWriter(fw); // // Expo mean insert csExecutionExpoDelay = new ExponentialDistribution(csExecutionTime); interRequestExpoDelay = new ExponentialDistribution(interRequestDelay); // System.out.println("********************************************************"); System.out.println("My process id : " + myProcessId); System.out.println("Number of processes : " + numberOfProcesses); System.out.println("Inter-request delay : " + interRequestDelay); System.out.println("Critical section execution time : " + csExecutionTime); System.out.println("Maximum number of request : " + maxNumberOfRequest); System.out.println( "My process name : " + machineNames[myProcessId] + " My port number : " + portNumbers[myProcessId]); for (int i = 0; i < numberOfProcesses; i++) { System.out.println("Process name : " + machineNames[i] + " Port number : " + portNumbers[i]); } System.out.println("********************************************************"); //For hosting server localhost SctpServerChannel sctpServerChannel = SctpServerChannel.open(); InetSocketAddress serverAddr = new InetSocketAddress(portNumbers[myProcessId]); sctpServerChannel.bind(serverAddr); System.out.println("********************************************************"); System.out.println("Local server hosted"); System.out.println("********************************************************"); //For creating neighbor SCTP channels Thread.sleep(30000); socketAddress = new SocketAddress[numberOfProcesses]; sctpChannel = new SctpChannel[numberOfProcesses]; System.out.println("********************************************************"); System.out.println("Neighbor channels created"); System.out.println("********************************************************"); //Thread spanned for generating critical section request new Thread(new LamportBasicVersion()).start(); //while loop to receive all the requests and other messages while (true) { try (SctpChannel sctpChannelFromClient = sctpServerChannel.accept()) { mutex.acquire(); byteBufferFromNeighbor.clear(); String receiveMessage; MessageInfo messageInfoFromNeighbor = sctpChannelFromClient.receive(byteBufferFromNeighbor, null, null); //System.out.println("Raw Message : " + messageInfoFromNeighbor); receiveMessage = byteToString(byteBufferFromNeighbor, messageInfoFromNeighbor); //write to file start writer.write("Received Message : " + receiveMessage); writer.write("\n"); writer.flush(); //write to file end System.out.println("Received Message : " + receiveMessage); if (receiveMessage.contains("Request")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // int requestMade = Integer.parseInt(parseMessage[3] + parseMessage[1]); queue.add(requestMade); //Send reply messages to that process for entering CS lamportClock++; //vector clock construction int[] vector = VectorClass.increment(myProcessId); String vectorClockConstruction = ""; for (int g = 0; g < vector.length; g++) { if (g == 0) { vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]); } else { vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]); } } // for (int k = 0; k < numberOfProcesses; k++) { if (k == Integer.parseInt(parseMessage[1])) { try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[k].connect(socketAddress[k]); String sendMessage = "Reply from Process-" + myProcessId + "-" + Integer.toString(requestMade) + "-" + lamportClock + "-" + vectorClockConstruction; System.out.println("Message sent is : " + sendMessage); //write to file start writer.write("Message sent is : " + sendMessage); writer.write("\n"); writer.flush(); //write to file end MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[k].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[k].close(); } catch (IOException ex) { Logger.getLogger(LamportBasicVersion.class.getName()).log(Level.SEVERE, null, ex); } } } } else if (receiveMessage.contains("Reply")) { conditionArray[myProcessId] = 1; String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // conditionArray[Integer.parseInt(parseMessage[1])] = 1; int count = 0; for (int v = 0; v < numberOfProcesses; v++) { if (conditionArray[v] == 1) { count = count + 1; } } if (count == numberOfProcesses) { L1ConditionFlag = 1; System.out.println("Inside L1"); blockingQueue.put("L1"); //Clearing condition array after receiving all REPLY for (int z = 0; z < numberOfProcesses; z++) { conditionArray[z] = 0; } if (L2ConditionFlag == 0 && outstandingRequest == 1) { Integer[] queueArray = new Integer[queue.size()]; queue.toArray(queueArray); Arrays.sort(queueArray); if (queueArray[0] == currentRequestBeingServed) { System.out.println("Inside L2"); L2ConditionFlag = 1; blockingQueue.put("L2"); } } } } else if (receiveMessage.contains("Release")) { int present = 0; int delete = 0; String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // if (queue.size() != 0) { Integer[] queueArray = new Integer[queue.size()]; queue.toArray(queueArray); Arrays.sort(queueArray); for (int a = 0; a < queueArray.length; a++) { if (queueArray[a] == Integer.parseInt(parseMessage[2])) { present = 1; delete = a; } } if (present == 1) { for (int s = 0; s <= delete; s++) { queue.remove(); } } } if (L2ConditionFlag == 0 && outstandingRequest == 1) { if (queue.size() != 0) { Integer[] queueArray1 = new Integer[queue.size()]; queue.toArray(queueArray1); Arrays.sort(queueArray1); if (currentRequestBeingServed == queueArray1[0]) { L2ConditionFlag = 1; System.out.println("Inside L2"); blockingQueue.put("L2"); } } } } else if (receiveMessage.contains("Finish")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // finishFlagArray[Integer.parseInt(parseMessage[1])] = 1; int count = 0; for (int v = 0; v < numberOfProcesses; v++) { if (finishFlagArray[v] == 1) { count = count + 1; } } if (count == numberOfProcesses) { break; } } //logic for other messages //Print the queue to check System.out.println("********************************************************"); for (Object item : queue) { System.out.print(item); System.out.print("\t"); } System.out.println("********************************************************"); } mutex.release(); } }
From source file:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java
/** * Run the program./*from ww w . java2s. c o m*/ * * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value. */ public static void main(String[] args) { // takes file path from first program's argument if (args.length < 1) { logger.error("****** Path to input file must be first argument to program! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } String filePath = args[0]; File uploadFile = new File(filePath); if (!uploadFile.exists()) { logger.error("****** File does not exist at expected locations! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } if (args.length > 1) { serverUrl = args[1]; } logger.info("File to upload: " + filePath); CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverUrl + "false"); FileBody bin = new FileBody(uploadFile); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart(FITS_FORM_FIELD_DATAFILE, bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); logger.info("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { logger.info("HTTP Response Status Line: " + response.getStatusLine()); // Expecting a 200 Status Code if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String reason = response.getStatusLine().getReasonPhrase(); logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode() + "] -- Reason (if available): " + reason); } else { HttpEntity resEntity = response.getEntity(); InputStream is = resEntity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String output; StringBuilder sb = new StringBuilder(); while ((output = in.readLine()) != null) { sb.append(output); sb.append(System.getProperty("line.separator")); } logger.info(sb.toString()); in.close(); EntityUtils.consume(resEntity); } } finally { response.close(); } } catch (Exception e) { logger.error("Caught exception: " + e.getMessage(), e); } finally { try { httpclient.close(); } catch (IOException e) { logger.warn("Exception closing HTTP client: " + e.getMessage(), e); } logger.info("DONE"); } }
From source file:niclients.main.regni.java
public static void main(String[] args) throws UnsupportedEncodingException { HttpClient client = new DefaultHttpClient(); if (commandparser(args)) { if (createpub()) { try { HttpResponse response = client.execute(post); int resp_code = response.getStatusLine().getStatusCode(); System.err.println("RESP_CODE: " + Integer.toString(resp_code)); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); }//from w ww . ja va 2 s . c om } catch (IOException e) { e.printStackTrace(); } } else { System.err.println("Publish creation failed!"); } } else { System.err.println("Command line parsing failed!"); } }
From source file:RoucairolCarvahloBasicVersion.java
public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException { //For parsing the file and storing the information String line;//from ww w. ja v a 2 s.c om String configurationFile = "configuration.txt"; int lineCountInFile = 0; myProcessId = Integer.parseInt(args[0]); FileReader fileReader = new FileReader(configurationFile); BufferedReader bufferedReader = new BufferedReader(fileReader); while ((line = bufferedReader.readLine()) != null) { if ((!(line.startsWith("#"))) && (!(line.isEmpty()))) { lineCountInFile = lineCountInFile + 1; String[] splitLine = line.split(" "); switch (lineCountInFile) { case 1: numberOfProcesses = Integer.parseInt(splitLine[0]); interRequestDelay = Integer.parseInt(splitLine[1]); csExecutionTime = Integer.parseInt(splitLine[2]); maxNumberOfRequest = Integer.parseInt(splitLine[3]); machineNames = new String[Integer.parseInt(splitLine[0])]; portNumbers = new int[Integer.parseInt(splitLine[0])]; break; default: machineNames[lineCountInFile - 2] = splitLine[1]; portNumbers[lineCountInFile - 2] = Integer.parseInt(splitLine[2]); break; } } } //Initializing finish array finishFlagArray = new int[numberOfProcesses]; //Initializing vector class VectorClass.initialize(numberOfProcesses); //Fill the arrays with zero false value for (int o = 0; o < numberOfProcesses; o++) { finishFlagArray[o] = 0; } //Initializing key array and inserting values keyArray = new int[numberOfProcesses]; for (int q = 0; q < numberOfProcesses; q++) { if (q >= myProcessId) { keyArray[q] = 1; } } filename = filename + Integer.toString(myProcessId) + ".out"; file = new File(filename); file.createNewFile(); writer = new FileWriter(file); // Write clocks to file filenameClock = filenameClock + Integer.toString(myProcessId) + ".out"; fileClock = new File(filenameClock); fileClock.createNewFile(); //writerClock = new FileWriter(fileClock); fw = new FileWriter(fileClock); bw = new BufferedWriter(fw); // // Expo mean insert csExecutionExpoDelay = new ExponentialDistribution(csExecutionTime); interRequestExpoDelay = new ExponentialDistribution(interRequestDelay); // System.out.println("********************************************************"); System.out.println("My process id : " + myProcessId); System.out.println("Number of processes : " + numberOfProcesses); System.out.println("Inter-request delay : " + interRequestDelay); System.out.println("Critical section execution time : " + csExecutionTime); System.out.println("Maximum number of request : " + maxNumberOfRequest); System.out.println( "My process name : " + machineNames[myProcessId] + " My port number : " + portNumbers[myProcessId]); for (int i = 0; i < numberOfProcesses; i++) { System.out.println("Process name : " + machineNames[i] + " Port number : " + portNumbers[i]); } System.out.println("********************************************************"); for (int q = 0; q < numberOfProcesses; q++) { System.out.println("KeyArray" + q + " - " + keyArray[q]); } System.out.println("********************************************************"); //For hosting server localhost SctpServerChannel sctpServerChannel = SctpServerChannel.open(); InetSocketAddress serverAddr = new InetSocketAddress(portNumbers[myProcessId]); sctpServerChannel.bind(serverAddr); System.out.println("********************************************************"); System.out.println("Local server hosted"); System.out.println("********************************************************"); //For creating neighbor SCTP channels Thread.sleep(30000); socketAddress = new SocketAddress[numberOfProcesses]; sctpChannel = new SctpChannel[numberOfProcesses]; System.out.println("********************************************************"); System.out.println("Neighbor channels created"); System.out.println("********************************************************"); //Thread spanned for generating critical section request new Thread(new RoucairolCarvahloBasicVersion()).start(); while (true) { try (SctpChannel sctpChannelFromClient = sctpServerChannel.accept()) { mutex.acquire(); byteBufferFromNeighbor.clear(); String receiveMessage; MessageInfo messageInfoFromNeighbor = sctpChannelFromClient.receive(byteBufferFromNeighbor, null, null); //System.out.println("Raw Message : " + messageInfoFromNeighbor); receiveMessage = byteToString(byteBufferFromNeighbor, messageInfoFromNeighbor); System.out.println("Received Message : " + receiveMessage); if (receiveMessage.contains("Request")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // int requestMade = Integer.parseInt(parseMessage[3] + parseMessage[1]); if (outstandingRequest == 1) { if (requestMade < currentRequestBeingServed) { lamportClock++; //Newly inserted for vector timesatmp int[] vector = VectorClass.increment(myProcessId); String vectorClockConstruction = ""; for (int g = 0; g < vector.length; g++) { if (g == 0) { vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]); } else { vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]); } } // keyArray[Integer.parseInt(parseMessage[1])] = 0; try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[Integer.parseInt(parseMessage[1])] .connect(socketAddress[Integer.parseInt(parseMessage[1])]); String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-" + lamportClock + "-" + vectorClockConstruction; System.out.println("Message sent is : " + sendMessage); MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[Integer.parseInt(parseMessage[1])].close(); } catch (IOException ex) { Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE, null, ex); } //Include block for reverse request lamportClock++; //Newly inserted for vector timesatmp int[] vector1 = VectorClass.increment(myProcessId); String vectorClockConstruction1 = ""; for (int g = 0; g < vector1.length; g++) { if (g == 0) { vectorClockConstruction1 = vectorClockConstruction1 + Integer.toString(vector1[g]); } else { vectorClockConstruction1 = vectorClockConstruction1 + "," + Integer.toString(vector1[g]); } } // try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[Integer.parseInt(parseMessage[1])] .connect(socketAddress[Integer.parseInt(parseMessage[1])]); String sendMessage = "ReverseSend from Process-" + myProcessId + "-" + currentRequestBeingServed + "-" + lamportClock + "-" + vectorClockConstruction1; System.out.println("Message sent is : " + sendMessage); MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[Integer.parseInt(parseMessage[1])].close(); } catch (IOException ex) { Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE, null, ex); } } else if (requestMade == currentRequestBeingServed) { if (Integer.parseInt(parseMessage[1]) < myProcessId) { lamportClock++; //Newly inserted for vector timesatmp int[] vector = VectorClass.increment(myProcessId); String vectorClockConstruction = ""; for (int g = 0; g < vector.length; g++) { if (g == 0) { vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]); } else { vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]); } } // keyArray[Integer.parseInt(parseMessage[1])] = 0; try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[Integer.parseInt(parseMessage[1])] .connect(socketAddress[Integer.parseInt(parseMessage[1])]); String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-" + lamportClock + "-" + vectorClockConstruction; System.out.println("Message sent is : " + sendMessage); MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[Integer.parseInt(parseMessage[1])].close(); } catch (IOException ex) { Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()) .log(Level.SEVERE, null, ex); } //Include block for reverse request lamportClock++; //Newly inserted for vector timesatmp int[] vector1 = VectorClass.increment(myProcessId); String vectorClockConstruction1 = ""; for (int g = 0; g < vector1.length; g++) { if (g == 0) { vectorClockConstruction1 = vectorClockConstruction1 + Integer.toString(vector1[g]); } else { vectorClockConstruction1 = vectorClockConstruction1 + "," + Integer.toString(vector1[g]); } } // try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[Integer.parseInt(parseMessage[1])] .connect(socketAddress[Integer.parseInt(parseMessage[1])]); String sendMessage = "ReverseSend from Process-" + myProcessId + "-" + currentRequestBeingServed + "-" + lamportClock + "-" + vectorClockConstruction1; System.out.println("Message sent is : " + sendMessage); MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[Integer.parseInt(parseMessage[1])].close(); } catch (IOException ex) { Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()) .log(Level.SEVERE, null, ex); } } else if (myProcessId < Integer.parseInt(parseMessage[1])) { queue.add(requestMade); } } else if (requestMade > currentRequestBeingServed) { queue.add(requestMade); } } else if (outstandingRequest == 0) { lamportClock++; //Newly inserted for vector timesatmp int[] vector = VectorClass.increment(myProcessId); String vectorClockConstruction = ""; for (int g = 0; g < vector.length; g++) { if (g == 0) { vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]); } else { vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]); } } // keyArray[Integer.parseInt(parseMessage[1])] = 0; try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[Integer.parseInt(parseMessage[1])] .connect(socketAddress[Integer.parseInt(parseMessage[1])]); String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-" + lamportClock + "-" + vectorClockConstruction; System.out.println("Message sent is : " + sendMessage); MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[Integer.parseInt(parseMessage[1])].close(); } catch (IOException ex) { Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE, null, ex); } } } else if (receiveMessage.contains("Key")) { //receive check condition execute critical section block String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // keyArray[Integer.parseInt(parseMessage[1])] = 1; int countOnes = 0; for (int y = 0; y < numberOfProcesses; y++) { if (keyArray[y] == 1) { countOnes = countOnes + 1; } } if (countOnes == numberOfProcesses) { outstandingRequest = 0; currentRequestBeingServed = 0; enterCriticalSectionExecution(); timestamp2 = new Timestamp(System.currentTimeMillis()); csExit(); } } else if (receiveMessage.contains("ReverseSend")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // int requestMade = Integer.parseInt(parseMessage[2]); if (outstandingRequest == 1) { if (requestMade < currentRequestBeingServed) { lamportClock++; //Newly inserted for vector timesatmp int[] vector = VectorClass.increment(myProcessId); String vectorClockConstruction = ""; for (int g = 0; g < vector.length; g++) { if (g == 0) { vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]); } else { vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]); } } // keyArray[Integer.parseInt(parseMessage[1])] = 0; try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[Integer.parseInt(parseMessage[1])] .connect(socketAddress[Integer.parseInt(parseMessage[1])]); String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-" + lamportClock + "-" + vectorClockConstruction; System.out.println("Message sent is : " + sendMessage); MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[Integer.parseInt(parseMessage[1])].close(); } catch (IOException ex) { Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE, null, ex); } //Include block for reverse request lamportClock++; //Newly inserted for vector timesatmp int[] vector1 = VectorClass.increment(myProcessId); String vectorClockConstruction1 = ""; for (int g = 0; g < vector1.length; g++) { if (g == 0) { vectorClockConstruction1 = vectorClockConstruction1 + Integer.toString(vector1[g]); } else { vectorClockConstruction1 = vectorClockConstruction1 + "," + Integer.toString(vector1[g]); } } // try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[Integer.parseInt(parseMessage[1])] .connect(socketAddress[Integer.parseInt(parseMessage[1])]); String sendMessage = "ReverseSend from Process-" + myProcessId + "-" + currentRequestBeingServed + "-" + lamportClock + "-" + vectorClockConstruction1; System.out.println("Message sent is : " + sendMessage); MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[Integer.parseInt(parseMessage[1])].close(); } catch (IOException ex) { Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE, null, ex); } } else if (requestMade == currentRequestBeingServed) { if (Integer.parseInt(parseMessage[1]) < myProcessId) { lamportClock++; //Newly inserted for vector timesatmp int[] vector = VectorClass.increment(myProcessId); String vectorClockConstruction = ""; for (int g = 0; g < vector.length; g++) { if (g == 0) { vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]); } else { vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]); } } // keyArray[Integer.parseInt(parseMessage[1])] = 0; try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[Integer.parseInt(parseMessage[1])] .connect(socketAddress[Integer.parseInt(parseMessage[1])]); String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-" + lamportClock + "-" + vectorClockConstruction; System.out.println("Message sent is : " + sendMessage); MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[Integer.parseInt(parseMessage[1])].close(); } catch (IOException ex) { Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()) .log(Level.SEVERE, null, ex); } //Include block for reverse request lamportClock++; //Newly inserted for vector timesatmp int[] vector1 = VectorClass.increment(myProcessId); String vectorClockConstruction1 = ""; for (int g = 0; g < vector1.length; g++) { if (g == 0) { vectorClockConstruction1 = vectorClockConstruction1 + Integer.toString(vector1[g]); } else { vectorClockConstruction1 = vectorClockConstruction1 + "," + Integer.toString(vector1[g]); } } // try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[Integer.parseInt(parseMessage[1])] .connect(socketAddress[Integer.parseInt(parseMessage[1])]); String sendMessage = "ReverseSend from Process-" + myProcessId + "-" + currentRequestBeingServed + "-" + lamportClock + "-" + vectorClockConstruction1; System.out.println("Message sent is : " + sendMessage); MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[Integer.parseInt(parseMessage[1])].close(); } catch (IOException ex) { Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()) .log(Level.SEVERE, null, ex); } } else if (myProcessId < Integer.parseInt(parseMessage[1])) { queue.add(requestMade); } } else if (requestMade > currentRequestBeingServed) { queue.add(requestMade); } } else if (outstandingRequest == 0) { lamportClock++; //Newly inserted for vector timesatmp int[] vector = VectorClass.increment(myProcessId); String vectorClockConstruction = ""; for (int g = 0; g < vector.length; g++) { if (g == 0) { vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]); } else { vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]); } } // keyArray[Integer.parseInt(parseMessage[1])] = 0; try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[Integer.parseInt(parseMessage[1])] .connect(socketAddress[Integer.parseInt(parseMessage[1])]); String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-" + lamportClock + "-" + vectorClockConstruction; System.out.println("Message sent is : " + sendMessage); MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[Integer.parseInt(parseMessage[1])].close(); } catch (IOException ex) { Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE, null, ex); } } } else if (receiveMessage.contains("Finish")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // finishFlagArray[Integer.parseInt(parseMessage[1])] = 1; int count = 0; for (int v = 0; v < numberOfProcesses; v++) { if (finishFlagArray[v] == 1) { count = count + 1; } } if (count == numberOfProcesses) { break; } } } mutex.release(); } }
From source file:FileCompressor.java
public static void main(String[] args) throws IOException { String file = "D:\\XJad.rar.txt"; BufferedReader reader = new BufferedReader(new FileReader(file)); BufferedWriter writer = new BufferedWriter(new FileWriter(file + "_out.txt")); StringBuilder content = new StringBuilder(); String tmp;/*from w ww . j av a2 s.com*/ while ((tmp = reader.readLine()) != null) { content.append(tmp); content.append(System.getProperty("line.separator")); } FileCompressor f = new FileCompressor(); writer.write(f.compress(content.toString())); writer.close(); reader.close(); reader = new BufferedReader(new FileReader(file + "_out.txt")); StringBuilder content2 = new StringBuilder(); while ((tmp = reader.readLine()) != null) { content2.append(tmp); content2.append(System.getProperty("line.separator")); } String decompressed = f.decompress(content2.toString()); String c = content.toString(); System.out.println(decompressed.equals(c)); }