#java.io.IOException
Explore tagged Tumblr posts
Text
I was trying to do some Index writing speed improvement and thought of creating a asynchronous Lucene index writer. This writer provides a addDocument() method which can be called asynchronously by multiple threads. Here are the few scenario where you can utilize this implementation - Reading the data is slower then writing to the index. (Typical scenario where you read over network, or from database.) - Reading can be divided in multiple logical parts which can be processed in separate threads. - You are looking for asynchronous behavior to decouple reading and writing processes. This implementation is a wrapper which utilizes core methods of IndexWriter class, and does not do any change to it except making it asynchronous. It utilizes Java's java.util.concurrent.BlockingQueue for storing the documents. It can be supplied with any implementation of this class using its constructor. Below is the Java source of this implementation class This class provides multiple constructors to have better control. Few terms which are used here are as follows Sleep Milliseconds On Empty: This is the sleep duration when writer finds nothing in queue and wants to wait for some data to come in queue. () Queue Size: This is the size of the queue which can be configured as a constructor parameter input. AsynchronousIndexWriter.java package swiki.lucene.asynchronous; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; /** * @author swiki swiki * */ public class AsynchronousIndexWriter implements Runnable /* * A blocking queue of document to facilitate asynchronous writing. */ private BlockingQueue documents; /* * Instance of core index writer which does the actual writing task. */ private IndexWriter writer; /* * Thread which makes writing asynchronous */ private Thread writerThread; /* * We need to set this to false if the document addition is completed. This * will not immediately stop the writing as there could be some documents in * the queue. It completes once all documents are written and the queue is * empty. */ private boolean keepRunning = true; /* * This flag is set to false once writer is done with the queue data * writing. */ private boolean isRunning = true; /* * Duration in miliseconds for which the writer should sleep when it finds * the queue empty and job is still not completed */ private long sleepMilisecondOnEmpty = 100; /** * This method should be used to add documents to index queue. If the queue * is full it will wait for the queue to be available. * * @param doc * @throws InterruptedException */ public void addDocument(Document doc) throws InterruptedException documents.put(doc); public void startWriting() writerThread = new Thread(this, "AsynchronousIndexWriter"); writerThread.start(); /** * Constructor with indexwriter as input. It Uses ArrayBlockingQueue with * size 100 and sleepMilisecondOnEmpty is 100ms * * @param w */ public AsynchronousIndexWriter(IndexWriter w) this(w, 100, 100); /** * Constructor with indexwriter and queue size as input. It Uses * ArrayBlockingQueue with size queueSize and sleepMilisecondOnEmpty is * 100ms * * @param w * @param queueSize */ public AsynchronousIndexWriter(IndexWriter w, int queueSize) this(w, queueSize, 100); /** * Constructor with indexwriter, queueSize as input. It Uses * ArrayBlockingQueue with size queueSize * * @param w * @param queueSize * @param sleepMilisecondOnEmpty */ public AsynchronousIndexWriter(IndexWriter w, int queueSize, long sleepMilisecondOnEmpty) this(w, new ArrayBlockingQueue(queueSize), sleepMilisecondOnEmpty); /** * A implementation of BlockingQueue can be used * * @param w * @param queueSize * @param sleepMilisecondOnEmpty */ public AsynchronousIndexWriter(IndexWriter w, BlockingQueue queue,
long sleepMilisecondOnEmpty) writer = w; documents = queue; this.sleepMilisecondOnEmpty = sleepMilisecondOnEmpty; startWriting(); /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ public void run() while (keepRunning /** * Stop the thread gracefully, wait until its done writing. */ private void stopWriting() this.keepRunning = false; try while (isRunning) //using the same sleep duration as writer uses Thread.sleep(sleepMilisecondOnEmpty); catch (InterruptedException e) e.printStackTrace(); public void optimize() throws CorruptIndexException, IOException writer.optimize(); public void close() throws CorruptIndexException, IOException stopWriting(); writer.close(); Below is a sample class which demonstrates how we can use this class. Here are few things to note, asynchronous thread is started as soon as you instantiate using new AsynchronousIndexWriter(...) TestAsyncWriter.java package swiki.lucene.asynchronous; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; /** * @author swiki swiki * */ public class TestAsyncWriter public static void main(String[] args) try Directory fsdir = FSDirectory.getDirectory("index"); IndexWriter w = new IndexWriter(fsdir, new StandardAnalyzer(), true); AsynchronousIndexWriter writer = new AsynchronousIndexWriter(w); /* * This call can be replaced by the logic of reading * data using multiple threads */ addDocumentsInMultipleThreads(writer); writer.optimize(); writer.close(); catch (Exception e) e.printStackTrace(); private static void addDocumentsInMultipleThreads( AsynchronousIndexWriter writer) throws InterruptedException //add here the code for adding document from multiple threads. Document doc = new Document(); doc.add(new Field("content","My Content", Field.Store.YES, Field.Index.UN_TOKENIZED)); writer.addDocument(new Document()); If you find this useful or have some suggestions for improvements please leave a comment and I will try to respond. Lucene parallel writer code, lucene parallel indexing, lucene fast index creation, asynchronous index creation, parallel index creation, fast index creation code, Lucene Asynchronous Index Writer, thread based index writer, multi threaded index writing lucene indexwriter, lucene indexing , lucene fast index writer, lucene fast indexing, lucene asynchronous writer, lucene building fast index, lucene parallel index, search engine lucene, indexwriter lucene, what is lucene search, implementing search lucene, lucene indexing speed, lucene indexing performance improvement.
0 notes
Text
🚀 How to Copy an Image using Java!
Here's a simple code snippet to get you started:
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException;
public class cacms { public static void main(String[] args) { String sourcePath = "C:\\Users\\Administrator\\Desktop\\cacms Institute\\LOGO.png";
String destinationPath = "C:\\Users\\Administrator\\Desktop\\cacms Institute\\LOGO COPY.png";
File sourceFile = new File(sourcePath); File destinationFile = new File(destinationPath);
try (FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destinationFile)) {
byte[] buffer = new byte[1024]; int length;
while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); }
System.out.println("File copied successfully!");
} catch (IOException e) { System.err.println("File copy failed: " + e.getMessage()); } } }
Want to learn more Java? 💻 Enroll at CACMS Institute today! Follow us for more tips and tutorials @cacms.institute
📞 Contact us at +91 8288040281 or visit the link below for further details.
0 notes
Link
0 notes
Text
HTTP PROXY JMX.newMXBeanProxy
This Java code demonstrates a simple HTTP client that sends a GET request to a specified host and port, receives the response, and performs parsing of the data.Let’s break down the code step by step:1. The code imports necessary classes for handling network connections and I/O operations: `java.io.IOException`, `java.io.InputStream`, `java.io.OutputStream`, and `java.net.Socket`.2. The `Main`…
View On WordPress
0 notes
Text
ubuntu – java.io.IOException: All directories in dfs.datanode.data.dir are invalid
1.sudo chown vaughn:hadoop -R /usr/local/hadoop_store
where hadoop is group name. use
grep vaughn /etc/group
in your terminal to see your group name.
2.clean temporary directories.
3.Format the name node.
Hope this helps.
Looks like its a permission issue, The user which is used to start datanode should have write access in the data node -data directories.
Try to execute the below command before starting datanode service.
0 notes
Text
package ti;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern;
import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document;
import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Collections2; import com.google.common.collect.Lists;
public class InstagramReplicator { public static InstagramReplicator newInstance(String instagramUser, String tumblrUser, String tagName) throws IOException { return new InstagramReplicator(instagramUser, tumblrUser, tagName); } public void doUpdate() throws IOException { System.out.println("Checking for updates: instagramUser=" + instagramUser); for(String instagramUrl : loadInstagramUrls()) { if(!currentImages.contains(instagramUrl)) { submitPostToTumblr ( loadInstagramPost(instagramUrl) ); currentImages.add(instagramUrl); if(currentImages.size() > 100) { currentImages.remove(currentImages.get(0)); } } } } private List<String> loadInstagramUrls() throws IOException { List<String> instagramUrls = findMatches ( Jsoup.connect("http://instagram.com/" + instagramUser).get().outerHtml(), "\"link\":\"(http:\\\\/\\\\/instagram\\.com\\\\/p\\\\/[^\\\\]*\\\\/)\"", true ); Collections.reverse(instagramUrls); //System.out.println(instagramUser + " - " + instagramUrls); return instagramUrls; } private Post loadInstagramPost(String postUrl) throws IOException { System.out.println("Loading post: postUrl=" + postUrl); String docText = Jsoup.connect(postUrl).get().outerHtml(); //System.out.println("doctext=" + docText); String caption = "<p>" + findMatch(docText, "\"caption\":\"(.*?[^\\\\])\"", false) + "</p>"; String tagRegEx = "#([A-Za-z0-9_]+)"; String userRegEx = "@([A-Za-z0-9_]+)"; List<String> tags = Lists.newArrayList(); tags.addAll(findMatches(caption, tagRegEx, false)); tags.addAll(findMatches(caption, userRegEx, false)); //caption = caption.replaceAll(tagRegEx, "<a href=\\\\\"http://www.gramfeed.com/instagram/tags#$1\\\\\">$0</a>"); caption = caption.replaceAll(userRegEx, "<a href=\\\\\"http://instagram.com/$1\\\\\">$0</a>"); if(docText.contains("\"is_video\":true")) { caption += "<p><a href=\\\"" + postUrl + "\\\">Watch Video</a></p>"; } return new Post ( postUrl, findMatch(docText, "\"display_src\":\"([^\"]*)\"", true), //imageUrl caption, Joiner.on(",").join(tags) ); } private void submitPostToTumblr(Post post) throws IOException { System.out.println("Submitting post: post=" + post); try { HttpURLConnection connection = (HttpURLConnection) new URL("http://www.tumblr.com/svc/post/update").openConnection();
connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", tumblrCookie); connection.setRequestProperty("X-tumblr-puppies", getSecureFormKey()); connection.setRequestProperty("X-tumblr-form-key","OdhVH6QQTBzl9IZZDViXwyj5vOU"); connection.setRequestProperty("Origin","http://www.tumblr.com"); connection.setRequestProperty("Accept-Encoding","gzip,deflate,sdch"); connection.setRequestProperty("Host","www.tumblr.com"); connection.setRequestProperty("Accept-Language","en-US,en;q=0.8"); connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36"); connection.setRequestProperty("Content-Type","application/json"); connection.setRequestProperty("Accept","application/json, text/javascript, */*; q=0.01"); connection.setRequestProperty("Referer","http://www.tumblr.com/new/photo"); connection.setRequestProperty("X-Requested-With","XMLHttpRequest"); connection.setRequestProperty("Connection","keep-alive"); connection.setRequestProperty("DNT","1"); connection.setUseCaches(false);
OutputStream output = connection.getOutputStream(); output.write ( ("{\"form_key\":\"OdhVH6QQTBzl9IZZDViXwyj5vOU\",\"context_id\":\"\",\"context_page\":\"dashboard\"," + "\"editor_type\":\"rich\",\"is_rich_text[one]\":\"0\",\"is_rich_text[two]\":\"1\",\"is_rich_text[three]\":\"0\"," + "\"channel_id\":\"" + tumblrUser + "\",\"post[slug]\":\"\"," + "\"post[source_url]\":\"" + post.postUrl + "\",\"post[date]\":\"\",\"post[three]\":\"" + post.postUrl + "\",\"MAX_FILE_SIZE\":\"10485760\",\"post[type]\":\"photo\"," + "\"post[two]\":\"" + post.caption + "\",\"post[tags]\":\"" + Joiner.on(",").join(userTags, post.tags, instagramUser, "instagram").replace('_', ' ') + "\",\"post[publish_on]\":\"\",\"post[state]\":\"0 3\",\"post[photoset_layout]\":\"1\",\"post[photoset_order]\":\"o1\"," + "\"images[o1]\":\"" + post.imageUrl + "\",\"photo_src[]\":\"" + post.imageUrl + "\"}").getBytes(Charset.forName("UTF-8")) ); output.close();
InputStream input = connection.getInputStream(); while(input.read() != -1) {}
System.out.println("Post submission complete, httpStatusCode=" + connection.getResponseCode());
input.close(); } catch (IOException e) { if(consecutiveTumblrErrors++ > 10) { System.err.println("FATAL: Too many consecutive tumblr failures, shutting down"); System.exit(1); } throw e; } consecutiveTumblrErrors = 0; } private String getSecureFormKey() throws IOException { Connection connection = Jsoup.connect("http://www.tumblr.com/svc/secure_form_key") .header("Cookie", tumblrCookie) .header("X-tumblr-form-key","OdhVH6QQTBzl9IZZDViXwyj5vOU") .header("Origin","http://www.tumblr.com") .header("Accept-Encoding","gzip,deflate,sdch") .header("Host","www.tumblr.com") .header("Accept-Language","en-US,en;q=0.8") .header("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36") .header("Content-Type","application/json") .header("Accept","application/json, text/javascript, */*; q=0.01") .header("Referer","http://www.tumblr.com/new/photo") .header("X-Requested-With","XMLHttpRequest") .header("Connection","keep-alive") .header("DNT","1") .header("Content-Length", "0"); connection.post(); String secureFormKey = connection.response().header("X-tumblr-secure-form-key"); System.out.println("secureFormKey=" + secureFormKey);
return secureFormKey; }
private String findMatch(String string, String regex, boolean isUrl) { List<String> matches = findMatches(string, regex, isUrl); if(matches.isEmpty()) { return ""; } return matches.get(0); } private List<String> findMatches(String string, String regex, boolean isUrl) { Matcher matcher = Pattern .compile(regex) .matcher(string);
List<String> matches = Lists.newArrayList();
while(matcher.find()) { matches.add ( matcher .group(1) .replace ( (isUrl ? "\\" : ""), "" ) ); }
return matches; } //nested classes private class Post { public Post(String postUrl, String imageUrl, String caption, String tags) { this.postUrl = postUrl; this.imageUrl = imageUrl; this.caption = caption; this.tags = tags; } @Override public String toString() { return "Post [postUrl=" + postUrl + ", imageUrl=" + imageUrl + ", caption=" + caption + ", tags=" + tags + "]"; }
private final String postUrl; private final String imageUrl; private final String caption; private final String tags; } //constructors
private InstagramReplicator(String instagramUser, String tumblrUser, String tagName) throws IOException { this.instagramUser = instagramUser; this.tumblrUser = tumblrUser; this.userTags = tagName; currentImages = loadInstagramUrls();
/* currentImages.removeAll ( Splitter .on(',') .trimResults() .omitEmptyStrings() .splitToList ( ) );*/
}
//attributes
private final String instagramUser; private final String tumblrUser; private final String userTags; private final List<String> currentImages;
//static
public static void main(String[] args) throws IOException { Executors.newScheduledThreadPool(0).scheduleWithFixedDelay ( new Runnable() { List<InstagramReplicator> replicators = Lists.newArrayList ( InstagramReplicator.newInstance("willaaaahh", "willaaaahhh", "willa holland"), InstagramReplicator.newInstance("emmaroberts", "emmaroberts9", "emma roberts"), InstagramReplicator.newInstance("tfarm7", "tfarm11", "taissa farmiga"), InstagramReplicator.newInstance("taylorswift", "taylorswift26", "taylor swift,taylorswift13"), InstagramReplicator.newInstance("yelyahwilliams", "yelyahwilliams-instagram", "hayley williams"),
InstagramReplicator.newInstance("MileyCyrus", "mileycyrus-instagram", "miley cyrus"), //InstagramReplicator.newInstance("badgalriri", "badgalriri-instagram", "rihanna"), InstagramReplicator.newInstance("beyonce", "beyonce-instagram", "beyonce knowles"), InstagramReplicator.newInstance("caradelevingne", "caradelevingne-instagram", "cara delevingne"), InstagramReplicator.newInstance("nickiminaj", "nickiminaj-instagram", "nicki minaj"), InstagramReplicator.newInstance("emmyrossum", "emmyrossum-instagram", "emmy rossum"), InstagramReplicator.newInstance("tigersjaw", "tigersjaw-instagram", "tigers jaw,brianna collins"), InstagramReplicator.newInstance("tayjardine", "tayjardine-instagram", "tay jardine,taylor jardine,we are the in crowd"), InstagramReplicator.newInstance("lordemusic", "lordemusic-instagram", "lorde") );
Iterator<InstagramReplicator> replicatorIterator = replicators.iterator();
@Override public void run() { if(!replicatorIterator.hasNext()) { replicatorIterator = replicators.iterator(); }
InstagramReplicator replicator = replicatorIterator.next();
try { replicator.doUpdate(); } catch (Throwable e) { e.printStackTrace(); } } }, 0, 5, TimeUnit.SECONDS ); } private static int consecutiveTumblrErrors = 0; private static final String tumblrCookie = ""; }
19 notes
·
View notes
Text
Guidelines for Using Exceptions in Java
Note: Whitespace has been automatically removed by this site for all the code examples.
You may want to read and adopt the guidelines that help you get the most out of Java's exception handling mechanism. You can write powerful and effective Java code by adopting most, or all, of the things recommended here.
Remember that exception handling provides a way to process synchronous errors such as divisions by zero and out-of-range array indexes. It's not meant for handling asynchronous events such as disk I/O completions and mouse clicks and keystrokes.
When to use Exceptions You may be wondering as to how you actually decide to create and throw an exception. As a rule of thumb, create exception classes for all common exceptions that are likely to occur in multiple classes of an application. In order to deal with simple errors that are likely to occur only in individual methods, try not to create an exception class. You can use an if statement in most cases to trap these types of errors.
Here's a simple example that shows when not to use a try-catch block in your code. The code throws an error when there's an exception of the type NullPointerException.
try {
System.out.println(refvar.toString()};
}
catch (NullPointerException e) {
System.out.println("refVar is null!");
This is pure overkill. You can instead use the much simpler if statement to handle these types of simple errors.
if (refVar!=null)
System.out.println(refVar.toString()};
else
System.out.println("refVar is null");
If your code can perform a simple logic test, as shown here, to handle an error, do so, rather than using an exception object to handle the error.
When you neither catch nor throw exceptions When you call any method that throws a checked exception, you must either throw the exception or catch it. If you decide that you can't handle the exception in the method where it occurs, write a throw statement to send the exception up to the calling method, which must then either handle it with an exception handler, or throw it up to its calling method.
The following set of examples show how you must either catch or throw a checked exception, in order to avoid compiler errors.
The first example shows code that throws an IOException. The statement in the method getFileLength may throw an IO exception when it calls the constructor of the RandomAccessFile class. In addition, the statement that calls the length method of the RandomAccessFile object may also throw an IOException. You thus specify the throws clause in the declaration for the getFileLength method to trap IOException.
public static long getFileLength() throws IOException
{
RandomAccessFile in = new RandomAccessFile("mytext.dat", "r");
long length = in.length();
return length;
}
Our next example shows code for a method that calls the getFileLength method. Since we already know that the getFileLength method call throws an IOException error, our new method must either handle the IO Exception or throw it. Our example here shows how to handle the IOException by catching it with a try statement:
public static int getRecordCount()
{
try
{
long length = getFileLength(); // this may throw an IOException
int recordCount = (int) (length / /RECORD_SIZE);
return recordCount;
}
catch (IOException e) // this will catch the IOException
{
System.out.println("IO Exception!");
return 0;
}
}
The third example shows how a method can call the getFileLength method without catching IOException. Instead, it throws the exception.
public static int getRecordCount() throws IOException
{
long length = getFileLength(); //this may throw an IOException
int recordCount = (int) (length / RECORD_SIZE);
return recordCount;
}
The getRecordCount method here includes a throw clause, which ensures that any IOException is thrown up to the calling method.
Our fourth example shows what happens when you don't catch an exception or throw it.
public static int getRecordCount()
{
long length = getFileLength(); //this may throw an IOException
int recordCount = (int) (length / RECORD_SIZE);
return recordCount;
}
Since your code fails to catch or throw a checked exception, you'll receive a compile error:
MyExceptionTest.java.26: unreported exception java.io.IOException;
must be caught or declared to be thrown
The following is a quick summary of best practices and guidelines that enable you to take advantage of Java's exception handling mechanism, without succumbing to common missteps in the use of exceptions.
Begin Early It is a good idea to incorporate exception handling into your applications from the get go, before you even start programming. That is, you must do this at the design stage, as it gets much harder to do it after implementing your applications.
Don't Ever Ignore an Exception Regardless of whether you're dealing with a checked or an unchecked exception, don't ever ignore the exception. Sometimes, you might see code such as the following:
//Following is an empty catch block
try {
...
} catch (SomeException e) {
}
The empty catch block means that the exception is simply ignored - it's not dealt with. You don't want to do this in your programs. At the minimum, if you must really, really ignore the exception, put a comment explaining why you wanted to ignore the exception. You can use printStackTrace to output a simple error message to tell you there was a problem. If you ignore the exception, because of a condition that you've predicted, it means that the program will run on despite the error. However, you're going to run the risk of a complete program failure down the road when conditions change. If you propagate the exception out, you can ensure that the program fails quickly and captures information that helps you fix the error.
Don't use Exception Handling for every Statement The goal of exception handling is to clarify programs - try not to use a try/catch/finally mechanism for every potential exception generating statement. A simple strategy is to enclose a significant amount of code within the try block and specify multiple catch blocks to account for all possible exceptions. End the whole thing with a single finally block if you need to release any resources held by the program. In any case, avoid placing try/catch/finally around each statement that might throw an exception. Your goal is to use exception handling to remove error processing code from the main program code.
Maintain Failure Atomicity Always strive to ensure that when an object throws an exception, the object continues to remain in a well-defined and usable state. Ideally, even after a method fails due to an exception, the object should be left in the state it was before the method was invoked, When a method can do this, it's said to possess the property of failure atomicity.
You can achieve failure atomicity by using any of the following programming techniques.
Design Immutable Objects The easiest way to achieve failure atomicity is by designing immutable objects. Although when you create an object you can change its contents, occasionally, it's a good idea to create objects whose contents cannot be changed after creation. An object such as this is called an immutable object and its class, an immutable class. A good example is the String class, which is an immutable class. You get automatic failure atomicity when an object is immutable, because the state of an object can't be modified after you create the object.
Check Parameters for Validity before the Operation If you're stuck with mutable objects, the best way to achieve failure atomicity is to perform a check for the validity of parameters before the program commences the modification of an object. The following example shows how you do this:
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
The initial size check ensures that the method will do two things when it tries to pop an element from an empty stack: it will throw an exception and it will do so while leaving the size field in a consistent state. Otherwise, the attempt to pop the element from an empty stack will leave the size field in a negative state which, of course, is an inconsistent state for the object to be in.
Attempt to Execute the Code before you Modify the Object You can write your programs in a way where the code that is susceptible to a potential exception, is run before any code that modifies an object. A good example would be where you would like to add an element to a TreeMap, wherein the new element must be compared using the TreeMap's ordering. If your code attempts to add an incorrect type element, it will fail when a search for the element in the tree is made, before the tree is modified.
Intercept the Failure Another strategy to achieve failure atomicity is to put in code that intercepts a failure that occurs during an operation, and which rolls back the object's state to what it was before the operation began. This strategy is often adopted when modifying disk based data, that is, data contained in a relational database, for example.
Perform Operations on a Temporary Copy of the Object You can limit state changes made to an object by changing a temporary copy of the object. You replace the contents of the object with the temporary copy once you complete the computational operations. If, for some reason, the computational work (say, a sort) ends up failing, no harm is done to the original object, as you're working with just a copy of the object.
Collect Failure Details If you're troubleshooting an easily reproducible failure, it's no big deal whether you're collecting detailed failure information. When dealing with exceptions that are not easily reproducible, it is critical that your exception's toString method captures sufficient details about the failure - to help diagnose and fix the failure.
When an exception occurs, your details message of an exception should capture the current values of all parameters and values that contributed to the exception. If your error message simply states IndexOutofBoundException, it's only of limited use and may, or may not, help you fix the data problem. If, on the other hand, your detail message for the IndexOutofBoundException contains the lower and upper bounds and the index value, you have something meaningful in your hands with which to proceed towards a fix of the failure condition.
Since the stack trace of the exception always contains the precise file and line number that threw the exception, you don't need a lot of information about the source code in your exception messages. To ensure that your exceptions always contain adequate failure details in their details message, use one of the constructors I explained about earlier in this chapter. It is better to do this than to capture the details within a simple string detail message.
The following example shows how you can use a more helpful constructor than the simple String constructor.
/**
* Construct an IndexOutOfBoundsException.
*
* @param lowerBound the lowest legal index value.
* @param upperBound the highest legal index value plus one.
* @param index the actual index value.
*/
public IndexOutOfBoundsException(int lowerBound, int upperBound,
int index) {
// Generate a detail message that captures the failure
super("Lower bound: " + lowerBound +
", Upper bound: " + upperBound +
", Index: " + index);
// Save failure information for programmatic access
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.index = index;
}
Top Tip: Provide accessor methods for all exceptions, especially for checked exceptions.
As mentioned earlier, it's sometimes useful to provide accessor methods to capture details regarding exactly why a failure happened. In the case of the example just shown, you can, for example, provide accessor methods for lowerBound, upperBound and index. It's critical that you provide such accessor methods for all accessor methods.My site list to string in java
Use Standard Java Exceptions As discussed earlier in the book, the Java platform offers a built-in set of unchecked exceptions which will take care of most of your exception mechanism setting needs. Make a point to try and use these preexisting exceptions before you run off coding your own custom exceptions. Other programmers are familiar with these preexisting exceptions and, therefore, they can easily understand your code. Also, since you'll be using just a set of basic exception classes and not a whole bunch of custom exceptions, your programs need less time to load.
Here are brief descriptions of the most common standard Java exceptions.
IllegalArgumentException
You throw this exception when a caller passes in an argument with an inappropriate value. For example, a calling program that passes a negative number in a parameter that denotes how many times you repeat an action.
IllegalStateException
This is the exception thrown when an object is illegally invoked because of its state - say, when a calling program tries to use an object before it has been initialized.
NullPointerException
Used when a parameter value is null when it ought not to be.
IndexOutofBoundsException
An exception thrown when a caller passes an out of range value in a parameter representing an index into a sequence.
ConcurrentModificationException
Thrown when an object designed for single thread usage finds that it was, or is, being concurrently modified.
UnsupportedOperationException
Thrown when an object doesn't support a specific operation such as when a program tries to delete an element from an append-only list.
Although in most cases it's quite apparent as to which exception applies to an error condition, sometimes, you may find that more than one exception might be correctly used for an error condition. There aren't any cut and dry rules for the specification of exceptions - as with some other things in Java, handling exceptions is an art as well as a science!
Document All of a Method's Exceptions Spend the necessary time to fully document all exceptions thrown by each method in an application. Declare all checked exceptions individually and use the Javadoc tag @throws to document the conditions under which each of the exceptions can be thrown.
It is critical that you don't fall into the bad habit of declaring that a method throws some super class of multiple exception cases that the method is set up to throw. That means that you never declare a method that can throw the generic exception classes Exception or Throwable! Using generic exceptions might handle the exception all right, but it keeps you from understanding the precise error that caused the exception to be thrown.
Top Tip: Always attempt to document every single exception that can potentially be thrown by each method in a program.
Take care to document both checked and unchecked exceptions. Since unchecked exceptions normally represent programming errors, documenting them can keep you from avoiding those errors. You can use the same Javadoc tag @Throws to document unchecked exceptions, as is the case for checked exceptions.
If multiple methods in a class can throw the same exception, you may document the exception once in the class's documentation comment. This is much more efficient than documenting the exception separately for each of the methods.
Finally, a useful rule of thumb when handling Java exceptions is to always throw early and catch late!
This finally wraps up our discussion of Java's exception handling mechanisms and how to make the best use of them in your code. Our next topic is the effective use of pre and post conditions in your code within the framework of what's called Java assertions, primarily as a way of testing code before you move it to production.
1 note
·
View note
Text
Crear, compilar, generar y ejecutar un JAR de Java que ejecuta un cmdlet de PowerShell utilizando Runtime
Crear, compilar, generar y ejecutar un JAR de Java que ejecuta un cmdlet de PowerShell utilizando Runtime
import java.io.*; public class CrearJava { public static void main(String[] args) { FileWriter fichero = null; PrintWriter pw = null; try { fichero = new FileWriter("EjecutarPowerShell.java"); pw = new PrintWriter(fichero); pw.println("import java.io.IOException;"); pw.println("import java.io.BufferedReader;"); pw.println("import java.io.IOException;"); pw.println("import…
View On WordPress
#IOException#Java#java.io.BufferedReader#java.io.InputStreamReader#java.io.IOException#PSVersion#PSVersionTable#stdout#System.out.println
0 notes
Text
Belajar Java: Menggunakan Prosedur dan Fungsi untuk Membuat Sub-program
Pada contoh program di pembahasan sebelumnya, kita hanya menulis kode intruksi pada fungsi main() saja.
Fungsi main() adalah fungsi utama dalam program Java. Semua kode yang kita tulis di dalamnya, akan langsung dieksekusi.
Tapi masalahnya sekarang:
“Bagaimana kalau kita membuat program yang cukup besar, apakah kita masih bisa menulis semua kodenya di dalam fungsi main()?”
Bisa-bisa saja, tapi kurang efektif dan akan menghabiskan banyak tenaga untuk mengetik kodenya.
Belum lagi kalau ada error…
“Lalu solusinya bagaimana?”
Solusinya menggunakan prosedur/fungsi.
Prosedur/fungsi dapat memecah program menjadi sub-sub program, sehingga kita bisa membuat program lebih efisien.
Penggunaan prosedur/fungsi dapat mengurangi pengetikan kode yang berulang-ulang.
Pada kesempatan ini, kita akan belajar menggunakan prosedur/fungsi pada Java untuk membuat program.
Pertama, kita kenalan dulu dengan prosedur dan fungsi. Setelah itu, dilanjutkan dengan contoh program.
Pengertian Prosedur, Fungsi, dan Method
Jangan bingung…karena ketiga-tiganya sama.
Prosedur, Fungsi, dan Method itu sama.
Prosedur adalah sebutan untuk fungsi yang tidak mengembalikan nilai. Fungsi ini biasanya ditandai dengan kata kunci void.
Fungsi adalah sebutan untuk fungsi yang mengembalikan nilai.
Method adalah fungsi yang berada di dalam Class. Sebutan ini, biasanya digunakan pada OOP.
Untuk memudahkan, mari kita sebut semuanya fungsi.
Cara Membuat Fungsi di Java
Fungsi harus dibuat atau ditulis di dalam class.
Struktur dasarnya seperti ini:
static TypeDataKembalian namaFungsi(){ // statemen atau kode fungsi }
Penjelasan:
Kata kunci static, artinya kita membuat fungsi yang dapat dipanggil tanpa harus membuat instansiasi objek.
Bingung? Nanti saya jelaskan.
TypeDataKembalian adalah tipe data dari nilai yang dikembalikan setelah fungsi dieksekusi.
namaFungsi() adalah nama fungsinya. Biasanya ditulis dengan huruf kecil di awalnya. Lalu, kalau terdapat lebih dari satu suku kata, huruf awal di kata kedua ditulis kapital.
Contoh:
static void ucapSalam(){ System.out.println("Selamat Pagi"); }
Tipe data void artinya kosong, fungsi tersebut tidak mengebalikan nilai apa-apa.
Cara Memanggil/Eksekusi Fungsi
Setelah kita membuat fungsi, selanjutnya kita akan mengeksekusi fungsinya.
Fungsi dapat dipanggil dari fungsi main atau dari fungsi yang lainnya.
Contoh pemanggilan fungsi dalam dalam funsgi main:
public static void main(String[] args){ ucapSalam(); }
Maka akan menghasilkan output:
Selamat Pagi
Kode lengkapnya, silahkan dicoba sendiri:
class BelajarFungsi { // membuat fungsi ucapSalam() static void ucapSalam(){ System.out.println("Selamat Pagi"); } // membuat fungsi main() public static void main(String[] args){ // memanggil/eksekusi fungsi ucapSalam() ucapSalam(); } }
Fungsi dengan Parameter
Parameter adalah variabel yang menampung nilai untuk diproses di dalam fungsi. Parameter berperan sebagai input untuk fungsi.
Struktur dasarnya seperti ini:
static TipeData namaFungsi(TipeData namaParameter, TipeData namaParameterLain){ // kode fungsi }
Penjelasan:
Parameter ditulis di antara tanda kurung (...);
Parameter harus diberikan tipe data;
Bila terdapat lebih dari satu parameter, maka dipisah dengan tanda koma.
Contoh fungsi yang memiliki parameter:
static void ucapin(String ucapan){ System.out.println(ucapan); }
Pada contoh tersebut, kita membuat parameter bernama ucapan dengan tipe String. Sehingga kita bisa menggunakan variabel ucapan di dalam fungsi.
Cara pemanggilan fungsi yang memiliki parameter:
ucapin("Hallo!"); ucapin("Selamat datang di pemrograman Java"); ucapin("Saya kira ini bagian terakhir"); ucapin("Sampai jumpa lagi, ya!");
Hasil outputnya:
Hallo! Selamat datang di pemrograman Java Saya kira ini bagian terakhir Sampai jumpa lagi, ya!
Fungsi yang Mengembalikan Nilai
Setelah fungsi memproses data yang diinputkan melalui parameter, selanjutnya fungsi harus mengembalikan nilai agar dapat diolah pada proses berikutnya.
Pengembalian nilai pada fungsi menggunakan kata kunci return.
Contoh:
static int luasPersegi(int sisi){ int luas = sisi * sisi; return luas; }
Pada contoh tersebut, kita membuat sebuah parameter bernama sisi. Kemudian fungsi akan mengembalikan nilai dengan tipe int (integer) dari variabel luas.
Contoh pemanggilanya:
System.out.println("Luas Persegi dengan panjang sisi 5 adalah " + luasPersegi(5));
Hasil Output:
Luas Persegi dengan panjang sisi 5 adalah 25
Pemanggilan Fungsi di Fungsi Lain
Fungsi-fungsi dapat saling memanggil untuk memproses data.
Contoh, sebuah program Kalkulator Bangun Ruang memiliki fungsi-fungsi: luasPersegi(), luasPersegiPanjang(), luasSegitiga(), luasBalok(), luasKubus() dsb.
Fungsi-fungsi tersebut dapat saling membantu, contoh fungsi luasKubus() membutuhkan fungsi luasPersegi().
Rumus:
Luas Kubus = 6 * luasPersegi; Luas Persegi = sisi * sisi;
Maka programnya bisa dibuat seperti ini:
public class BangunRuang { public static void main(String[] args) { int s = 12; int luas = luasKubus(s); System.out.println(luas); } // membuat fungsi luasPersegi() static int luasPersegi(int sisi){ return sisi * sisi; } // membuat fungsi luasKubus() static int luasKubus(int sisi){ // memanggil fungsi luasPersegi return 6 * luasPersegi(sisi); } }
Hasil output
864
Fungsi Static dan Non-Static
Pada contoh-contoh diatas, kita menggunakan kata kunci static sebelum membuat fungsi.
Kata kunci static akan membuat fungsi dapat dieksekusi langsung, tanpa harus membuat instansiasi objek dari class.
Contoh:
public class FungsiStatic { // Fungsi non-static void makan(String makanan){ System.out.println("Hi!"); System.out.println("Saya sedang makan " + makanan); } // fungsi static static void minum(String minuman){ System.out.println("Saya sedang minum " + minuman); } // fungsi main public static void main(String[] args) { // pemanggilan fungsi static minum("Kopi"); // mambuat instansiasi objek saya dari class FungsiStatic FungsiStatic saya = new FungsiStatic(); // pemanggilan fungsi non-static saya.makan("Nasi Goreng"); } }
Pada contoh tersebut, fungsi makan() adalah fungsi non-static. Sedangkan fungsi minum() adalah fungsi static.
Hasil output dari program di atas:
Saya sedang minum Kopi Hi! Saya sedang makan Nasi Goreng
Apabila kita tidak membuat objek untuk memanggil fungsi non-static, maka akan terjadi error.
Variabel Global dan Variabel Lokal pada Java
Variabel global adalah variabel yang bisa diakses dari semua fungsi. Sedangkan variabel lokal adalah variabel yang hanya bisa diakses dari dalam fungsi tempat variabel itu berada.
Bingung?
Mari kita lihat contohnya:
class ProgramKu{ // ini variabel global static String nama = "Programku"; static String version = "1.0.0"; static void help(){ // ini variabel lokal String nama = "Petani Kode"; // mengakses variabel global di dalam fungso help() System.out.println("Nama: " + nama); System.out.println("Versi: " + version); } public static void main(String args[]){ // panggil fungsi help() help(); System.out.println("Nama: " + nama); System.out.println("Versi: " + version); } }
Hasil outputnya:
Nama: Petani Kode Versi: 1.0.0 Nama: Programku Versi: 1.0.0
Saat pemanggilan fungsi help() kita membuat ulang variabel nama. Sehingga variabel nama menjadi variabel lokal pada fungsi help() dan nilainya berubah menjadi "Petani Kode".
Sedangkan, saat kita akases lagi variabel nama melalui fungsi main() nilainya tetap sama seperti yang didefinisikan.
Contoh Program dengan Fungsi dan Prosedur
Program ini adalah program sederhana dengan fitur sebagai berikut:
Baca data dari ArrayList
Simpan data ke ArrayList
Ubah data
Hapus Data
Keluar
Belum tahu tentang ArrayList?
Silahkan baca meteri: Mengenal Array di Java
Baiklah, silahkan buat class baru bernama FungsiProsedur. Lalu impor class-class yang dibutuhkan.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList;
Setelah itu buat variabel global di dalam class FungsiProsedur:
static ArrayList listBuah = new ArrayList(); static boolean isRunning = true; static InputStreamReader inputStreamReader = new InputStreamReader(System.in); static BufferedReader input = new BufferedReader(inputStreamReader);
Penjelasan:
Variabel listBuah adalah variabel global untuk menyimpan nama-nama buah.
Variabel isRunning adalah variabel global untuk membuat loop.
Kemudian inputStreamReader dan input adalah objek yang kita butuhkan untuk mengambil input dari keyboard.
Setelah itu, buat masing-masing fungsi.
Fungsi untuk menampilkan menu:
static void showMenu() throws IOException { System.out.println("========= MENU ========"); System.out.println("[1] Show All Buah"); System.out.println("[2] Insert Buah"); System.out.println("[3] Edit Buah"); System.out.println("[4] Delete Buah"); System.out.println("[5] Exit"); System.out.print("PILIH MENU> "); int selectedMenu = Integer.valueOf(input.readLine()); switch(selectedMenu){ case 1: showAllBuah(); break; case 2: insertBuah(); break; case 3: editBuah(); break; case 4: deleteBuah(); break; case 5: System.exit(0); break; default: System.out.println("Pilihan salah!"); } }
Fungsi tersebut bertugas untuk menampilkan menu dan menentukan fungsi mana yang akan dipanggil berdasarkan nomer menu yang diinputkan.
Apa itu throws IOException?
Nanti saya akan bahas di kesempatan berikutnya. Untuk saat ini diabaikan saja dulu. Ini karena kita menggunakan Buffereader, jadi throws IOException wajib ditulis.
Fungsi untuk menampilkan data:
static void showAllBuah(){ if(listBuah.isEmpty()){ System.out.println("Belum ada data"); } else { // tampilkan semua buah for(int i = 0; i < listBuah.size(); i++){ System.out.println(String.format("[%d] %s",i, listBuah.get(i))); } } }
Fungsi tersebut bertugas menampilkan isi dari listBuah. Kalau listBuah kosong, maka akan ditampilkan pesan "Belum ada data".
Fungsi untuk menambah data buah:
static void insertBuah() throws IOException{ System.out.print("Nama buah: "); String namaBuah = input.readLine(); listBuah.add(namaBuah); }
Pada fungsi tersebut, kita menggunakan method listBuah.add(namaBuah); untuk menambah data ke dalam listBuah berdasarkan namaBuah yang diberikan.
Fungsi untuk mengubah data buah:
static void editBuah() throws IOException{ showAllBuah(); System.out.print("Pilih nomer buah: "); int indexBuah = Integer.valueOf(input.readLine()); System.out.print("Nama Baru: "); String namaBaru = input.readLine(); // ubah nama buah listBuah.set(indexBuah, namaBaru); }
Pertama kita perlu tampilkan dulu daftar buahnya, lalu kita minta user untuk memilih buah mana yang akan diedit.
Setelah itu, kita update buahnya dengan method listBuah.set(indexBuah, namaBaru);.
Fungsi untuk menghapus buah:
static void deleteBuah() throws IOException{ showAllBuah(); System.out.print("Pilih nomer buah: "); int indexBuah = Integer.valueOf(input.readLine()); // hapus buah listBuah.remove(indexBuah); }
Hampir sama seperti edit buah, untuk menghapus buah kita juga butuh nomer indeks buah yang akan dihapus.
Lalu mengapusnya dengan method listBuah.remove(indexBuah);.
Fungsi main:
public static void main(String[] args) throws IOException { do { showMenu(); } while (isRunning); }
Lengkap sudah, berikut ini bentuk kode lengkapnya.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class FungsiProsedur { static ArrayList listBuah = new ArrayList(); static boolean isRunning = true; static InputStreamReader inputStreamReader = new InputStreamReader(System.in); static BufferedReader input = new BufferedReader(inputStreamReader); static void showMenu() throws IOException{ System.out.println("========= MENU ========"); System.out.println("[1] Show All Buah"); System.out.println("[2] Insert Buah"); System.out.println("[3] Edit Buah"); System.out.println("[4] Delete Buah"); System.out.println("[5] Exit"); System.out.print("PILIH MENU> "); int selectedMenu = Integer.valueOf(input.readLine()); switch(selectedMenu){ case 1: showAllBuah(); break; case 2: insertBuah(); break; case 3: editBuah(); break; case 4: deleteBuah(); break; case 5: System.exit(0); break; default: System.out.println("Pilihan salah!"); } } static void showAllBuah(){ if(listBuah.isEmpty()){ System.out.println("Belum ada data"); } else { // tampilkan semua buah for(int i = 0; i < listBuah.size(); i++){ System.out.println(String.format("[%d] %s",i, listBuah.get(i))); } } } static void insertBuah() throws IOException{ System.out.print("Nama buah: "); String namaBuah = input.readLine(); listBuah.add(namaBuah); } static void editBuah() throws IOException{ showAllBuah(); System.out.print("Pilih nomer buah: "); int indexBuah = Integer.valueOf(input.readLine()); System.out.print("Nama Baru: "); String namaBaru = input.readLine(); // ubah nama buah listBuah.set(indexBuah, namaBaru); } static void deleteBuah() throws IOException{ showAllBuah(); System.out.print("Pilih nomer buah: "); int indexBuah = Integer.valueOf(input.readLine()); // hapus buah listBuah.remove(indexBuah); } public static void main(String[] args) throws IOException { do { showMenu(); } while (isRunning); } }
Setelah itu, silahkan dijalankan dan perhatikanlah hasilnya.
========= MENU ======== [1] Show All Buah [2] Insert Buah [3] Edit Buah [4] Delete Buah [5] Exit PILIH MENU> 1 Belum ada data ========= MENU ======== [1] Show All Buah [2] Insert Buah [3] Edit Buah [4] Delete Buah [5] Exit PILIH MENU> 2 Nama buah: Apel ========= MENU ======== [1] Show All Buah [2] Insert Buah [3] Edit Buah [4] Delete Buah [5] Exit PILIH MENU> 1 [0] Apel ========= MENU ======== [1] Show All Buah [2] Insert Buah [3] Edit Buah [4] Delete Buah [5] Exit PILIH MENU>
Silahkan coba untuk melakukan insert, edit, dan delete.
1 note
·
View note
Text
vérifier la connectivité Internet sur un ordinateur en Java
Voici un exemple de code Java pour vérifier la connectivité Internet sur un ordinateur : import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; public class InternetChecker { public static void main(String[] args) { try { // création d'une instance d'InetAddress pour accéder à un site web InetAddress address = InetAddress.getByName("www.google.com"); //…

View On WordPress
0 notes
Text
File Writer Class
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java.
Import java.io.IOException;
public class demo
{
public static void main(String args[])
{
try
{
Filewriter obj= new Filewriter("javafile.txt");
Writer.write("Files in java are good");
writer.close();
System.out.println("successfully writen");
}
catch(IoException e)
{
System.out.println("An error has occured");
e.printstacktrace();
}}}
1 note
·
View note
Text
CAS Project evidence
===TileContent.java===
import java.awt.image.BufferedImage;
public class TileContent { BufferedImage img;String type;int x;int y;
public TileContent(BufferedImage img_,String type_,int x_,int y_) { img=img_;type=type_;x=x_;y=y_;
} }
===TileImagesConfig.java===
import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList;
import javax.imageio.ImageIO;
public class TileImagesConfig { InputStream t; BufferedImage slime; BufferedImage fireSlime; BufferedImage waterSlime; BufferedImage golem; BufferedImage blaze; BufferedImage theWorld; BufferedImage hpPotion; BufferedImage scorePotion;public TileImagesConfig(){ } public void preConfig() throws IOException { t = getClass().getResourceAsStream("imgs/monsters/slime.png"); slime = ImageIO.read(t); t = getClass().getResourceAsStream("imgs/monsters/slime2.png"); fireSlime = ImageIO.read(t); t = getClass().getResourceAsStream("imgs/monsters/slime3.png"); waterSlime = ImageIO.read(t); t = getClass().getResourceAsStream("imgs/monsters/golem.png"); golem = ImageIO.read(t); t = getClass().getResourceAsStream("imgs/monsters/blaze.png"); blaze = ImageIO.read(t); t = getClass().getResourceAsStream("imgs/monsters/potionHp.png"); hpPotion = ImageIO.read(t); t = getClass().getResourceAsStream("imgs/monsters/potionScore.png"); scorePotion = ImageIO.read(t); t = getClass().getResourceAsStream("imgs/monsters/theWorld.png"); theWorld = ImageIO.read(t); } public void config(ArrayList<BufferedImage> imgs,ArrayList<String> types) { //common for(int i=0;i<10;i++) { imgs.add(slime);types.add("slime");imgs.add(slime);types.add("slime2"); imgs.add(fireSlime);types.add("fireSlime");imgs.add(fireSlime);types.add("fireSlime"); imgs.add(waterSlime);types.add("waterSlime");imgs.add(waterSlime);types.add("waterSlime2"); } //rare for(int i=0;i<6;i++) { imgs.add(golem);types.add("golem"); imgs.add(blaze);types.add("blaze");imgs.add(blaze);types.add("blaze");imgs.add(blaze);types.add("blaze2"); } //legend imgs.add(hpPotion);types.add("hpPotion");imgs.add(hpPotion);types.add("hpPotion"); imgs.add(scorePotion);types.add("scorePotion"); imgs.add(theWorld);types.add("theWorld");imgs.add(theWorld);types.add("theWorld");imgs.add(theWorld);types.add("theWorld2"); }
}
0 notes
Text
Mockwebserver enqueue

#Mockwebserver enqueue code#
#Mockwebserver enqueue series#
You can further customise it using onStatus() method like below.
#Mockwebserver enqueue series#
The retrieve method in WebClient throws WebClientResponseException when there will be a 4xx and 5xx series exception is received. To handle errors in WebClient you can use extend retrieve method. If you have to make a POST call you can leverage post method and in that case you will have to pass a body to the method body, there are a lot of methods to play around with, once you start to use it you will have various methods to put in use for sure. The method getPost is the method which will be making the request with the help of webclient instance and retrieve the response from external API call. In the scenario above, we are leveraging GET method and returning a response from API call. You can choose HTTP methods depending upon the nature of the HTTP call and make request to it. Please refer to all the methods while you use it. In step3 we have created an instance of WebClient and initialized it by using WebClient builder, it will create a WebClient object and will also allow you to customise your call with several methods it offers. Add Spring WebFlux dependency to you POM.XML If you are using any other build tool, please find the dependency on the internet, they are easily available. Note – I would be using maven build tool to show the demo. So, make sure you are using Spring WebFlux already if you plan to use WebClient to make API calls. Pio ufheaoa a hatjafni nd neuwyufk usm tumfeyb id o CeyvCopjipce afsurl. setResponseCode(200)) Kaogc uten hmema lkib-yz-gxuq: Oco vwa vibsRibVisyax tcoq meu xsuuxoz jafade xi ayveiau i xugcuhzo. The main advantage of using the WebClient is, It’s reactive as it uses webflux and It’s also non blocking in nature by default and response will always be returned in either Mono or Flux. // 1 mockWebServer.enqueue( // 2 MockResponse() // 3. You can leverage any of these methods to make calls to the external service asynchronously. WebClient is simply an interface which offers some methods to make calls to rest services, there are methods like GET, POST, PUT, PATCH, DELETE and OPTIONS. It was introduced in Spring 5 as as part of Web reactive framework that helps to build reactive and non blocking web applications. If you are using Spring WebFlux, you can choose to use WebClient to call external rest services. I am overriding the “base-url” property with the value of the MockWebServer url and random port (e.g.Alright, In this article we will talk about Spring Boot Web Client. The method takes in the registry of properties, and lets you add or override properties. status ( addFilters = false ) class WebClientIntegrationTest Import .ObjectMapper import import import import .Assertions import .AfterAll import .BeforeAll import .Test import .annotation.Autowired import. import .context.SpringBootTest import .DynamicPropertyRegistry import .DynamicPropertySource import .servlet.MockMvc import .servlet.ResultActions import. import java.io.IOException import import static org.
#Mockwebserver enqueue code#
Here is the test code for handling 200 responses for GET and POST and a 500 response: MockWebServer will generate a url, which we will insert into our application properties using are also choosing to not require the MockMvc to pass a token to our application, because that concern is better tested after we deploy our application. If you want, you can skip to my GitHub repo with the adle file and example code. It is a simple pass-through API that hits a backend and returns the response from it. Our project will include Spring Security with OAuth2 Client Credentials, Actuator, Spring Web, JUnit 5 and Webflux, and some other common dependencies. We will be using Spring Boot version 2.6.3 with Gradle wrapper version 7.3.3 and Java 11. Shown below as Gradle imports: testImplementation '3:okhttp:4.0.1' testImplementation '3:mockwebserver:4.0.1' 3. baseUrl (server.url ('/')) // Other builder methods.build () Second, to get responses from the mock web server, you need to enqueue the expected. Retrofit retrofit new Retrofit.Builder (). Generally, you configure your retrofit to call the server's endpoint. To use MockWebServer, you need two dependencies. If you want to set the url, you'll need to pass it to the start () method. Better still, it enables you to test the token caching functionality that comes built into WebClient, but we won’t get to that today. This lets you test your WebClient setup as well. Spring Boot 2.2.6 introduced the which allows you to insert the MockWebServer url into the properties at runtime. The tests overrode the WebClient, and so did not cover the configuration of the WebClient (which could be incorrectly configured). The intention was to write an integration test that did not touch the inside of the code, but only the edges. I had previously written an article Integration Testing with MockWebServer that explained a way to write integration tests for a web application using WebClient and MockWebServer (okhttp).

0 notes
Text
Redis pipe example for java
Redis pipe example
import org.joda.time.DateTime; import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.stream.Stream; public class RedisBatchVal { public static void main(String[] args) throws IOException { Jedis jedis = new Jedis(); jedis.select(1); pipe(jedis); iptop(jedis); } private static void pipe(Jedis jedis) throws IOException { HashMap<String, Integer> map = inputBatchKey(); long startTime = System.currentTimeMillis(); //获取开始时间 Pipeline pipe = jedis.pipelined(); Map<String, Response<String>> newMap = new HashMap<>(); for (Map.Entry<String, Integer> entry : map.entrySet()) { newMap.put(entry.getKey(), pipe.get(entry.getKey())); } pipe.sync(); long endTime = System.currentTimeMillis(); //获取结束时间 System.out.println(MainApp.getCurrentThreadName() + new DateTime().toString("yyyy-MM-dd HH:mm:ss") + "程序运行时间:" + (endTime - startTime) + "ms"); //输出程序运行时间 HashMap<String, Integer> tempMap = new HashMap<>(); for (Map.Entry<String, Response<String>> stringResponseEntry : newMap.entrySet()) { Response<String> value = stringResponseEntry.getValue(); String key = stringResponseEntry.getKey(); Integer integer = Integer.valueOf(value.get()); tempMap.put(key, integer); } sort(tempMap); } private static HashMap<String, Integer> inputBatchKey() throws IOException { HashMap<String, Integer> map = new HashMap<>(); try (Stream<String> lines = Files.lines(Paths.get("/Users/xmc/IdeaProjects/cron-ftp/src/main/resources/a.txt"), Charset.defaultCharset())) { lines.forEach(key -> { map.put(key, null); }); } return map; } private static void iptop(Jedis jedis) throws IOException { HashMap<String, Integer> map = inputBatchKey(); long startTime = System.currentTimeMillis(); //获取开始时间 Map<String, Integer> treeMap = new HashMap(); for (Map.Entry<String, Integer> entry : map.entrySet()) { String key = entry.getKey(); treeMap.put(entry.getKey(), Integer.valueOf(jedis.get(key))); } long endTime = System.currentTimeMillis(); //获取结束时间 System.out.println(MainApp.getCurrentThreadName() + new DateTime().toString("yyyy-MM-dd HH:mm:ss") + "程序运行时间:" + (endTime - startTime) + "ms"); //输出程序运行时间 sort(treeMap); } private static void sort(Map<String, Integer> treeMap) { List<Map.Entry<String, Integer>> list_Data = new ArrayList<Map.Entry<String, Integer>>(treeMap.entrySet()); Collections.sort(list_Data, (o1, o2) -> { if ((o2.getValue() - o1.getValue()) > 0) return 1; else if ((o2.getValue() - o1.getValue()) == 0) return 0; else return -1; }); } }
1 note
·
View note
Text
Compilar y ejecutar una clase de Java que ejecuta un cmdlet de PowerShell utilizando Runtime
Compilar y ejecutar una clase de Java que ejecuta un cmdlet de PowerShell utilizando Runtime
Clase de Java que ejecuta PowerShell (la clase tiene que ser compilada) import java.io.IOException; import java.util.concurrent.TimeUnit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class EjecutarPowerShell { public static void main(String[] args) throws InterruptedException { Runtime runtime = Runtime.getRuntime(); try { Process process =…
View On WordPress
#IOException#Java#java.io.BufferedReader#java.io.InputStreamReader#java.io.IOException#java.util.concurrent.TimeUnit#PSVersion#PSVersionTable#stdout#System.out.println
0 notes
Text
How to program the Konami Code (Java Swing event handling)
A basic implementation of the Konami code check is provided. You probably want to optimize it for other magic inputs but this is probably what you can start with.
Why did I use Java Swing? (AKA, UI libraries?). Because console input by default is not adjusted to take the arrow keys as events since they're used for scrolling and control. To handle cases like these, using KeyListener events from a UI library is recommended; AWT provides a pretty good implementation.
To display Unicode artifacts on screen, I have to use Swing components, because AWT is not well adjusted to the Unicode-first world.
import javax.swing.*; import java.awt.Font; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class Main { public static char[] KONAMI = new char[] { 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 10 }; public static int[] buffer = new int[KONAMI.length]; public static char[] charBuffer = new char[KONAMI.length]; public static Map<Integer, Character> chars = new HashMap<>(); public static int i = 0; static class Konami extends JFrame implements KeyListener { JLabel l; JLabel r; Konami() { setSize(600, 200); setLayout(null); setVisible(true); chars.put(0, ' '); chars.put(38, '↑'); chars.put(40, '↓'); chars.put(37, '←'); chars.put(39, '→'); chars.put(66, 'b'); chars.put(65, 'a'); chars.put(10, '↵'); l = new JLabel(); r = new JLabel(); l.setFont(new Font("Mono", Font.PLAIN, 24)); r.setFont(new Font("Mono", Font.PLAIN, 24)); l.setBounds(20, 50, 600, 30); r.setBounds(20, 100, 500, 30); add(l); add(r); addKeyListener(this); l.setText(convertBuffer()); } private String convertBuffer(){ for(int i = 0; i < buffer.length; i++){ charBuffer[i] = chars.getOrDefault(buffer[i], (char)buffer[i]); } return Arrays.toString(charBuffer); } private void checkKonami(int keyCode) throws IOException { if(i>=KONAMI.length) { scrollBuffer(); buffer[KONAMI.length - 1] = keyCode; } else { buffer[i++] = keyCode; } } private static boolean konamiPressed() { for(int i = 0; i < KONAMI.length; i++){ if(buffer[i] != KONAMI[i]) return false; } return true; } private static void scrollBuffer() { for(int i = 0; i < KONAMI.length-1; i++){ buffer[i] = buffer[i+1]; } buffer[KONAMI.length-1] = 0; } @Override public void keyPressed(KeyEvent e) { try { checkKonami(e.getKeyCode()); } catch (IOException ioException) { ioException.printStackTrace(); } } @Override public void keyReleased(KeyEvent e) { l.setText(convertBuffer()); if(konamiPressed()){ r.setText("you're cool!"); } else { r.setText(""); } } @Override public void keyTyped(KeyEvent e) { } } public static void main(String[] args) throws IOException { new Konami(); } }
0 notes