• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/62

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

62 Cards in this Set

  • Front
  • Back

GET

– use it to fetch a resourceThe GET verb denotes the only method that can be cached at multiple levels. Resources can be cached at the origin, at the client and in between. Network devices can participate in the caching strategy, in turn significantly reducing the load on the origin service.

POST

– use it to create a resourceThe POST verb denotes the creation of a resource. This method is not cacheable and is the most dangerous of all. Using this method guaranties that the system state will be modified.It can also be used to push data to the service. When the service receives the data, it can create a new resource returning the URI corresponding to the new resource. It can react to the received data in various unpredictable ways.

PUT

– use it to update a resourceThe PUT verb denotes the modification of a resource state. The difference between PUT and POST, is that PUT modifies the resource state in anidempotent manner. No matter how many times a PUT gets executed, the outcome is always the same and predictable.PUT allows you to push a resource to a specific URI. If the resource does not exist it creates it. If it exists it replaces it.

HEAD

– use it to retrieve meta-information without the response bodyThe HEAD verb is very useful. It can be used to fetch E-Tags and other meta-information for specific resources without the full representational state of the requested resource. This empowers the consumers to verify if a specific resource has been modified since the last time it was fetched. Further more, this is a great trick to help reduce the amount of data required to travel over the network for each request.PATCH

PATCH

– use it to make partial modifications to resourcesRarely have I seen this verb used but I’m sure it comes in handy when a consumer is required to send a delta of the original and the modified representational state to the server. In turn reducing the amount of data required to travel over the network and giving the consumer a better experience.

Hypermedia

– use it to make partial modifications to resourcesRarely have I seen this verb used but I’m sure it comes in handy when a consumer is required to send a delta of the original and the modified representational state to the server. In turn reducing the amount of data required to travel over the network and giving the consumer a better experience.

HAL

HAL is a simple way of linking with JSON or XML.It provides a set of conventions for expressing hyperlinks to, and embeddedness of, related resources – the rest of a HAL document is just plain old JSON or XML.HAL is a bit like HTML for machines, in that it is designed to drive many different types of application. The difference is that HTML is intended for presenting a graphical hypertext interface to a ‘human actor’, whereas HAL is intended for presenting a machine hypertext interface to ‘automated actors’.

PUT vs. POST

PUT vs POST in REST. In other words, POST is used to create. The PUT method requests that the enclosed entity be stored under the supplied Request-URI . If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server.

SOAP (not REST)

SOAP defines the XML-based message format that Web service-enabled applicationsuse to communicate and inter-operate with each other over the Web.

WSDL (used with SOAP)

Part of the magic is the Web Services Description Language (WSDL). This is another file that’s associated with SOAP. It provides a definition of how the Web service works, so that when you create a reference to it, the IDE can completely automate the process. So, the difficulty of using SOAP depends to a large degree on the language you use.

Error handling in SOAP

built in so easy to handle errors

REST - definition / benefits

REST provides a lighter weight alternative. Instead of using XML to make a request, REST relies on a simple URL in many cases. In some situations you must provide additional information in special ways, but most Web services using REST rely exclusively on obtaining the needed information using the URL approach. REST can use four different HTTP 1.1 verbs (GET, POST, PUT, and DELETE) to perform tasks

Difference in data types SOAP vs. REST

Unlike SOAP, REST doesn’t have to use XML to provide the response. You can find REST-based Web services that output the data in Command Separated Value (CSV), JavaScript Object Notation (JSON) and Really Simple Syndication (RSS).

Argument of SOAP vs. REST

SOAP is definitely the heavyweight choice for Web service access. It provides the following advantages when compared to REST:




Language, platform, and transport independent (REST requires use of HTTP)




Works well in distributed enterprise environments (REST assumes direct point-to-point communication)




StandardizedProvides significant pre-build extensibility in the form of the WS* standards




Built-in error handlingAutomation when used with certain language products




REST is easier to use for the most part and is more flexible.




It has the following advantages when compared to SOAP:




No expensive tools require to interact with the Web service




Smaller learning curveEfficient (SOAP uses XML for all messages, REST can use smaller message formats)




Fast (no extensive processing required)




Closer to other Web technologies in design philosophy

What do you need to do for a connection to a URL and get data?

URL oracle = new




URL("http://www.oracle.com/");




URLConnection yc = oracle.openConnection();




BufferedReader in = new BufferedReader(new InputStreamReader( yc.getInputStream()));




String inputLine;


while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close();

Given a string, return a new string where the first and last chars have been exchanged.

public String frontBack(String str) {




if (str.length() <= 1) return str;




String mid = str.substring(1, str.length()-1);




// last + mid + first return str.charAt(str.length()-1) + mid + str.charAt(0);




}

Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.

public String front3(String str) {




String front;




if (str.length() >= 3) {


front = str.substring(0, 3);


} else {


front = str;


}




return front + front + front;




}

Given a string, take the last char and return a new string with the last char added at the front and back, so "cat" yields "tcatt". The original string will be length 1 or more.

public String backAround(String str) {




// Get the last char String last = str.substring(str.length() - 1);




return last + str + last;




}

Return true if the given non-negative number is a multiple of 3 or a multiple of 5. Use the % "mod" operator

public boolean or35(int n)


{




return (n % 3 == 0) || (n % 5 == 0);




}

Given a string, take the first 2 chars and return the string with the 2 chars added at both the front and back, so "kitten" yields"kikittenki". If the string length is less than 2, use whatever chars are there.

public String front22(String str) {




// First figure the number of chars to take int take = 2;




if (take > str.length()) {


take = str.length();


}




String front = str.substring(0, take);




return front + str + front;




}

Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. Note: use .equals() to compare 2 strings.

public String notString(String str) {




if (str.length() >= 3 && str.substring(0, 3).equals("not"))


{


return str;


}


return "not " + str;


}

package supports regular expression processing

java.util.regex

what do you use for regular expressions in Java?

the Pattern and Matcher classes




use the compile function on the pattern instance

Regex example - matches any word

String regex = "\\w+";




Pattern pattern = Pattern.compile(regex);




String candidate = "asdf Java2s.com";




Matcher matcher = pattern.matcher(candidate);




if (matcher.find()) { System.out.println("GROUP 0:" + matcher.group(0));


}

Reg ex example

String regex = "[a-z]@.";




Pattern p = Pattern.compile(regex);




String str = "abc@yahoo.com,123@cnn.com,abc@google.com";




Matcher m = p.matcher(str);




if (m.find()) {




String foundStr = str.substring(m.start(), m.end());




System.out.println("Found string is:" + foundStr);




}

what does the overloaded 2 argument pattern.compile method do?

sets options on the pattern. IE - Pattern.LITERAL

Key parts of REG EX

Pattern p = Pattern.compile(regex);




Matcher m = p.matcher(source);




while (m.find()) {




System.out.println("Matched Text:" + m.group() + ", Start:" + m.start() + ", " + "End:" + m.end());




}




OUTPUT:


Matched Text: c@e Start:2 End:2

Java I/O File example

File f = new File(pathname); System.out.println("File Name: " + f.getName()); System.out.println("File exists: " + f.exists()); System.out.println("Absolute Path: " + f.getAbsolutePath());

Creating a File - Java Code

File dummyFile = new File("test.txt");




boolean fileCreated = dummyFile.createNewFile();





Creating a file in the TMP directory

File tempFile = File.createTempFile("abc", ".txt");

New Directory Java code

File newDir = new File("C:\\users\\home");




newDir.mkdir();

List of files in a root directories - code

File[] roots = File.listRoots(); System.out.println("List of root directories:");




for (File f : roots) { System.out.println(f.getPath());


}

List of files and directories

// Change the dirPath value to list files from your directory




String dirPath = "C:\\";


File dir = new File(dirPath);




File[] list = dir.listFiles();




for (File f : list) {


if (f.isFile())


{ System.out.println(f.getPath() + " (File)"); } else if (f.isDirectory()) { System.out.println(f.getPath() + " (Directory)"); } }

Filefilter written in lambda exp

FileFilter filter = file -> {




if (file.isFile()) {




String fileName = file.getName().toLowerCase(); if (fileName.endsWith(".sys")) {




return false;


} }


return true;


};

Using a FileFilter

FileFilter filter = file -> {


if (file.isFile()) {


String fileName = file.getName().toLowerCase();


if (fileName.endsWith(".sys")) {


return false; }


}


return true;


};






File[] list = dir.listFiles(filter);

Reading data from a file

String dataSourceFile = "asdf.txt";




try (


FileInputStream fin = new FileInputStream(dataSourceFile))


{


byte byteData;


while ((byteData = (byte) fin.read()) != -1) { System.out.print((char) byteData);


}


} catch (FileNotFoundException e) {


; } catch (IOException e) {


e.printStackTrace();


}


}

Getting a File input stream

try (


FileInputStream fin = new FileInputStream(dataSourceFile)


) {

Use this. Buffered Input Stream code ex.

String srcFile = "test.txt";




try (


BufferedInputStream bis = new BufferedInputStream(new FileInputStream( srcFile))


) {




// Read one byte at a time and display it byte byteData;


while ((byteData = (byte) bis.read()) != -1) { System.out.print((char) byteData); }


} catch (Exception e2) {


e2.printStackTrace(); }

Buffered Output Stream

has better speed...




BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("your output file path");




then can use write(), flush(), and close() methods

Writing to a File

// Get the line separator for the current platform




String lineSeparator = System.getProperty("line.separator");




String line1 = "test"; String line2 = "test1"; String line3 = "test2"; String line4 = "test3";




try (


FileOutputStream fos = new FileOutputStream(destFile))


{ fos.write(line1.getBytes()); fos.write(lineSeparator.getBytes()); fos.write(line2.getBytes()); fos.write(lineSeparator.getBytes()); fos.write(line3.getBytes()); fos.write(lineSeparator.getBytes()); fos.write(line4.getBytes());




// Flush the written bytes to the file


fos.flush();


System.out.println("Text has been written to " + (new File(destFile)).getAbsolutePath());


} catch (Exception e2) {


e2.printStackTrace();


}

PrintStream - definition

The PrintStream class is a concrete decorator for the output stream.




PrintStream can print any data type values, primitive or object, in a suitable format for printing.




PrintStream can write data to the output stream do not throw an IOException.




If a method throws an IOException, PrintStream sets an internal flag, rather than throwing the exception to the caller.




The flag can be checked using its checkError() method, which returns true if an IOException occurs during the method execution.




PrintStream has an auto-flush capability. We can specify in its constructor that it should flush the contents written to it automatically.

PrintStream example

String destFile = "luci3.txt";




try (


PrintStream ps = new PrintStream(destFile))


{


ps.println("test");


ps.println("test1");


ps.println("test2");


ps.print("test3");




// flush the print stream


ps.flush();


System.out.println("Text has been written to " + (new File(destFile).getAbsolutePath()));


} catch (FileNotFoundException e1) { e1.printStackTrace();


}

DataOutputStream - def

DataOutputStream can write Java primitive data type values to an output stream.




The DataOutputStream class contains a write method to write a data type. It supports writing a string to an output stream using the writeUTF(String text) method.




To write Java primitive data type values to a file named primitives.dat, we construct an object of DataOutputStream as follows:




DataOutputStream dos = new DataOutputStream(new FileOutputStream("primitives.dat"));

DataOutputStream ex.

try (


DataOutputStream dos = new DataOutputStream(new FileOutputStream( destFile))) {


dos.writeInt(765);


dos.writeDouble(6789.50); dos.writeBoolean(true);


dos.writeUTF("Java Input/Output is cool!");

Java pipes code

PipedInputStream pis = new PipedInputStream();




PipedOutputStream pos = new PipedOutputStream();




pis.connect(pos);




/* Connect the two ends */

Piped I/O example

PipedInputStream pis = new PipedInputStream();


PipedOutputStream pos = new PipedOutputStream();


pos.connect(pis);


Runnable producer = () -> produceData(pos); Runnable consumer = () -> consumeData(pis); new Thread(producer).start();


new Thread(consumer).start();


}




public static void produceData(PipedOutputStream pos) {


try {


for (int i = 1; i <= 50; i++) {


pos.write((byte) i);


pos.flush();


System.out.println("Writing: " + i); Thread.sleep(500);


}


pos.close();


} catch (Exception e) {


e.printStackTrace();


} }




public static void consumeData(PipedInputStream pis) {


try {


int num = -1;


while ((num = pis.read()) != -1) { System.out.println("Reading: " + num); } pis.close();


} catch (Exception e) {


e.printStackTrace();


}

Serializing an object code ex.

File fileObject = new File("person.ser");




try (


ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream( fileObject))) {


oos.writeObject(p1);


oos.writeObject(p2);


oos.writeObject(p3);

implementation of load() and dump() for a JSON serializable object

public JSONObject dump() throws JSONException {


JSONObject result = new JSONObject(); JSONArray a = new JSONArray();


for(T i : items){ a.put(i.dump());


// inside this i.dump(), store "class-name" } result.put("items", a); return result;}public void load(JSONObject obj) throws JSONException {


JSONArray arrayItems = obj.getJSONArray("items");


for (int i = 0; i < arrayItems.length(); i++) { JSONObject item = arrayItems.getJSONObject(i);




String className = item.getString("class-name");




try { Class clazzy = Class.forName(className); T newItem = (T) clazzy.newInstance(); newItem.load(obj); items.add(newItem);




} catch (InstantiationException e) {


// whatever } catch (IllegalAccessException e) {


// whatever } catch (ClassNotFoundException e) {


// whatever }

What interface do you need to implement to Serialize your class in JSON?

interface JSONSerializable{




public JSONObject dump() throws JSONException


//serializes object




public void load(JSONObject obj) throws JSONException


//deserializes object


}

BufferReader code example

BufferedReader br = new BufferedReader(new LowerCaseReader(new FileReader( fileName)));




String str = null;




while ((str = br.readLine()) != null) {




System.out.println(str);




}

Aspect-Oriented Programming

AOP provides the ability to implement crosscutting logic, which applies to many parts of your application, in a single place.

JAXB

JAXB: The newest implementation to read XML documents: Is part of Java 6 in v2.




This allows us to serialize java objects from a document. You read the document with a class that implements an interface to javax.xml.bind.Unmarshaller (you get a class for this from JAXBContext.newInstance).




The context has to be initialized with the used classes, but you just have to specify the root classes and don't have to worry about static referenced classes.




You use annotations to specify which classes should be elements (@XmlRootElement) and which fields are elements(@XmlElement) or attributes (@XmlAttribute, what a surprise!)




RootElementClass adr = new RootElementClass();


FileInputStream adrFile = null;


try {


adrFile = new FileInputStream("test"); JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);


Unmarshaller um = ctx.createUnmarshaller(); adr = (RootElementClass) um.unmarshal(adrFile);


} catch(IOException exc) { } catch(JAXBException exc) { } finally { }Write document: FileOutputStream adrFile = null; try { adrFile = new FileOutputStream("test.xml"); JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class); Marshaller ma = ctx.createMarshaller(); ma.marshal(..); } catch(IOException exc) { } catch(JAXBException exc) { } finally { }

Spring Project with Wired Beans

By using Spring Dependency Injection (DI) we can declare Java Beans in the Spring configuration xml file. Then wire the Java Beans in the xml file. In this way Spring can make our printer loosely coupled to the different Printer implementations.We change the Helper class to accept the Printer.package


com.java2s.output;


import com.java2s.output.Printer;




public class OutputHelper{


Printer outputGenerator;


public void print(){ outputGenerator.print(); } public void setOutputGenerator(Printer outputGenerator){


this.outputGenerator = outputGenerator; }


}




Then we have to create a Spring bean configuration file and declare all your Java object dependencies here.Call it via Springpackage com.java2s.common;


import org.springframework.context.ApplicationContext;


import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.java2s.output.OutputHelper;




public class App {


public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});


OutputHelper output = (OutputHelper)context.getBean("OutputHelper"); output.print(); }


}




To switch Printer, we just need to change the Spring XML file for a different Printer. When Printer changed, we need to modify the Spring XML file only.


Simple Spring code to run basic app context

ApplicationContext context = new ClassPathXmlApplicationContext( "SpringBeans.xml");




OutputHelper output = (OutputHelper)context.getBean("outputHelper");




output.print();




}

Spring property tag shortcut

We can use shortcut property tag to fill value to Java bean properties in the following way.




The property tag can have a value attribute. We put our value there.




"p" schemaWe can even fill the properties when declaring the Java Bean in the bean tag.




In order to use the p schema we have to declare thexmlns:p="http://www.springframework.org/schema/p


Spring import XML file

Spring allows us to organize all Spring bean configuration files into a single XML file.




In order to host all configuration file we created a new Spring-All-Module.xml file, and import the other Spring bean files.




Put this file under project classpath.project-classpath/Spring-All-Module.xml




We can load a single xml file like this :




ApplicationContext context = new ClassPathXmlApplicationContext("Spring-All-Module.xml");


what do you need in an XML config file to scan packages for beans?

how to exclude classes from the scan?

context:exclude-filter

JDBC Example Code

//STEP 1 Import classes


import java.sql.*


//STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver");




//STEP 3: Open a connection System.out.println("Connecting to database...");


conn = DriverManager.getConnection(DB_URL,USER,PASS);




//STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement();


String sql; sql = "SELECT id, first, last, age FROM Employees";


ResultSet rs = stmt.executeQuery(sql);

JUnit Assert examples

//check for equality


assertEquals("Abc", str);




//check for false condition


assertFalse(num > 6);




//check for not null value


assertNotNull(str);

What's the result?

public class Main{




public static void main(String[] argv){ StringBuilder sb = new StringBuilder(); sb.append("AAA").insert(1, "BB").insert(4, "CCCC"); System.out.println(sb);




}}




ABBACCCCA

array to list

List list = Arrays.asList(array);