WGU C193 Client Server Vocab, c193 pt 7, c193 pt 5, c193 pt 9, c193 pt 4, c193 pt 2, C193, c193 pt 3, C193 part 1

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What is contained in a datagram?

A datagram contains a header and payload.

Which transport layer device reviews packets to determine whether they get accepted or denied passage to a private network from the Internet?

A firewall.

What is returned by the getInetAddresses() method?

A java.util.Enumeration containing an InetAddress object for each IP address the interface is bound to

What MIME subtype would be used for audio?

AAC, MP3

202

Accepted

What is the HTTP response code 2xx?

It is used for success codes.

409

Conflict

common fields from the header

Content-type Content-length Content-encoding Date Last-modified Expires

100

Continue

How do you enable CookieManager?

CookieManager manager = new CookieManager(); CookieHandler.setDefault(manager);

What is the name of the pattern that uses Try{ } Catch{ } Finally{ }?

Dispose pattern

417

Expectation Failed

What is the most concrete subclass of the InputStream class?

FileInputStream()

getAllByName()

Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system.

___ tells the server only to return the HTTP header, not to actually send the file. The most common use of this method is to check whether a file has been modified since the last time it was cached

HEAD

When connected to a server, what request will check to see if a web document has been modified since the document was last cached?

HEAD will request to see if a web document has been modified since the document was last cached.

Which type of protocol is closely related to the URLConnection class?

HTTP

407

HTTP_PROXY_AUTH

226

IM Used

Telnet Port Number

Port 23

Which type of device is used to request a service from a server and forward the response back to to original requester, acting as a go-between?

Proxy Server

What receives a request for a remote server from a local client, makes the request to the remote server, and forwards the result back to the local client?

Proxy server

getLocalAddress() and getLocalPort()

The getLocalAddress() and getLocalPort() methods tell you the network interface and port the Socket is connected from.

A resource is a thing that is identified by a ___, which can be a book, a file, a website, a URL, an Internet host, etc.

URL

suspend, stop

___ and ___ are the least desirable ways for a thread to indicate it's ready to pause because they can leave objects in inconsistent states.

HTTP

___ connection types GET PUT POST TRACE HEAD DELETE OPTIONS

ServerSocket

___ constructors ServerSocket(int port)throws BindException IOException ServerSocket(int port, int queuelength, IntAddress bindAddress) throws IOException serverSocket() throws IOException

URL

___ is composed of scheme authority path fragment Identifier query string

2628

dict tcp

Filters cannot be

disconnected from a stream

BufferedInputStream / BufferedOutputStream

does not declare methods of its own

7

echo tcp/udp

filters come in two versions

filter streams, and the readers and writers.

runnable

implement ___ then override run() then adding other methods to have a subclassable runnable.

java.io.outputStream

java's io class is

Given, Thread t = new Thread(); What will start the new thread?

t.start();

Streams are synchronous means...

when a thread asks a stream to read/write, it waits for the data to be read/written before doing anything else.

Interrupted Exception

when interrupt() is invoked, what is thrown that can terminate infinite loops.

Use last filter in the stream

when reading -Overwriting the reference will help with this

openConnection

which method to retrieve data from a URL provides more control over the download process?

Writers

-Mirrors the java.io.OutputStream class -Never used directly; used polymorphically, through one of its subclasses. -Writers can be buffered; either directly or chained to BufferedWriter.

OutputStreamWriter

-Most important concrete subclass of writer. -Converts characters to bytes according to specified encoding. -If no encoding is specified, the default platform encoding is used.

Readers

-Reader class mirrors java.io.InputStream -Never used directly, only through subclasses. -read() method returns a single Unicode character as an int with a value from 0 to 65,656 or -1 on end of stream.

BufferedOutputStream

-Stores written data in a buffer until buffer is full or flushed. -Does not declare any new methods of its own -Write places data in the buffer rather than directly on the underlying output stream

PrintStream assumes

-assumes the default encoding of the platform on which it's running. -Eats all exceptions -Unreliable for network connections

flush()

-breaks deadlocks by forcing the buffered stream to send its data even if the buffer isn't full. -You should do this to all streams before you close them, otherwise data may be lost

isLinkLocalAddress()

-helps IPv6 addresses self-configure -begins with FE80:0000::

isMCNodeLocal()

-is address interface-local multicast -begins with FF01 or FF11

isMCSiteLocal()

-is address site-wide multicast -begins with FF05 or FF15

isMCLinkLocal()

-is address subnet-wide multicast -begins with FF02 or FF12

mark()

-marks the current position in the stream -Only one mark in a stream at a time

isSiteLocalAddress()

-may be forwarded by routers within a site or campus -begins with FEC0:0000:: - begin with FEC0:0000:0000:0000 - returns true if the address is an IPv6 site-local address, false otherwise.

isMCGlobal()

-may have subscribers around the world -begins with FF0E or FF1E

isLoopbackAddress()

-returns true if address is loopback -IPv4: 127.0.0.1 -IPv6: 0:0:0:0:0:0:0:1 (::1)

isAnyLocalAddress()

-returns true if the address is a wildcard address -wildcard address matches any address of the local system -IPv4: 0.0.0.0 -IPv6: 0:0:0:0:0:0:0:0 wildcard address 0.0.0.0 or 0:0:0:0:0:0:0:0 aka ::

InputStreamReader

-the most important concrete subclass or Reader. -Reads bytes from stream and converts into characters according to specified encoding and returns them

InputStreamReader and OutputStreamWriter

-the most important concrete subclasses of Reader and Writer. -Translates to Unicode of specified encoding.

BufferedInputStream

-tries to get requested data from the buffer, and only when the buffer runs out of data does the stream read from the underlying source. -Does not declare any new methods of its own -Overrides methods from InputStream & supports marking and resetting

preempts

while a thread runs, a thread of higher priority unblocks , the thread scheduler __________, or interrupts, the lower-priority thread and assigns the unblocked higher-priority thread to the processor.

What is used to write data to the stream?

write()

What is this code doing? CookieManager manager = new CookieManager(); manager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); CookieHandler.setDefault(manager);

This code tells Java to block third-party cookies, but accepts cookies from the server it's directly talking to.

Which is true about threads versus processes?

Whereas each separate process has its own block of memory, threads are easier on resources because they share memory

public void write(char[] test)

Which class of writers will write characters in an array?

b. t.setPriority(15);

Which line of code will result in an IllegalArgumentException being thrown? a. t.setPriority(1); b. t.setPriority(15); c. t.setPriority(5); d. t.setPriority(10);

main()

Which method is returned when a single thread program exits?

Thread t = new Thread(); t.start ();

Which method should be invoked to start a new thread running in a virtual machine?

public void write(byte[] a)

Which method will allow Java to store IP addresses in an array by using an output stream?

TCP & UDP

Which protocols reside in the transport layer?

Firewall

Which transport layer device reviews packets to determine whether they get accepted or denied passage to a private network from the Internet?

The much better solution to finding out if the digest is null is to have the object just tell us when it's null by sending a ___

callback

Readers and writers

can be chained to input and output streams to allow programs to read and write text rather than bytes.

advantage of breaking data into packets

can be checked for damages in transit using checksums

asterisk " * "

can be used to indicate that all the hosts within a particular domain or subdomain should not be proxied -Dhttp.noProxyHosts=*.oreilly.com

yes

can code that synchronizes on a different object still run in parallel even if it uses a synchronized resource?

methods of the java.util.Date class

can convert a long to a String

monitor

each object in java is associated with it, which a thread can lock or unlock. Only one thread at a time may hold a lock on a ______.

lock field

each writer class has a ___ ___ that specifies the object that writes to the writer synchronize on.

URLEcnoder.encode()

encodes blindly. it does not distinguish between special characters used as part of the URL or query string such as / or =

what does inputStreamReader convert characters based on

encoding scheme

Socket does not override

equals() or hashcode()

What are DataStreams intended for?

exchanging data between two Java programs through network connection, a datafile, a pipe, or some other intermediary

InetSocketAddress.createUnresolved()

factory method used to skip looking up the host in DNS

bufferedReader bufferedWriter lineNumberReader pushbackReader pushbackWriter are examples of ___ ___ ___ ___?

filter readers and writers

filter classes

filter streams read/write classes

raw data

filters work mostly with ____ ____

Filter Class

A class that can be attached to a raw stream like Input or Output Streams to translate raw bytes to and from other formats.

Network

A collection of computers and other devices that can send data to and receive data from one another more or less in real-time.

Cooperative thread scheduler

A cooperative thread scheduler waits for the running thread to pause itself before handing off control of the CPU to a different thread.

What does NetworkInterface class represent?

A local IP address.

getSupportedCipherSuites()

A method in SSLSocketFactory that tells you which combination of algorithms is available on a given socket.

getEnabledCipherSuites()

A method of SSLSocketFactory which tells you which suites this socket is willing to use.

What is a network?

A network is a collection of computers and other devices that are connected to enable users to share hardware, software, and data, as well as to communicate electronically in more or less real time.

A client and a server can coexist in the same machine?

A system can act as Server and Client simultaneously. That is, one process is acting as Server and another is acting as a client. This may also happen that both client and server processes reside on the same machine.

Define the HTTP Response Code: 202

Accepted

When the noargs read( ) is done reading a single byte of data, what does it return?

An int between 0-255

OutputStream.write(int b) takes an int and writes what?

An unsigned byte.

Why would you convert a signed byte to an unsigned byte?

Because a signed byte returns an int between -128 to 127 instead of 0-255

Reading Data from a Server

Construct a URL object. Invoke the URL object's openConnection() method to retrieve a URLConnection object for that URL. Configure the URLConnection. Read the header fields. Get an input stream and read data. Get an output stream and write data. Close the connection.

What is the line of code performing? URL u = new URL(""http://www.abc.com/"");

Constructing a URL object from a string

The ___ interface defines a single call() method that can generically return any type.

Callable

Returning Information from a Thread

Callback is nothing but invoking a method in the main class that started it. It is called callback because the thread calls its creator back when it's done. Instead of directly creating a thread, sometimes ExecutorService is created that creates threads whenever it is needed. Race condition occurs when two or more threads can access shared data and they try to change it at the same time.

Synchronizing a method & performance

Can create a severe performance problem on some virtual machines possibly slowing down a machine by a factor of three. Dramatically increases the chances of a deadlock. Also, its often not the object itself you need to protect from simultaneous modification or access.

What type of data do the write methods in PrintWriter print?

Characters

java.io.Reader

Class specified the API by which characters are read

comparing an URI to anything other than another URI returns a

ClassCastException

4xx

Client Error

What does the 4XX line of HTTP response codes mean?

Client Error 400 - Bad Request 401 - Unauthorized 402 - Payment Required 403 - Forbidden 404 - Not found 405 - Method Not Allowed 406 - Not Acceptable 407 - Proxy Authentication 408 - Request Timeout 409 - Conflict 410 - Gone 411 - Length 412 - precondition failed 413 - Request entity too large 414 - Request URI too long 415 - unsupported media type 416 - Requested range not satisfiable

Define the HTTP Response Code: 4XX series

Client side error

Which model is characterized by storing large quantities of data on an expensive, high-powered server or cloud of servers while most of the program logic and the user interface is handled by client software running on relatively cheap personal computers?

Client/server model

try with resources can be used with any object that implements the___ interface, which includes almost every object you need to dispose

Closeable

Thread safe lists

Collections.synchronizedList()

Thread safe map

Collections.synchronizedMap()

URL does not implement _________

Comparable.

Define the HTTP Response Code: 100

Continue

What is Network Address Translation?

Conceals IP addresses of organization's host computer. Most of the nodes on the network have local, non-routable addresses, that connect the local networks to the ISP.

Internet layer

Defines how bits and bytes are organized into packets, and the addressing scheme by which different machines find each other. IP protocol is the only network protocol that java understands. IPV4, IPV6 send data in packets called datagrams. IPV4 headers are 20 to 60 bytes long. IPV4 payload is 65,515 bytes max. IPV6 header is larger and payload up to 4Gbytes.

Application layer

Delivers data to the user.

Which is true about Asymmetric encryption?

Different keys are used to encrypt and decrypt the data

java.io.FileInputStream and sun.net.TelnetOutputStream

Different stream classes that read and write particular sources of data.

Which statement is true about using instance methods instead of static methods for callbacks?

Each instance of the main class maps to exactly one file and can keep track of information about that file in a natural way without needing extra data structures.

420

Enhance Your Calm (Twitter)

Instead of directly creating a thread, sometimes this is created that creates threads whenever it is needed.

ExecutorService

What is the purpose of Executors?

Executors make it quite easy to set up thread pools you simply submit each task as a Runnable object to the pool. You get back a Future object you can use to check on the progress of the task.

How do you set the size of an Executors' thread pool?

Executors.newFixedThreadPool(#). For example: ExecutorService pool = Executors.newFixedThreadPool(THREAD_COUNT);

Which of the following prefixes is used for searching the group records only and showing all individuals in that group?

Expand or *

424

Failed Dependency

You can construct a URL object from a relative URL string and a base URI object

False, relative URL objects can be constructed from a base URL object and a relative URL string

Which class is the most important concrete subclass of Reader?

FileInputStream

Which subclass of InputStream is used to read data from a file?

FileInputStream

what methods does any subclass of writer need to overwrite

FileWriter

Which stream type is organized in a chain?

Filter

What is unique about the filter stream compared to others?

Filter Streams are usually chained.

Three types of filter class

Filter Streams, Readers, Writers

What can be chained to either an input stream or output stream?

Filter streams

part of a URL is the name of the server that provides the resource you want.

Host

The only thing a Java programmer needs to worry about on this layer is performance. This is where data is converted for transmission over physical media.

Host to network layer

What is the hidden layer?

Host-To-Network (Layer)

Physical address or Ethernet Layer?

Host-to-network (layer)

Which is more stable IP addresses or hostnames?

Hostnames are more stable. IP addresses can change.

Datagram

How IPv4 and IPv6 send packets across the internet layer

When using threads, getting the correct results can depend on which of the following factors:

How many threads the program spawns The speed of the CPU How many CPUs the system uses The algorithm the Java virtual machine uses to allot time to different threads

In which of the following objects is each cookie of the CookieStore encapsulated for providing methods to inspect its attributes?

HttpCookie

418

I'm a teapot (April Fool's joke in 1998)

Streams

I/O in Java is build on these -After one is created, you can usually ignore the details of exactly what it is you are reading or writing

What groups produce most of the standards relevant to network programming and protocols?

IETF and W3C

What is on port 143?

IMAP. It is a protocol used for accessing mailboxes stored on a server.

An if statement checks whether the content type is text or the Content-length field is missing or invalid (contentLength == -1). If either of these is true, the ___ is thrown.

IOException

Which of the following exceptions will be thrown by the reset() method if the markSupported() method returns false?

IOException

RFC 791

IP

Which address is typically assigned to the computer by the organization that is responsible for it?

IP Address

32 Bit IP address

IP V4 (internet layer)

What addressing scheme represents 90% of internet traffic still?

IP V4 (internet layer)

xxx.xxx.xxx.xxx (decimal representation of IP address)

IP V4 (internet layer)

128 bit IP address

IP V6 (internet layer)

FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF (8 quads of Hexidecimal, representing the IP address)

IP V6 (internet layer)

FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:xxx.xxx.xxx.xxx (decimal number in last quad)

IP V6 (internet layer) with IPV4 at end for backward compatibility

hostnames are much more stable than

IP adresses

The class of service is stored in an eight-bit field called ___ in the IP header.

IP_TOS

Java's Socket class, which is used by both clients and servers, has methods for which of the following operations?

Connect to a remote machine. Send data. Receive data. Bind to a port.

Socket sock1 = newSocket(host, 1234, eth0, 0); System.out.println("Connected to " + sock1.getInetAddress() + " on port " + sock1.getPort());

Connected to www.bing.com on port 1234

Observe the given code statement: try { Socket theSocket = newSocket(host, 1234, eth0, 0); System.out.println("Connected to " + theSocket.getInetAddress() + " on port " + theSocket.getPort()); } What will be the output from the code above if the host is www.myCompany.com?

Connected to www.myCompany.com on port 1234

IPV4 vs IPV6

IPv4 is four unsigned bytes each ranging from 0 to 255. IPv6 is eight blocks of four hexadecimal digits. For IPv6, leading zeros don't need to be written.

When is asynchronous IO a better alternative than threads?

If an application needs thousands of simultaneous long-lived connections

When is asynchronous IO a better alternative than threads?

If an application needs thousands of simultaneous long-lived connections.

Multiple synchronizations on the same objects.

If two threads synchronize on the same object and reach their synchronization point near the same time, once one of the two parallel threads gets into its synchronization block, the other must wait.

What is RFC 3501?

Internet Message Access Protocol (IMAP). It is a protocol for remotely accessing a mailbox stored on a server including downloading messages, deleting messages, and moving messages to different folders.

ISP

Internet Service Provider

nodes, hosts

Internet addresses consist of ____ and ____.

500

Internal Server Error

Define the HTTP Response Code: 500

Internal server error

Which layer defines how bits and bytes of data are organized into the larger groups called packets, and the addressing scheme by which different machines find one another?

Internet

Defines how bits and bytes of data are organizes into the larger groups called packets.

Internet (Layer)

IP layer?

Internet (Layer)

Responsible for defining how data is stored in packets.

Internet (Layer)

The addressing scheme by which different machines find one another.

Internet (Layer)

ICANN

Internet Corporation for assigned names and numbers

What is RFC 2821?

It is the simple mail transfer protocol. It is an application layer protocol by which one host transfers email to another host.

What is the HTTP response code 101?

It is the switching protocols. The server accepts the client's request in the Upgrade header field to change the application protocol.

What is the HTTP response code 408?

It is the timed out response code. The client took too long to send the request.

What is RFC 793?

It is the transmission control protocol. It is a reliable, connection-oriented streaming transport layer protocol.

What is the HTTP response code 401?

It is the unauthorized response code. Usually a username or password issue.

What is the Internet?

It is the world's largest IP-based network. It covers many different countries across all seven continents.

What is the purpose of threading?

It is to make use of available resources efficiently.

What is the HTTP response code 4xx?

It is used for client errors.

What is the HTTP response code 1xx?

It is used for informational responses.

What is the HTTP response code 3xx?

It is used for redirection codes.

What is the HTTP response code 5xx?

It is used for server errors.

This next section develops a full-blown HTTP server, called ___, that can serve an entire document tree, including images, applets, HTML files, text files, and more.

JHTTP

full-Fledged HTTP server that serve an entire document tree

JHTTP

Which MIME subtype is appropriate for the image/* MIME type?

JPEG

Which MIME subtype is appropriate for the image/*MIME type?

JPEG is the MIME appropriate subtype

What will allow a programmer to mitigate shoulder surfing for website usernames and passwords?

JPasswordField allows a programmer to mitigate the risk of shoulder surfing.

What is on port 110?

POP3. It is a protocol for the transfer of the accumulated email from the host to sporadically connected clients.

The ___ method is the most general method. It too uploads a representation of a resource to a server at a known URL, but it does not specify what the server is to do with the newly supplied resource.

POST

pages accessed with the ___ method should not be chached

POST

GET vs POST

POST is overused, any safe operation that does not commit the user to anything should use get rather than POST. Only operations that commit the user should use POST.

when requests cannot be completed with GET

POST should be used as it allows for URL lengths of over 2,000 characters

GET should only be used for safe operations; whereas,

POST should be used for unsafe operations

The ___ method uploads a representation of a resource to the server at a known URL.

PUT

Which of the following HTTP methods uploads a representation of a resource to the server at a known URL?

PUT

A chunk of bytes that contain information about who sent it and where it's going.

Packet

What is the advantage of breaking data into packets over a network?

Packets can be checked for damages in transit using checksums.

206

Partial Content

Which connection type can act as both the client and server from the same endpoint?

Peer-to-peer connections can have peers act as both clients and servers.

308

Permanent Redirect

The ___ solution constantly pings the digest to see if it's null ("Are we there yet? Are we there yet? Are we there yet?...")

Polling

___ contains the main() method that reads the file and creates one LookupTask per line.

PooledWeblog

FTP Port Number

Port 21

whois Port Number

Port 43

Echo Port Number

Port 7

Finger Port Number

Port 79

Abstraction in the computer's memory used to allow multiple processes access to the same internet connection.

Ports

If ___ is turned on, the client occasionally sends a data packet over an idle connection (most commonly once every two hours), just to make sure the server hasn't crashed.

SO_KEEPALIVE

The ___ option specifies what to do with datagrams that have not yet been sent when a socket is closed.

SO_LINGER public void setSoLinger(boolean on, int seconds) throws SocketException public int getSoLinger() throws SocketException

The ___ option controls the suggested send buffer size used for network input.

SO_RCVBUF

This option sets the default receives buffer size for client sockets accepted by the server socket.

SO_RCVBUF

If the ___ is turned on (it's turned off by default), another socket is allowed to bind to the port even while data may be outstanding for the previous socket.

SO_REUSEADDR

This option for server sockets determines whether a new socket will be allowed to bind to a previously used port while there mights still be data traversing the network addressed to the old socket.

SO_REUSEADDR

The ___ option controls the suggested send buffer size used for network output.

SO_SNDBUF

the amount of time, in milliseconds, that accept() waits for an incoming connection before throwing a java.io.InterruptedIOException.

SO_TIMEOUT

Normally when you try to read data from a socket, the read( ) call blocks as long as necessary to get enough bytes. By setting ___, you ensure that the call will not block for more than a fixed number of milliseconds

SO_TIMEOUT if (s.getSoTimeout() == 0) s.setSoTimeout(180000);

What protocol is on port 22?

SSH and is used for remote logins.

What are the parts of a URI?

Scheme Scheme-specific Fragment identifier

Authenticator.requestPasswordAuthentication() throws a

SecurityException

303

See Other

Which type of system is more expensive and stores vast quantities of data?

Server

5XX

Server Error

5xx

Server Error

Given, Thread t = new Thread(cb); t.setPriority(8); t.start(); What does the t.setPriority(8); line of code perform?

Sets the priority of each spawned thread to 8

PrintStream

Should be avoided for network applications. println() is platform dependant and dosn't provide a consisten return character for the new line across all platforms which makes the class unusable for rigid network protocol communications. The class also assumes the encoding which may not actually be accurate. It also eats all exceptions.

HTTP servers begins with a server that always sends out the same file, no matter what the request. It's called ___

SingleFileHTTPServer

Which of the following classes hold the content to send, the header to send, and the port to bind?

SingleFileHTTPServer

Why is the read( ) method abstract?

So subclasses can change it to the specific medium that needs to be read in (like ByteArrayInputStream for example)

You can ask for a NetworkInterface by IP address, by name, or by enumeration. Each of these throw the ___ exception.

Socket

Using the accept method, how would you construct a socket?

Socket connection = server.accept();

What is the line after constructing the socket object to instantiate it?

Socket socket = factory.createSocket("host",port);

What is the Socket Constructor?

Socket(host, port, interface, localport)

Which class provides a convenient store for local transient socket connection information?

SocketAddress

Which Java class provides a convenient store for the local transient socket connection information?

SocketAddress provides a convenient store for local transient socket connection information.

What is the construct for the SocketFactory?

SocketFactory factory = SSLSocketFactory.getDefault();

Two processes in client-server model

Sockets Remote Procedure Calls (RPC)

Socket Operations

Sockets can perform seven basic operations: Connect to a remote machine Send data Receive data Close a connection Bind to a port Listen for incoming data Accept connections from remote machines on the bound port

What protocol is on port 20?

The FTP data protocol. This port is able to transfer files.

What protocol is on port 21?

The FTP protocol. This port is used to sent FTP commands like PUT or GET.

What is the world's largest IP-based network?

The Internet

Which layer defines how bits and bytes of data are organized into larger groups called packets, and the addressing scheme by which different machines find one another?

The Internet layer.

What is an internal network not visible from the outside?

The Intranet

JPasswordField class

The JPasswordField class is a lightweight component that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters.

The code 504 along with the message Gateway Timeout is displayed when:

The proxy server did not receive a response from the upstream server within a reasonable amount of time, so it can't send the desired response to the client.

Path

The location of the resource at the resolution of the URI request. (e.g. /music/listen, /watch, /someusername)

What method is returned when a single thread program exits?

The main() method is returned when a single thread exits.

getLocalAddress() and getLocalPort()

The methods tell you the network interface and port the Socket is connected from.

isInputShutdown() and isOutputShutdown()

The methods tell you whether the input and output streams are open or closed, respectively. You can use these (rather than isConnected() and isClosed()) to more specifically ascertain whether you can read from or write to a socket.

Marking support (InputStream method mark())

The only input stream classes in java.io that always support marking are BufferedInputStream and ByteArrayInputStream. However, other input streams such as TelnetInputStream may support marking if they're chained to a buffered input stream first.

Scheme

The protocol in a URI (e.g. http:, mailto:, magnet:, etc.)

Query

The query string to post data to the server (e.g. ?searchterm=somesearchterm, ?vid=somevideoid, ?postid=somepostid)

Which is true about symmetric encryption?

The same key is used to encrypt and decrypt the data

What is this code doing? SocketAddress address = new InetSocketAddress("proxy.example.com", 80); Proxy proxy = new Proxy(Proxy.Type.HTTP, address);

This creates a Proxy object representing an HTTP proxy server on port 80 of proxy.example.com.

Using the URI "abc://admin:[email protected]:1234/path/data ?key=value&key2=value2#fragid1" What method would return the query, and what would it return?

getQuery( ); key=value&key2=value2

Which method will ensure that the character "%" followed by two hexadecimal digits are converted to the correct reserved character?

getRawPath()

What method will ensure that the character '%' followed by two hexadecimal digits are converted to the correct reserved character?

getRawPath() will ensure that the character % followed by two hexadecimal digits are converted to the correct reserved character.

___ returns the socket address of the system being connected to and ___ returns the socket address from which the connection is made.

getRemoteSocketAddress( ) getLocalSocketAddress()

methods inherited from the Authenticator superclass:

getRequestingHost() getRequestingProtocol() getRequestingPort()

Which are methods inherited from the Authenticator superclass?

getRequestingPort() getRequestingProtocol() getRequestingHost()

Using the URI "abc://admin:[email protected]:1234/path/data ?key=value&key2=value2#fragid1" What method would return the scheme, and what would it return?

getScheme( ); abc

Which class returns the value of true if the socket is set to use client mode?

getUseClientMode()

returns the value of true if the socket is set to use client mode

getUseClientMode()

inetAddress.getAllByName

gets all addresses of a host if there is more than one

Each running virtual machine has a single ___ object it uses to locate the proxy server for different connections

java.net.ProxySelector

For servers that accept connections, Java provides a ___ class that represents server sockets

java.net.ServerSocket

Which of the following packages provides classes for parsing and managing certificates?

java.security.cert

Executors class resides in?

java.util.concurrent

Callable import

java.util.concurrent.Callable

logging tool in java

java.util.logging

This package provides classes for networking applications. These classes include factories for creating sockets.

javax.net

relative URLs

not complete URLs, inherit parts from parent URL whereas a complete URL is called absolute

If there is no value specified in the URL path AND IT IS NOT A PORT, all other getter methods will return

null

how do objects register interest in the result of a callback method.

thread or runnable

Runnable state:

thread's default state. After the call to start() completes, a thread becomes runnable whether or not that thread is running

How are filters connected to the stream?

through their constructors

the issue with interrupt() on blocking threads

throwing an interrupt on a blocking thread that is sleeping is not a guarantee to solve a deadlock, infact is could cause more problems as the way this is implemented is platform specific.

NoRouteToHostException

thrown when the connection has timed out

setNeedClientAuth()

throws IllegalArgumentException

37

time tcp/udp

Why would a Java program interact with the Physical layer?

to improve performance

synchronize block

to indicate lines should be executed together, wrap them in a ___ ___.

System-wide

to install a ___-___ cache you need: a concrete subclass of ResponseCache a concrete subclass of CacheReuest a concrete subclass of CacheResponse

private, final

to make an object immutable, just make all it's fields ____ and ____, then don't write any setter methods.

set properties such as http.proxyHost and http.proxyPort

to set domain name / ip address and port number to a proxy server

toString() returns a more human readable version of an URI but for a syntactically correct URI, must use

toASCIIString()

The ___ method converts a URL object to a string that can be used in an HTML link or a web browser's Open URL dialog.

toExternalForm( ) *note: this is the toString( ) equivalent method for URLs

URL has three methods that convert an instance to another form:

toString(), toExternalForm(), and toURI().

Given https://www.company.com/current/sfs/index.html?isbn=44322#toc What is the identifier?

toc

Observe the given URL: https://www.company.com/current/sfs/index.html?isbn=44322#toc Which is the fragment identifier in this URL?

toc

filter streams

transform raw byte data into common formats.

When using instance methods instead of static methods for callbacks, each instance of the main class maps to exactly one file and can keep track of information about that file in a natural way without needing extra data structures. true or false

true

getNeedClientAuth()

true if socket requires authentication from client side, false otherwise

How would you code having to open a socket on port 13 from "time.nist.gov"?

try (Socket socket = new Socket("time.nist.gov", 13)) { // read from the socket... } catch (IOException ex) { System.err.println("Could not connect to time.nist.gov"); }

abort

what does the cache handler call if a problem arises? this method removes any data from the cache that has been stored for the request.

java.io.inputStream

what does the java reader class mirror?

local IP address

what does the networkInterface represent?

loopback address

what does un-trusted code that calls InetAddress.getLocalHost() get?

IOException

what exception is thrown by isReachable() if there is a network error.

IOException

what is UnknownHostException a subclass of?

java.lang.Thread

what is a thread an instance object of?

openStream

what is the most commonly used method to retrieve data from a URL? This method: returns an InputStream

IllegalArgumentException

what is thrown when you exceed the max setPriority()

inetAddress.getByAddress()

what method can create addresses for hosts that do not exist or can't be reached by creating an InetAddress object with an IP address and no hostname

getInetAddress

what method do you use to get a NetworkInterface object's IP address and name?

read, close

what methods does any subclass of inputStream need to overwrite?

write, flush, close

what methods does any subclass of writer need to overwrite

query

what part of the URI http://www.powels.com/cgi-bin/biblio?inkey=62-1634645-0 is ?inkey=62-1634645-0

path

what part of the URI http://www.powels.com/cgi-bin/biblio?inkey=62-1634645-0 is cgi-bin/biblio

scheme

what part of the URI http://www.powels.com/cgi-bin/biblio?inkey=62-1634645-0 is http

authority

what part of the URI http://www.powels.com/cgi-bin/biblio?inkey=62-1634645-0 is www.powels.com

static factory methods

what returns the NetworkInterface object associated with a particular network interface? These can be asked for by IP address, name, and enumeration

checkConnect

what security manager method can test if a host can be rescheduled?

content type, content length

what two fields does a HTTP header include

http, file

what two protocols are the only ones available in all virtual machines?

read only

what type of access do these methods give to parts of a URL? getField() getHost() getPort() getProtocol() getRef() getQuery() getPath() getUserInfo() getAuthority()

low priority

what type of priority do background threads and long tasks get?

instance variables

what type of variables have problems with synchronization?

Streams are synchronous

when a thread asks a stream to read or write a piece of data, it waits for the data to be read or written before it does anything else

A ___ client connects to one of several central servers and requests directory information for a person or persons

whois

43

whois tcp

java.util.Collections

wrap maps and lists use the thread safe version of ___.___.___. (new Collections.synchronized(foo)) This is only thread safe if you do not access the underlying data structure directly.

What is OutputStream's fundamental method?

write

Which Writer method is used to write to a stream?

write

outputStream

write() close() and flush() methods in filters work with

Standard OutputStream Methods

write(), close(), flush(),

OutputStream's fundamental method is

write(int b)

OutputStream's fundamental method

write(int b) -Although this method takes an int as an argument, it actually writes an unsigned byte

outputStream write methods

write(int b) write(byte [] data) write(byte [] data, int offset, int lengths) writes an int 0-255's corresponding byte to the stream

Success This means the action was successfully received, understood, and accepted.

2XX

INFO

3

returns a single value character as an int with a value from 0 to 65545 (or -1)

read()

the basic method of InputStream is the noargs ___ method

read()

InputStream fundamental methods to read data as raw bytes

read() skip() available() close()

basic method to read from InputStream?

read() no args

byte, int

read() reads a _____ and returns an _____

Standard InputStream Methods

read(), close(), available()

InetAddress.getByName()

This method does not merely set a private String field in the InetAddress class. It actually makes a connection to the local DNS server to look up the name and the numeric address You can also do a reverse lookup by IP address. For example, if you want the hostname for the address 208.201.239.100, pass the dotted quad address to InetAddress.getByName(): InetAddress address = InetAddress.getByName("208.201.239.100"); System.out.println(address.getHostName());

notifyAll

This method notifies all threads waiting on an object.

Blocking

This method of indicating a thread is ready to pause can: wait or a non-held resource block while waiting for data to arrive block when entering a synchronized method. wait for a lock to be released will not release any locks held

Yielding

This method of indicating a thread is ready to pause: must be done explicitly make sure that the thread and objects are in a consistent state make sure it's not synchronized does not release locks

getByInetAddress()

This method returns a NetworkInterface object representing the network interface bound to the specified IP address.

getByName()

This method returns a NetworkInterface object representing the network interface with the particular name.

getNetworkInterfaces()

This method returns a java.util.Enumeration listing all the network interfaces on the local host.

getDisplayName()

This method returns a more human-friendly name for the particular NetworkInterface object.

getInetAddresses()

This method returns an Enumeration with all or a subset of the InetAddresses bound to this network interface. A java.util.Enumeration containing an InetAddress object for each IP address the interface is bound to

notify

This method wakes one thread waiting on an object.

What does this code do? int bytesRead = 0; int bytesToRead = 1024; byte[ ] input = new byte[bytesToRead]; while (bytesRead < bytesToRead) { bytesRead += in.read(input, bytesRead, bytesToRead - bytesRead); if (result == -1) break; // end of stream bytesRead += result; }

This places all the bytes in a loop that reads until the array is filled. If there was an interruption, then the return value will be -1, so the break is necessary to prevent an infinite loop.

What does invoking the close( ) method do?

This releases and resources associated with the stream, such as handles or ports.

what is a thread an instance object of?

java.lang.Thread

Java 5 Cookie implementaion

java.net.CookieHandler defines an API for storing and retrieving cookies. This API does not include implementation of the abstract class so there is alot of writing work to do if you want to use it.

Before Java will store and return cookies, you need to enable the ___ class and ___ subclass.

java.net.CookieManager CookieHandler Code: CookieManager manager = new CookieManager(); CookieHandler.setDefault(manager);

Java 6 Cookie implementation

java.net.CookieManager is a subclass of CookieHandler that was added in Java 6. It is not turned on by default but is at least built out and not just an abstract.

The ___ class is Java's high-level representation of an IP address, both IPv4 and IPv6.

java.net.InetAddress

What is Java's high level representation of an IP address?

java.net.InetAddress

Which class is Java's high-level representation of an IP address?

java.net.InetAddress

hostname

java.net.InetAddress converts an IP address to a ___

URL

what does static classLoader.getSystemResource(String name) return?

performance penalty

what does synchronize carry in quite a few VMs?

I/O in Java is built on

Streams

What is IO in Java built upon?

Streams

What IS a good solution to a race condition?

Synchronization

In Java 6 and earlier, what is the best way to close the stream?

The best way to close a stream in Java 6 and earlier is the finally block.

From the socket server how do you determine if you need authentication on the first handshake?

setUseClientMode();

What port(s) is Telnet?

23

Which is the default port for telnet?

23

Telnet

23 TCP Used for interactive, remote command-line sessions.

Smtp

25 TCP The Simple Mail Transfer Protocol is used to send email between machines.

Dict

2628 TCP A UTF-8 encoded dictionary service that provides definitions of words.

Configure the URLConnection

3

Node

A single device on a network - Any machine on a network.

A starvation problem

A starvation problem can be hard to spot if you're developing on a VM that uses preemptive thread scheduling. Just because the problem doesn't arise on your machine doesn't mean it won't arise on your customers' machines if their VMs use cooperative thread scheduling. Most current virtual machines use preemptive thread scheduling, but some older virtual machines are cooperatively scheduled, and you may also encounter cooperative scheduling in special-purpose Java virtual machines such as for embedded environments.

1XX

Informational

1xx

Informational

Define the HTTP Response Code: 1XX Series

Informational

What reads data in Java?

InputStream

Most important Reader subclass

InputStreamReader

What are the most important concrete subclasses for the Read and Writer

InputStreamReader and OutputStreamWriter

most important concrete subclasses of Reader and Writer are the

InputStreamReader and OutputStreamWriter

The most important concrete sub classes of Reader and Writer are?

InputStreamReader and the OutputStreamWriter classes. An InputStreamReader contains an underlying input stream from which it reads raw bytes. It translates these bytes into Unicode characters according to a specified encoding. An OutputStreamWriter receives Unicode characters from a running program. It then translates those characters into bytes using a specified encoding and writes the bytes onto an underlying output stream.

When should a thread not sleep?

Inside a synchronized method or block.

if the proxy requires a user name and password

Install an Authenticator

Which of the following is an important step in writing to a file?

Instantiate OutputStream's child class FileOutputStream

507

Insufficient Storage

How does a Proxy Server help improve load times?

Local Caching - Stores files (temporarily) that are from commonly accessed sites in effort to reduce load on internet connection and improve load times.

Synchronization Alternatives

Local variables are created with each instantiation of a class or method so they are a good way to ensure that resources aren't being shared. Method types of primitives are also safe from modification because java passes arguments by value and not reference.

Sleeping threads keep all the ___ they took from the CPU, which can be an issue.

Locks

___ is a Callable that parses a logfile entry, looks up a single address, and replaces that address with the corresponding hostname.

LookupTask

TCP Traffic Classes

Low Cost, High Reliability, Maximum Throughput, Minimum Delay

getContentType() returns

MIME type null if not available text/html is the most common

All these constructors throw a ___ if you try to create a URL for an unsupported protocol or if the URL is syntactically incorrect.

MalformedURLException

URL

Methods to retrieve data from ___: inputStream openStream() URLConnection openConnection() URLConnection openConnection(proxy proxy) Object getContent() Object getContent(Class [] classes)

Who creates most of the protocols?

Most are created by the Internet Engineering Task Force (IETF) and the World Wide Web Consortium (W3C).

301

Moved Permanently

Define the HTTP Response Code: 301

Moved Permanently

302

Moved Temporarily

300

Multiple choices

What is on port 119?

NNTP is on port 119. Usenet news transfers aka "Network News Transfer Protocol".

How the local address seen and routed from outside the network?

Network Address Translation

511

Network Authentication Required

A programmer wants to use a factory method to return a NetworkInterface object and then use a getter method to return all the IP addresses of that object. Which code should be used?

NetworkInterface foo = NetworkInterface.getByName("eth1"); Enumeration fooAddresses = foo.getInetAddresses();

204

No Content

Does the Java core networking API support explicit peer-to-peer communications?

No, it does not support explicit peer-to-peer communications.

Is it secure to create an InetAddress object from a hostname?

No, it is considered insecure to create an InetAddress object from a hostname because it requires a DNS lookup which could potentially be spoofed.

Which term refers to each device connected to a network?

Node

203

Non-Authoritative Information

COPY & MOVE

Non-standard methods that Java will not send.

Proxy servers

Normally operate at the application layer.

Firewalls

Normally operate at transport or internet layers.

501

Not Implemented

304

Not Modified

Thread Priorities

Not all operating systems support 11 different priorities. For instance, Windows only has 7. On Windows, priorities 1 and 2, 3 and 4, 6 and 7, and 8 and 9 are treated equally (e.g., a priority 9 thread will not necessarily preempt a priority 8 thread).

Thread priority quirk

Not all operating systems support 11 different priorities. For instance, Windows only has 7. On Windows, priorities 1 and 2, 3 and 4, 6 and 7, and 8 and 9 are treated equally (e.g., a priority 9 thread will not necessarily preempt a priority 8 thread).

Define the HTTP Response Code: 404

Not found

StringBuilder

Not immutable, can be changed after they are created.

200

OK

Once ___ is turned on, any urgent data that arrives will be placed on the socket's input stream to be read in the usual way.

OOBINLINE

Which option is set to true for receiving urgent data inline with regular data from the socket?

OOBINLINE

The ___ request method asks what options are supported for a particular URL. If the request URL is an asterisk (*), the request applies to the server as a whole rather than to one particular URL on the server.

OPTIONS

A specific routing protocol quickly identifies changes within the network to find the fastest route and distributes this information to all routers on the segment. Which routing protocol is being described?

OSPF

Acts as a go between with the outside world and the firewall and PC.

Proxy

Which device will allow a company to hide internal IPs before they leave the network boundary?

Proxy

bypass all proxy servers

Proxy.NO_PROXY

Which are types of proxies?

Proxy.Type.DIRECT Proxy.Type.SOCKS Proxy.Type.HTTP

types of proxy java undestands

Proxy.Type.SOCKS Proxy.Type.HTTP Proxy.Type.DIRECT

each virtual machine has exactly one ___ To change the ___, pass the new selector to the static ___.setDefault() method.

ProxySelector

Using Threads

Q: When using threads, getting the correct results can depend on which of the following factors: How many CPUs the system uses The speed of the CPU How many threads the program spawns The algorithm the Java virtual machine uses to allot time to different threads

Internet Standards

RFC 1112 The internet layer methods by which conforming systems can direct a single packet of data to multiple hosts. This is called multicasting. Java's support for multicasting is discussed in Chapter 13. RFC 868 An application layer protocol that sends the time in seconds since midnight, January 1, 1900, to a client connecting over TCP or UDP. The time is sent as a machine-readable, 32-bit unsigned integer. The standard is incomplete in that it does not specify how the integer is encoded in 32 bits, but in practice a big-endian integer is used. RFC 864 An application layer protocol that sends an indefinite sequence of ASCII characters to any client that connects over either TCP or UDP; also useful as a debugging tool. RFC 867 An application layer protocol that sends a human-readable ASCII string indicating the current date and time at the server to any client that connects over TCP or UDP. This contrasts with the various NTP and Time Server protocols, which do not return data that can be easily read by humans. RFC 5000 Describes the standardization process and the current status of the different Internet protocols. Periodically updated in new RFCs.

What is the RFC for URI data?

RFC 2397

What is the RFC for HTTP?

RFC 2616 (1.1) or RFC 1945 (1.0)

What is the RFC code for URI syntax?

RFC 3986

What describes the standardization process and the current status of different Internet protocols?

RFC 5000

What is the RFC code for the official internet standards?

RFC 5000

What is the official Internet Protocol Standards?

RFC 5000

What is the RFC code for echo?

RFC 862

IETF standards are published as what?

RFC(s)

RIP

RIP prevents routing loops by implementing a limit on the number of hops allowed in a path from source to destination. The maximum number of hops allowed for RIP is 15, which limits the size of networks that RIP can support.

when two or more threads can access shared data and they try to change it at the same time

Race condition

InputStream & OutputStream

Read and write bytes singly.

What does the Java.io.InputStream mirror?

Reader class

What is never used directly but only through subclasses?

Reader class

What is this code doing? public static String getMacCyrillicString(InputStream in) throws IOException { InputStreamReader r = new InputStreamReader(in, "MacCyrillic"); StringBuilder sb = new StringBuilder(); int c; while ((c = r.read()) != -1) sb.append((char) c); return sb.toString(); }

Reading an input stream and converting it all to one Unicode string.

OutputStreamWriter

Receives characters from a Java program and converts these into bytes according to a specified encoding and writes them onto an underlying output stream.

3xx

Redirection

What does the 3XX line of HTTP response codes mean?

Redirection 300 - Multiple Choice 301 - Moved Permanently 302 - Moved Temporarily 303 - See Other 304 - Not Modified 305 - Use Proxy 307 - Temporary Redirect 308 - Permanent Redirect

Define the HTTP Response Code: 3XX series

Redirection and Relocation

3XX

Relocation & Redirection

logging levels

SEVERE (highest value) WARNING INFO CONFIG FINE FINER FINEST (lowest value) In addition there is a level OFF that can be used to turn off logging

Which of the following protocols is used to transfer email between servers or between a mail client and a server?

SMTP

What signifies the end of the stream?

Returning -1

SSLSocketFactory.getDefault()

Returns an instance of the SSL Socket Factory which is the encrypted version of a Socket. You would then use the .createSocket("", #) method to return an actual usable socket.

What protocol is on port 25?

SMTP is on port 25. It is used to send email between machines.

In the PasswordAuthentication class the username and password are defined as

String userName, char[] password

Unlike Strings ___ arguments are not safe because they're not immutable.

StringBuilder

TelnetOutputStream

Subclass of OutputStream is used to write data onto a network connection

TelnetOutputStream

Subclass of OutputStream is used to write data onto a network connection - uses these methods to write data onto a network connection

2xx

Success

Define the HTTP Response Code: 2XX Series

Success

What does the 2XX line of HTTP response codes mean?

Successful 200 - OK 201 - CREATED 202 - Accepted 203 - Non-Authoritative information 204 - No content 205 - Reset Content 226 - IM used

101

Switching Protocols

"Once one thread starts printing out the values, all other threads will have to stop and wait for it to finish before they can print out their values." What is this describing?

Synchronization

Which is true about synchronization?

Synchronization can lead to deadlocks

When should synchronization be considered?

Synchronization should be considered any time multiple threads share resources.

Which is more reliable UDP or TCP?

TCP

Internet Message Access Protocol (IMAP) (RFC 3501)

TCP 143

Border Gateway Protocol (BGP)

TCP 179

Secure Shell (SSH) (RFC 4250-4256)

TCP 22

Telnet (RFC 854)

TCP 23

Hypertext Transfer Protocol over SSL/TLS (HTTPS)

TCP 443

Java supported protocols

TCP and UDP only.

Which of the following is set to true for ensuring that packets are sent as quickly as possible regardless of their size?

TCP_NODELAY

Setting ___ to true ensures that packets are sent as quickly as possible regardless of their size.

TCP_NODELAY public void setTcpNoDelay(boolean on) throws SocketException public boolean getTcpNoDelay() throws SocketException

The ___ request method sends the HTTP header that the server received from the client.

TRACE

Which request method in setRequestMethod(string method) sends the HTTP header that the server received from the client?

TRACE.

BufferedReader

Take text from the buffer rather than directly from the underlying input stream or other text source

What protocol is on port 23?

Telnet. It is used for interactive remote command line sessions. Isn't secure.

Which subclass of OutputStream is used to write data onto a network connection?

TelnetOutputStream

307

Temporary Redirect

What is returned if the address you used .getByName("args"); on does not have a hostname?

The "args" you supplied will be returned so for example if you passed 72.30.16.42 in, that would be returned back if that address had no hostname.

what does the / at the beginning of a relative URL specify?

The / specifies relative to the document root not the current directory.

java.io.Reader specifies?

The API by which characters are read. Wherever input and output streams use bytes, readers and writers use Unicode characters.

java.io.Writer specifies?

The API by which characters are written. Wherever input and output streams use bytes, readers and writers use Unicode characters.

Which model stores large quantities of data on high powered comptuers and puts most of the program logic on cheap computers?

The Client/Server Model

isClosed() vs isBound() vs isConnected()

The isClosed() method returns true if the socket is closed, false if it isn't. However, this is not a perfect test. If the socket has never been connected in the first place, isClosed() returns false, even though the socket isn't exactly open. isBound() method tells you whether the socket successfully bound to the outgoing port on the local system. isConnected() refers to the remote end of the socket, isBound() refers to the local end. isConnected() tells you whether the socket has ever been connected to a remote host.

isInputShutdown() and isOutputShutdown()

The isInputShutdown() and isOutputShutdown() methods tell you whether the input and output streams are open or closed, respectively. You can use these (rather than isConnected() and isClosed()) to more specifically ascertain whether you can read from or write to a socket.

Authenticator class

The java.net package includes an Authenticator class you can use to provide a username and password for sites that protect themselves using HTTP authentication.

flush() method

breaks the deadlock by forcing the buffered stream to send its data even if the buffer isn't yet full

if more than one object wants the result of a calculation, the thread can keep a list of objects to ___ ___.

call back

one

each instance of a main class maps to only ___ file and can keep track of information about that particular file without needing an additional data structure. This makes it thread safe.

Unable to see from outside the network?

non-routable addresses 10.x.x.x; 172.16.x.x <-> 172.31.x.x; 192.168.x.x;

Which is used to determine if the input stream is open?

public boolean isInputShutdown()

Which is used to determine if the URI is hierarchical or non-hierarchical?

public boolean isOpaque()

The URL class also has a _______ method that checks whether two URLs point to the same resource

sameFile()

URI syntax

scheme : scheme-specific-part : fragment

CONFIG

4

4 layer TCP/IP network model

Application Transport Internet Host to Network

4XX

Client Error

TRACE

Echos back the client request for debugging purposes.

What describes the role of a client?

Initiate communication

What is the HTTP response code 200?

It is an OK code.

412

Precondition Failed

Input Streams

Read data

429

Too Many Requests

305

Use Proxy

Output streams

Write data

Can synchronization lead to deadlocks?

Yes

\r\n

a network server uses this to terminate a line

if the DNS cant find the address

an UnknownHostException is thrown (subclass of IOException)

79

finger tcp

disconnect

public abstract void ___() closes any open streams

URI Syntax

scheme:scheme-specific-part

25

smtp tcp

Encodes the string itself in a variant of the UTF-8 encoding of Unicode.

writeUTF()

what method includes the length of the string

writeUTF()

Given https://www.company.com/current/sfs/index.html?isbn=44322#toc What is the hostname?

www.company.com

What represents 0x in UTF-8?

%

to connect a server to a different port... telnet uses port 23 by default

$ telnet localhost 25

Which type of system is relatively cheaper, and only stores the content it needs at the time?

(the) Client

server lifecycle

* a new serversocket is created *the ServerSocket listens for incoming connection using the accept() method *GetInputStrean and/or GetOutputStream are called accordingly *server and client interact according to agreed-upon protocol until time to close the connection *server, client or both close the connection * server returns to step 2

the URI class

*** an URI object can represent a relative URI *** is purely about identification of resources *** is more conformant to the relevant specifications

How do you look up the address of a specific website?

*Note: This method does not merely set a private String field in the InetAddress class. It actually makes a connection to the local DNS server to look up the name and the numeric address.

URL components

*scheme a.k.a. protocol *authority *path *fragment identifier a.k.a. ref *query string

Advantages of Packets

- Checksums allow check for data corruption

What are the differences between URL and URLConnection?

- URLConnection provides access to the HTTP header. - URLConnection can configure the request parameters sent to the server. - URLConnection can write data to the server as well as read data from the server.

relative URL

- URLs that aren't complete but inherit pieces from their parent - any pieces that are missing are assumed to be the same as the corresponding pieces from the URL of the document in which the URL is found - example, suppose that while browsing http://www.ibiblio.org/javafaq/javatutorial. html you click on this hyperlink: <a href="javafaq.html">

public URLConnection openConnection() throws IOException

- You should use this method when you want to communicate directly with the server. - The openConnection() method opens a socket to the specified URL and returns a URLConnection object. A URLConnection represents an open connection to a network resource. If the call fails, openConnection() throws an IOException. For example: try { URL u = new URL("https://news.ycombinator.com/"); try { URLConnection uc = u.openConnection(); InputStream in = uc.getInputStream(); // read from the connection... } catch (IOException ex) { System.err.println(ex); } } catch (MalformedURLException ex) { System.err.println(ex); }

URL u1 = new URL("http://www.ncsa.uiuc.edu/HTMLPrimer.html#GS"); URL u2 = new URL("http://www.ncsa.uiuc.edu/HTMLPrimer.html#HD"); if (u1.sameFile(u2)) { System.out.println(u1 + " is the same file as \n" + u2); } else { System.out.println(u1 + " is not the same file as \n" + u2); }

- a fragment of code that uses sameFile() to compare two URLs - The output is: http://www.ncsa.uiuc.edu/HTMLPrimer.html#GS is the same file as http://www.ncsa.uiuc.edu/HTMLPrimer.html#HD

The HandshakeCompletedEvent class provides four methods for getting information about the event:

- public SSLSession getSession( ) - public String getCipherSuite( ) - public X509Certificate[ ] getPeerCertificateChain( ) throws SSLPeerUnverifiedException - public SSLSocket getSocket( )

If there is no Content-length header, getContentLength() returns a value of:

-1

If there is no port specified in the URL path, getPort( ) will return a value of

-1

What will be returned by the getContentLength() method if there is no content-length header?

-1

getContentLength() returns ___ if there is no content-length heather

-1

the read() method returns what at the end of the stream?

-1

isMulticastAddress()

-IPv6: starts with FF -IPv4: 224.0.0.0 -> 239.255.255.255

cookiePolicy

.ACCEPT_ALL .ACCEPT_NONE .ACCEPT_ORIGINAL_SERVER

By passing ___ for the local port number, I say that I don't care which port is used but I do want to use the network interface bound to the local hostname I specified.

0

The ideal number of entries in an error log is

0

Construct a URL object

1

SEVERE

1

What number is assigned to MIN_PRIORITY?

1

URL Connection sequence

1 Construct a URL object 2 Invoke the URL;s object openConnection() method to retreive a URLConnection object for that URL. 3 Configure the connection 4 Read the header fields 5 Get an input stream and read data 6 Get an output stream and write data 7 Close the connection

minimum steps needed to retrieve data from an URL

1 Construct an URL object 2 Invoke the URL;s object openConnection() method to retreive a URLConnection object for that URL. 3 Invoke the URLConnection;s getInputStrem() method 4 Read from the input stream using the usual stream API

What port numbers are for well known services?

1 to 1023

What are the steps for utilizing a URLConnection?

1) Construct a URL object. 2) Invoke the URL object's openConnection() method to retrieve a URLConnection object for that URL. 3) Configure the URLConnection. 4) Read the header fields. 5) Get an input stream and read data. 6) Get an output stream and write data. 7) Close the connection.

What are the steps to retrieve data from a URL using a URLConnection?

1) Construct a URL object. 2) Invoke the URL object's openConnection() method to retrieve a URLConnection object for that URL. 3) Invoke the URLConnection's getInputStream() method. 4) Read from the input stream using the usual stream API.

server object lifecycle

1) a new serverSocket is created on a port using the ServerSocket() constructor 2) Server socket listens for incoming connection attempts with accept() accept returns a server object that connects the client to the server 3)depending on the type of server, one two or both methods are called getInputStream() getOutputStream() 4)server and client interact according to agreed upon protocol until connection is called to close 5)server, client, or both close the connection 6)server sleeps to wait for the new client connection

deadlock problems

1)two threads need exclusive access to the same set of resources. Each thread holds the lock of a different subset of those resources.

1. What are the 4 Timeout methods? 2. What is the exception thrown for these methods?

1. public void setConnectTimeout(int timeout) public int getConnectTimeout( ) public void setReadTimeout(int timeout) public int getReadTimeout( ) 2. SocketTimeoutException

What are the 4 steps needed to retrieve data from a URL using a URLConnection object?

1. Construct a URL object. 2. Invoke the URL object's openConnection() method to retrieve a URLConnection object for that URL. 3. Invoke the URLConnection's getInputStream() method. 4. Read from the input stream using the usual stream API.

What are the 7 steps to constructing a URLConnection?

1. Construct a URL object. 2. Invoke the URL object's openConnection() method to retrieve a URLConnection object for that URL. 3. Configure the URLConnection. 4. Read the header fields. 5. Get an input stream and read data. 6. Get an output stream and write data. 7. Close the connection.

steps in a HTTP Connection

1. the client opens a TCP connection to the server (port80 by default) 2. the client sends a message to the server requesting a resource at the specified path 3. The server send a response to the client 4. The server closes the connection

What number is assigned to MAX_PRIORITY?

10

pause

10 ways a thread can ___ or indicate that it is ready to ___: block on I/O yield wait on an object finish suspend block on a synchronized object sleep join another thread be preempted by a higher priority thread stop

What are the non-routable IP Addresses?

10.x.x.x; 172.16.x.x to 172.31.x.x; 192.168.x.x; Local host - 127.0.0.1

Internet Codes

100 continue 200 ok 300 multiple classes 403 forbidden 404 not found 501 not implemented

POP3

110 TCP Post Office Protocol version 3 is a protocol for the transfer of accumulated email from the host to sporadically connected clients.

NNTP

119 TCP Usenet news transfer; more formally known as the "Network News Transfer Protocol."

A daytime server listens on port __

13

Daytime

13 TCP/UDP Provides an ASCII representation of the current time on the server.

IMAP

143 TCP Internet Message Access Protocol is a protocol for accessing mailboxes stored on a server.

how many parameters does the base write method of java.io.outputStream take?

3 (char[] text, int offset, int length)

Infomational This means request received and continuing process.

1XX

HTTP response codes

1XX Infomational This means request received and continuing process. 2XX Success This means the action was successfully received, understood, and accepted. 3XX Redirection This means further action must be taken in order to complete the request. 4XX Client Error This means the request contains bad syntax or cannot be fulfilled. 401 Unauthorized If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. 403 - Forbidden The server understood the request, but is refusing to fulfill it. 5XX Server Error The server failed to fulfill an apparently valid request.

Invoke the URL object's openConnection() method to retrieve a URLConnection object for that URL

2

WARNING

2

how many protected constructors does java.io.outputStream have?

2

For BufferedInputStream/BufferedOutputStream the buffer size is set to __ bytes for an input stream and bytes for an __output stream

2,048, 512

FTP data

20 TCP FTP uses two well-known ports. This port is used to transfer files.

What port(s) is FTP?

20,21

Which address is an IPv4?

209.117.62.36:8080

Which port does FTP use by default?

21

FTP

21 TCP This port is used to send FTP commands like put and get.

What port(s) is SSH?

22

SSH

22 TCP Used for encrypted, remote logins.

Time

37 TCP/UDP A ______ server returns the number of seconds that have elapsed on the server since midnight, January 1, 1900, as a four-byte, unsigned, big-endian integer.

Redirection This means further action must be taken in order to complete the request.

3XX

Read the header fields

4

Which code and message will be displayed when the server understood the request, but is deliberately refusing to process it?

403 Forbidden

Whois

43 TCP A simple directory service for Internet network administrators.

Given https://www.company.com/current/sfs/index.html?isbn=44322#toc What is the port number?

443. HTTPS runs on 443 by default.

Client Error This means the request contains bad syntax or cannot be fulfilled.

4XX

FINE

5

Get an input stream and read data

5

What number is assigned to NORM_PRIORITY?

5

The operating system stores incoming connection requests addressed to a particular port in a first-in, first-out queue. By default, Java sets the length of this queue to __

50

What is the maximum queue length for incoming connection requests?

50

java allows up to ____ connections

50

Which of the following response code refers to the error produced by the server when it failed to fulfill an apparently valid request?

5XX

FINER

6

Get an output stream and read data

6

How many total ports exist?

65535

Close the connection

7

Echo

7

FINEST

7

Finger

79 TCP A service that returns information about a user or users on the local system.

IPv6

8 blocks of 4 hex digits separated by colons

Which TCP port does the HTTP protocol use by default?

80

HTTP

80 TCP The underlying protocol of the World Wide Web.

BufferedReader and BufferedWriter default buffer size

8192 Characters

Discard

9 TCP/UDP a less useful test protocol in which all data received by the server is ignored.

PrintStream has

9 overload print() methods and 10 overload println() methods

Java use

90% Application layer 10% Transport layer

How much of your coding time will be spent in the Application layer?

90% of your coding in Java Network code is spent in the Application layer

Difference between URI and URL

A URI (Uniform Resource Identifier) is a string that identifies a resource. A URL (Uniform Resource Locator) gives a location to a resource and may or may not identify it.

The URI Class

A URI is a generalization of a URL that includes not only Uniform Resource Locators but also Uniform Resource Names (URNs). Most URIs used in practice are URLs, but most specifications and standards such as XML are defined in terms of URIs. In Java, URIs are represented by the java.net.URI class.

What is the biggest difference between a URI and a URL?

A URI tells you *what* the resource is, a URL tells you what the resource is AND GIVES YOU A PATH TO GET IT. It's the difference between the title "Harry Potter and The Deathly Hallows" and "Harry Potter and The Deathly Hallows at the Chicago Public Library on 35th and Halsted; located in room 312, Row 28, Shelf 7".

What is a URL?

A URL is a URI that, as well as identifying a resource, provides a specific network location for the resource that a client can use to retrieve a representation of that resource.

public final Object getContent(Class[] classes) throws IOException

A URL's content handler may provide different views of a resource. This overloaded variant of the getContent() method lets you choose which class you'd like the content to be returned as. The method attempts to return the URL's content in the first available format.

URI vs URL

A Uniform Resource Identifier (URI) is a string of characters in a particular syntax that identifies a resource. scheme:scheme-specific-part A URL is a URI that, as well as identifying a resource, provides a specific network location for the resource that a client can use to retrieve a representation of that resource. protocol://userInfo@host:port/path?query#fragment

urn

A Uniform Resource Name

Server Program Life Cycle

A new ServerSocket is created on a particular port using a ServerSocket() constructor. The ServerSocket listens for incoming connection attempts on that port using its accept() method. accept() blocks until a client attempts to make a connection, at which point accept() returns a Socket object connecting the client and the server. Depending on the type of server, either the Socket's getInputStream() method, getOutputStream() method, or both are called to get input and output streams that communicate with the client. The server and the client interact according to an agreed-upon protocol until it is time to close the connection. The server, the client, or both close the connection. The server returns to step 2 and waits for the next connection.

Which is true about the assumption of cached pages?

A page accessed with GET over HTTP can and should be cached, and a page accessed with HTTPS or POST usually shouldn't be cached

What is an anonymous port?

A port chosen by the system at runtime

Preemptive thread scheduler

A preemptive thread scheduler determines when a thread has had its fair share of CPU time, pauses that thread, and then hands off control of the CPU to a different thread.

preemptive vs cooperative scheduling

A preemptive thread scheduler determines when a thread has had its fair share of CPU time, pauses that thread, and then hands off control of the CPU to a different thread. A cooperative thread scheduler waits for the running thread to pause itself before handing off control of the CPU to a different thread. A virtual machine that uses cooperative thread scheduling is much more susceptible to thread starvation than a virtual machine that uses preemptive thread scheduling, because one high-priority, uncooperative thread can hog an entire CPU.

Process vs Thread

A process is an executing instance of an application. When you double-click the Microsoft Word icon, you start a process that runs Word. A thread is a path of execution within a process. Also, a process can contain multiple threads. When you start Word, the operating system creates a process and begins executing the primary thread of that process.

Initial state:

A program has created a thread's thread object, but the thread does not yet exist because the thread object's start() method has not yet been called

What device allows a company to hide internal IPs before they leave the network boundary?

A proxy lets a company hide internal IPs before they leave the network.

What is a thread?

A separate, independent path of execution in the virtual machine

Address

A sequence of bytes that uniquely identifies a node on the network.

What is the difference between big 'T' and little 't'?

A thread with a little t is a separate, independent path of execution in the virtual machine. A Thread with a capital T is an instance of the java.lang.Thread class.

javax.net.*

A user logs into the e-mail client via the web GUI using the username and password. The user wants to ensure that credentials are not easily obtainable by sniffing network traffic.

Synchronization

A way to assign exclusive access to a shared resource to a single thread for a specific series of statements.

The part of the URL that precedes the query string is given by the value of which attribute of the FORM element?

ACTION

The part of the URL that precedes the query string is given the value of which attribute of the FORM element?

ACTION is the FORM element that gives the value of the part of the URL that precedes the query string.

The InputStreamReader and OutputStreamWriter classes:

Act as decorators on top of input and output streams that change the interface from a byte-oriented interface to a character-oriented interface. Once this is done, additional character-oriented filters can be layered on top of the reader or writer using the java.io.FilterReader and java.io.FilterWriter classes.

HEAD

Acts like a GET except it only returns the header for the resource.

What type of thread scheduling does java use?

All Java virtual machines are guaranteed to use preemptive thread scheduling between priorities. That is, if a lower-priority thread is running when a higher-priority thread becomes ready to run, the virtual machine will sooner or later (and probably sooner) pause the lower-priority thread to allow the higher-priority thread to run. The higher-priority thread preempts the lower-priority thread.

Preemption

All Java virtual machines are guaranteed to use preemptive thread scheduling between priorities. That is, if a lower-priority thread is running when a higher-priority thread becomes ready to run, the virtual machine will sooner or later (and probably sooner) pause the lower-priority thread to allow the higher-priority thread to run. The higher-priority thread preempts the lower-priority thread. There are 10 ways a thread can pause in favor of other threads or indicate that it is ready to pause. These are: It can block on I/O. It can block on a synchronized object. It can yield. It can go to sleep. It can join another thread. It can wait on an object. It can finish. It can be preempted by a higher-priority thread. It can be suspended. It can stop.

DataOutputStream offers 11 methods

All data is written in big-endian format (binary)

ARIN

American Registry for Internet Numbers

What is URLConnection?

An abstract class that represents an active connection to a resource specified by a URL. The provides more control over the interaction with a server (especially an HTTP server) than the URL class. Second, the class is part of Java's protocol handler mechanism, which also includes the URLStreamHandler class. The idea behind protocol handlers is simple: they separate the details of processing a protocol from processing particular data types, providing user interfaces, and doing the other work that a monolithic web browser performs.

The flow of data through a chain of filters

Application Text InputStreamReader (buffered data) GzipInputStream (buffered, compressed data) CipherInputStream (buffered, compressed, encrypted data) BufferedInputStream (raw compressed, encrypted data) TelnetInputStream (raw compressed, encrypted data) Network

What layer delivers data to the user?

Application (Layer)

Layer closest to user?

Application (layer)

What layer decides what to do with the data?

Application (layer)

Layers of a Network

Application Layer - defines how a particular network interface-such as an Ethernet card or a WiFi antenna-sends IP datagrams over its physical connection to the local network and the world. Transport Layer (TCP, UDP) - defines how a particular network interface-such as an Ethernet card or a WiFi antenna-sends IP datagrams over its physical connection to the local network and the world. Internet Layer (IP) - defines how a particular network interface-such as an Ethernet card or a WiFi antenna-sends IP datagrams over its physical connection to the local network and the world. Host-To-Network (Ethernet, Wifi, LTE) - defines how a particular network interface-such as an Ethernet card or a WiFi antenna-sends IP datagrams over its physical connection to the local network and the world.

BufferedReader and BufferedWriter

Are the character-based equivalents of the byte-oriented BufferedInputStream and BufferedOutputStream classes. Where BufferedInputStream and BufferedOutputStream use an internal array of bytes as a buffer, BufferedReader and BufferedWriter use an internal array of chars.

Which class is not a subclass of Writer? ArrayWriter / FileWriter / OutputStreamWriter / BufferedWriter

ArrayWriter

How much data is transferred from server to client after the initial request?

Aside from the initial request for a page, almost all data is transferred from the server to the client

What does ARIN do?

Assigns ISP addresses

What does ICANN do?

Assigns Internet registries (ARIN) addresses

Which of the following logs contains one entry for each connection made to the server?

Audit

Classes used for HTTP authentication

Authenticator class The java.net package includes an Authenticator class you can use to provide a username and password for sites that protect themselves using HTTP authentication. PasswordAuthentication class The PasswordAuthentication class is a very simple final class that supports two read-only properties: username and password. The username is a String. The password is a char array so that the password can be erased when it's no longer needed. JPasswordField class The JPasswordField class is a lightweight component that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters.

To make the URL class use the authentication subclass, install it as the default authenticator by passing it to the static ___ method:

Authenticator.setDefault( )

Most important technique for preventing deadlock.

Avoid unnecessary synchronization.

BGP

BGP (Border Gateway Protocol) is a protocol for exchanging routing information between gateway hosts (each with its own router) in a network of autonomous systems. BGP is often the protocol used between gateway hosts on the Internet.

502

Bad Gateway

400

Bad Request

public String getAuthority()

Between the scheme and the path of a URL, you'll find the authority. This part of the URI indicates the authority that resolves the resource. In the most general case, the authority includes the user info, the host, and the port. For example, in the URL ftp://mp3:[email protected]:21000/c%3a/, the authority is mp3:[email protected]:21000, the user info is mp3:mp3, the host is 138.247.121.61, and the port is 21000. However, not all URLs have all parts. For instance, in the URL http://conferences.oreilly.com/java/speakers/, the authority is simply the hostname conferences. oreilly.com. The getAuthority() method returns the authority as it exists in the URL, with or without the user info and port.

Expedited Forwarding EF

Binary value 101110

A ___ is thrown if you try to construct a Socket or ServerSocket object on a local port that is in use or that you do not have sufficient privileges to use

BindException

What occurs any time a thread has to stop and wait for a resource it doesn't have?

Blocking

What occurs any time a thread has to stop and wait for a resource?

Blocking

Thread vs Runnable Synchronization

Both have the same concerns with synchronization and must consider synchronizing when their threads are operating on a shared resource.

What does the close() method shuts down for a socket?

Both input and output

Peer-to-peer

Both remote processes are executing at same level and they exchange data using some shared resource

What stores written data until it is full or flushed?

BufferedOutputStream

What is used to take text from the buffer rather than directly from the underlying input stream or the other text source?

BufferedReader

Which class makes reading data much faster?

BufferedReader

Which is used to take text from the buffer rather than directly from the underlying input stream or other text source?

BufferedReader

What is the line of code performing? URL u1 = new URL(""http://www.abc.com/javafaq/index.html""); URL u2 = new URL (u1, ""mailinglists.html"");

Builds an absolute URL from a relative URL and a base URL

Methods to read InputStream?

ByteArrayInputStream() FileInputStream() TelnetInputStream()

Which of the following is not a child class of InputStream? ByteArrayInputStream / FileInputStream / TelnetInputStream / ByteInputStream

ByteInputStream

What is a way the DNS attempts to save time for looking up data?

Caching

The ___ class allows you to add, remove, and list cookies so you can control the cookies that are sent outside the normal flow of HTTP requests and responses.

CookieStore

How do you store cookies locally?

CookieStore allows you to add, remove, and list cookies so that you can control the cookies that are sent outside the normal flow of HTTP requests and responses.

Cookie Limit

Cookies are limited to nonwhitespace ASCII text and may not contain commas or semicolons.

201

Created

What is performed with the following lines of code? SocketFactory factory = SSLSocketFactory.getDefault(); Socket socket = factory.createSocket(""login.ibiblio.org"", 7000);

Creates a secure client socket

The ___ method removes a resource from a specified URL.

DELETE

setUseClientMode()

DETERMINES whether this socket needs to do authentication in its first handshake

Packet Switched

Data Traveling on the network is broken into chunks called packets, each packet is handled separately.

What happens with a buffer write?

Data is written to the buffer instead of the underlying output stream

The ___ and ___ classes provide methods for reading and writing Java's primitive data types and strings in a binary format.

DataInputStream

readLine( ) is a popular method that is taken from the ___ class.

DataInputStream

What reads and writes in binary format?

DataInputStream() and DataOutputStream()

What is the condition in which two threads are stopped because each is waiting for a resources that the other has?

Deadlock

What occurs when two threads need exclusive access to the same set of resources and each thread holds the lock on a different subset of those resources?

Deadlock

___ occurs when two threads need exclusive access to the same set of resources and each thread holds the lock on a different subset of those resources

Deadlock

How do you make an object immutable and by proxy, thread safe?

Declare all fields private and final and don't write any methods that can change them.

Common DSCP values and interpretations

Default 00000 Best-effort traffic. Expedited Forwarding (EF) 101110 Low-loss, low-delay, low-jitter traffic. Often limited to 30% or less of network capacity. Assured Forwarding (AF) multiple Assured delivery up to a specified rate. Class Selector xxx000 Backward compatibility with the IPv4 TOS header, as stored in the first three bits.

NORM_PRIORITY

Default priority of a thread is 5

What should be chained to an output stream to convert an int to bytes and write those bytes to an underlying output stream?

Filter streams should be chained to an output stream to convert an int to bytes and write those bytes to an underlying output stream.

Filter Chains

Filters can be linked together to manipulate or interpret raw data.

Which of the following is used to filter traffic entering or exiting a network?

Firewall

What is responsible for inspecting each packet that passes into or out of its network interface and accepting or rejecting it according to a set of rules?

Firewall(s)

Define the HTTP Response Code: 403

Forbidden

TCP/IP

Four layer model

Hosts

Fully functional computer node

The ___ method retrieves a representation of a resource.

GET

When writing Java code to communicate with a server, using the POST method returns an error. Which URL method should be used instead?

GET

When writing Java code to communicate with a server, using the POST method returns an error. Which URL method should be used instead?

GET

pages accessed with the ___ method should be cached

GET

when you set doOutput to true for an http URL, the request method is changed from ___ to POST

GET

For example, adding an item to a shopping cart should send a ___, because this action doesn't commit; the user can still abandon the cart. However, placing the order should send a ___ because that action makes a commitment, which requires a resubmission if you reload that webpage.

GET POST

HttpURLConnection methods

GET POST HEAD PUT DELETE OPTIONS TRACE

Which are HTTP methods?

GET POST PUT

What are the four main HTTP methods?

GET POST PUT DELETE

HTTP Methods

GET PUT DELETE POST The other two that Java supports are OPTIONS, which lets the client ask the server what it can do with a specified resource; and TRACE, which echoes back the client request for debugging purposes, especially when proxy servers are misbehaving. Different servers recognize other nonstandard methods including COPY and MOVE, but Java does not send these.

HTTP Methods

GET The GET method retrieves a representation of a resource. PUT The PUT method replaces all current representations of the target resource with the uploaded content. DELETE The DELETE method removes a resource from a specified URL. POST The POST method uploads a representation of a resource to a server at a known URL. The other two that Java supports are OPTIONS, which lets the client ask the server what it can do with a specified resource; and TRACE, which echoes back the client request for debugging purposes, especially when proxy servers are misbehaving. Different servers recognize other nonstandard methods including COPY and MOVE, but Java does not send these.

When writing Java code to communicate with a server, using the POST method returns and error. What URL method should be used instead?

GET should be used instead of POST.

504

Gateway Timeout

410

Gone

Once connected to the server, which request will check to see if a web document has been modified since the document was last cached?

HEAD

Which HTTP method will you use to check whether the copy stored in the local cache is still valid or not?

HEAD

505

HTTP Version Not Supported

What is RFC 1945?

HTTP. Application layer protocol used by web browsers.

What is on port 80?

HTTP. It is the underlying protocol of the world wide web.

405

HTTP_BAD_METHOD

408

HTTP_CLIENT_TIMEOUT

403

HTTP_FORBIDDEN

406

HTTP_NOT_ACCEPTABLE

404

HTTP_NOT_FOUND

402

HTTP_PAYMENT_REQUIRED

401

HTTP_UNAUTHORIZED

Which interface is implemented for getting notifications of handshake-complete events?

HandshakeCompletedListener

interface implemented for getting notifications of handshake-completed events

HandshakeCompletedListener

Which of the following is NOT a way to wake up a thread? timeout expires / interrupt the thread / have another thread join it / notify the object

Have another thread join it

Which of the following is NOT a way to have a thread pause? sleep / yield / join / preempt

Have it preempt another thread

Thread Safe Collections rule

If you invoke collections.synchronizedSet, List or Map, you must not ever reference the original set, list or map again because if you do, the original object and the newly invoked object via Collections.Syncronized... will also be thread unsafe.

What exception does setNeedClientAuth() throw?

IllegalArgumentException

Which of the following exceptions is thrown by the setNeedClientAuth() method if socket is not on the server side?

IllegalArgumentException

setAllowUserInteraction() when the URLConnection is connected throws an

IllegalStateException

How do you gain fined-grained control of cookie management?

Implement the CookiePolicy interface into your class and override the shouldAccept() method.

Finally Block

In Java 6 and earlier, what is the best way to close the stream?

asymmetric encryption

In asymmetric encryption, the public key is used to encrypt the data and the private key is used to decrypt the data.

multithreaded servers

In what type of server do java programs should spawn a thread to interact with the client so that the other clients don't have to wait.

create a new InetAdress object

InetAddress addr1 = InetAddress.getByName("www.google.com");

What is the code to do a reverse lookup of an IP address, and print it?

InetAddress address = InetAddress.getByName("208.201.239.100"); System.out.println(address.getHostName());

How do you do a reverse address lookup in Java for 216.58.192.174?

InetAddress address = InetAddress.getByName("216.58.192.174"); System.out.println(address.getHostName());

How do you look up the address of google.com in Java?

InetAddress address = InetAddress.getByName("www.google.com");

There are no corresponding setHostName() and setAddress() methods for InetAddress, which means:

InetAddress is immutable.

check the latency to a particular host

InetAddress.isReachable()

Proxy Class

It allows more fine-grained control of proxy servers from within a Java program. Specifically, it allows you to choose different proxy servers for different remote hosts. The proxies themselves are represented by instances of the java.net.Proxy class. There are still only three kinds of proxies, HTTP, SOCKS, and direct connections (no proxy at all), represented by three constants in the Proxy.Type enum: Proxy.Type.DIRECT Proxy.Type.HTTP Proxy.Type.SOCKS Besides its type, the other important piece of information about a proxy is its address and port, given as a SocketAddress object. For example, this code fragment creates a Proxy object representing an HTTP proxy server on port 80 of proxy.example.com: SocketAddress address = new InetSocketAddress("proxy.example.com", 80); Proxy proxy = new Proxy(Proxy.Type.HTTP, address);

What is the advantage of breaking data into packets?

It allows packets to be checked for damages in transit using checksums.

What are RFC 1034 and 1035?

It are the Domain Name System. Defines how DNS servers on different hosts communicate with each other.

What are RFC 854 and 855?

It are the telnet protocols. It is an insecure remote login service for command-line environments.

What is a packet-switched network?

It breaks data down into chunks called packets and each packet is handled separately when moving across the network.

10 ways a thread can pause in favor of other threads or indicate that it is ready to pause.

It can block on I/O. It can block on a synchronized object. It can yield. It can go to sleep. It can join another thread. It can wait on an object. It can finish. It can be preempted by a higher-priority thread. It can be suspended. It can stop.

Which is a way a thread can pause in favor of other threads or indicate that it is ready to pause?

It can yield It can go to sleep It can join another thread It can be preempted by a higher-priority thread

What is the host-to-network layer?

It defines how a particular network interface such as an Ethernet card sends IP datagrams over its physical connection to the local network and world. The physical layer made up of wires, fiber, radio waves, etc. is also part of it. For programmers, the only time you need to think about this layer would be for performance.

What is the Internet layer?

It defines how packets are organized, the addressing scheme, the routing of packets, and to enable different types of host-to-network layers to talk to each other such as translating between Ethernet and DSL.

What is the application layer?

It delivers data to the user. It decides what to do with the data after it is transferred.

What does yielding not do?

It does not release any locks the thread holds.

Which is a characteristic of the Java core networking API?

It does not support explicit peer-to-peer communications

what does .showdown() do to an ExecutorService pool?

It does not terminate processing, it just signals the Executor that no further tasks will be added to the queue and that it should shut down when finished.

How does Java deal with Peer-To-Peer?

It doesn't inherently support Peer-To-Peer networking

what does .shutdownNow() do to an ExecutorService pool?

It ends work immediately.

What class does java.net.URL extend?

It extends java.lang.Object and is a final class that cannot be subclassed.

Why is flushing an important step in writing to a BufferedOutputStream?

It forces the stream to print the buffer

PrintStream's mostly unique feature

It internally synchronizes most methods on the PrintStream object. Most other subclasses of OutputStream don't internally synchronize.

What is the Java.net.InetAddress class?

It is Java's high-level representation of an IP address both IPv4 and IPv6.

What does an Expires header specify?

It is OK to cache this representation until the specified time

What is the HTTP response code 100?

It is a continue response code. The server is prepared to accept the request body and the client should send it. Allows clients to ask if the server will accept large amounts of data before the client sends it.

JPasswordField class

It is a lightweight component that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters.

What is a node?

It is a machine on a network. Most nodes are computers, but printers, routers, bridges, gateways, household "smart" appliances, etc. can all be nodes.

What does public void write(byte[] a) do?

It is a method that will allow Java to store IP addresses in an array by using an output stream.

What is a protocol?

It is a precise set of rules defining how computers communicate i.e. the format of addresses, how to split data into packets, etc.

BGP ()

It is a protocol for exchanging routing information between gateway hosts (each with its own router) in a network of autonomous systems. BGP is often the protocol used between gateway hosts on the Internet.

What is an address?

It is a sequence of bytes that uniquely identifies a node on a network.

PasswordAuthentication class

It is a very simple final class that supports two read-only properties: username and password. The username is a String. The password is a char array so that the password can be erased when it's no longer needed.

What is the Client/Server Model?

It is an application typically stores large quantities of data on a server or cloud of servers while the program logic/user interface is handled by the client software running on personal computers.

What is the HTTP response code 503?

It is the service unavailable response code. The server is temporarily unable to handle the request.

What is UDP?

It is an unreliable protocol used when where it doesn't matter if all the packets arrive or arrive in the same order. UDP doesn't verify if everything arrived or not and thus reduces overhead. This is quite frequently used for things like video.

What is this code doing? URL u1 = new URL("http://www.ncsa.uiuc.edu/HTMLPrimer.html#GS"); URL u2 = new URL("http://www.ncsa.uiuc.edu/HTMLPrimer.html#HD"); if (u1.sameFile(u2)) { System.out.println(u1 + " is the same file as \n" + u2); } else { System.out.println(u1 + " is not the same file as \n" + u2); }

It is comparing two URL's to see if they point to the same resource. *Note: The output is: http://www.ncsa.uiuc.edu/HTMLPrimer.html#GS is the same file as http://www.ncsa.uiuc.edu/HTMLPrimer.html#HD

PrintStream

It is evil and network programmers should avoid it like the plague!

Why is polling not a good solution to a race condition?

It is not guaranteed to work

What is TCP?

It is placed on top of the IP to give each end of the connection the ability to acknowledge receipt of IP packets and request retransmission of lost of or corrupted packets. Furthermore, it allows packets to be put back in the correct order. It carries a fair amount of overhead though.

URI Class

It is purely about identification of resources and parsing of URIs. It provides no methods to retrieve a representation of the resource identified by its URI. The URI class is more conformant to the relevant specifications than the URL class. A URI object can represent a relative URI. The URL class absolutizes all URIs before storing them.

What is the transport layer?

It is responsible for ensuring that packets are received in the order they were sent and that no data is lost or corrupted. The two primary protocols are TCP and UDP.

What is DNS?

It is the Domain Name System. DNS associates hostnames that can be more easily remembered (e.g. google.com) with IP addresses that computers can remember.

What is RFC 792?

It is the Internet Control Message Protocol. It is an internet layer protocol that uses raw IP datagrams but is not supported by Java. Used for ping and traceroute.

What is RFC 5000?

It is the Internet Official Protocol Standards. Describes the standardization process of the different Internet Protocols.

What is RFC 977?

It is the Network News Transfer Protocol. It is an application layer protocol by which Usenet new is transferred from machine to machine.

What is RFC 1939?

It is the Post Office Protocol v 3. And application layer protocol used by sporadically connected email clients such as Eudora.

What is RFC 768?

It is the User Datagram Protocol. It's an unreliable, connectionless transport layer protocol.

What is the HTTP response code 202?

It is the accepted code. It indicates that a request is being processed.

What is preemption?

It is the act of temporarily interrupting a task being carried out by a computer system, without requiring its cooperation, and with the intention of resuming the task at a later time. Such a change is known as a context switch. An example would be a thread being paused and hands off control of the CPU to a different thread.

What is the HTTP response code 400?

It is the bad request response code. The client's request to the server used improper syntax.

What is the HTTP response code 201?

It is the created code. The server has created a resource at the specified URL.

What is RFC 959?

It is the file transfer protocol. Optionally authenticated application layer protocol.

What is the HTTP response code 403?

It is the forbidden code. The server understands the request, but it refuses to process it.

What is the HTTP response code 500?

It is the internal server error response code. Server doesn't know how to handle a condition.

What is a port?

It is the logical connection point for the transmission of information packets. It does not represent anything physical. It is merely an abstraction of a computer's memory. This allows computers to do many different things at once.

What is the HTTP response code 301?

It is the moved permanently code. The resource has permanently moved to a new URL.

What is the HTTP response code 302?

It is the moved temporarily response code. The resource is at a new URL temporarily, but it's location will change again in the foreseeable future.

What is the HTTP response code 204?

It is the no content code. The server processed the request but has no information to send.

What is the HTTP response code 404?

It is the not found response code. The server cannot find the requested resource.

What is the HTTP response code 501?

It is the not implemented response code. Server doesn't have the feature needed to process this request.

asymmetric encryption

It is the public key used to encrypt the data and the private key is used to decrypt the data.

What is a callback?

It is when you allow the thread to call its creator back when it is done. This way the main program can go to sleep while waiting for the threads to finish and not steal time from the running threads.

What does this code do, and what would the output be? import java.io.*; import java.net.*; public class URLPrinter { public static void main(String[] args) { try { URL u = new URL("http://www.oreilly.com/"); URLConnection uc = u.openConnection(); System.out.println(uc.getURL()); } catch (IOException ex) { System.err.println(ex); } } }

It opens a connection with http://www.oreilly.com, gets the URL of the connection, and prints it. % java URLPrinter http://www.oreilly.com/

RIP

It prevents routing loops by implementing a limit on the number of hops allowed in a path from source to destination. The maximum number of hops allowed for RIP is 15, which limits the size of networks that RIP can support.

Purposes of the URLConnection class

It provides more control over the interaction with a server (especially an HTTP server) than the URL class It is part of Java's protocol handler mechanism, which also includes the URLStreamHandler class

Purposes of the URLConnection class

It provides more control over the interaction with a server (especially an HTTP server) than the URL class The URLConnection class is part of Java's protocol handler mechanism, which also includes the URLStreamHandler class

Which are purposes of the URLConnection class?

It provides more control over the interaction with a server (especially an HTTP server) than the URL class The URLConnection class is part of Java's protocol handler mechanism, which also includes the URLStreamHandler class

NetworkInterface class

It represents a local IP address. This can either be a physical interface such as an additional Ethernet card (common on firewalls and routers) or it can be a virtual interface bound to the same physical hardware as the machine's other IP addresses. The NetworkInterface class provides methods to enumerate all the local addresses, regardless of interface, and to create InetAddress objects from them. These InetAddress objects can then be used to create sockets, server sockets, and so forth. getByInetAddress() getNetworkInterfaces getInetAddresses() getByName() getDisplayName()

What does getByInetAddress() return?

It returns a Network Interface object representing the network interface bound to the specified IP address.

What does the following method of the NetworkInterface class do? getByInetAddress()

It returns a NetworkInterface object representing the network interface bound to the specified IP address.

What does the following method of the NetworkInterface class do? getByName()

It returns a NetworkInterface object representing the network interface with a particular name.

NetworkInterface foo = NetworkInterface.getByName("eth1"); Enumeration fooAddresses = foo.getInetAddresses(); What does this code do?

It returns a NetworkInterface object then gets all of the IP addresses of that object and stores them in fooAddresses.

What does NetworkInterface's getInetAddress() method return?

It returns a java.util.Enumeration containing an InetAddress object for each IP address the interface is bound to.

What does the following method of the NetworkInterface class do? getNetworkInterfaces()

It returns a java.util.Enumeration listing all the network interfaces on the local host.

What does the following method of the NetworkInterface class do? getDisplayName()

It returns a more human-friendly name for the particular NetworkInterface object.

What does the following method of the NetworkInterface class do? getInetAddresses()

It returns an Enumeration with all or a subset of the InetAddresses bound to this network interface.

getContentType()

It returns the MIME media type of the response body.

getLastModified()

It returns the date on which the document was last modified.

getContentLength()

It tells how many bytes there are in the content.

Which port does FTP use be default?

It uses port 21 by default.

What does an original thread do when a reader thread notifies a ManifestFile?

It wakes up and continues when a reader thread notifies a ManifestFile.

What is the Internet Protocol (IP)?

It was developed to allow multiple routes between any two points and to route packets of data around damaged routers. It also needed to be platform independent.

t.setPriority(15) will result in what?

It will result in an IllegalArgumentException because the thread class only has priorities ranging from 1 to 10 with 10 being the highest.

A Java programmer wants to use AES256 for the secure socket connections between the client and the server. What must be installed to support AES256?

Java Cryptography Extension (JCE)

A Java programmer wants to use AES256 for the secure socket connections between the client and the server. What must be installed to support AES256?

Java Cryptography Extension (JCE)

What must be installed to support AES256?

Java Cryptography Extension (JCE)

What should you do if the URL protocl you need isn't supported in your particular Java VM?

Java may have an additional protocol handler that you can download for the scheme you need. However, IRL, don't use this method, go find an API that can will work.

How long does Java cache unsuccessful DNS queries?

Java only caches unsuccessful queries for 10 seconds. This is because it is common for requests to time out.

Which protocols does Java support?

Java only supports TCP, UDP and the application protocols built on top of those.

What classes does Java use to distinguish between IPv4 and IPv6 addresses?

Java uses Inet4Address and Inet6Address in order to distinguish between IPv4 and IPv6 addresses.

Inet4Address and Inet6Address

Java uses two classes, Inet4Address and Inet6Address, in order to distinguish IPv4 addresses from IPv6 addresses: Inet4Address overrides several of the methods in InetAddress but doesn't change their behavior in any public way. Inet6Address is similar, but it does add one new method not present in the superclass, isIPv4CompatibleAddress.

java.net.InetAddress

Java's high level representation of an IP addres, both IPv4 and IPv6

Used to process numeric addresses and their corresponding host names.

Java.net.InetAddress class

a client indicates that it's willing to reuse a socket by including a Connection field in the HTTP request header with

Keep-Alive

under no conditions you should read or write to anything other than the

LAST filter in the chain

Failure to close a stream in a long-running program can?

Leak file handles, network ports, and other resources.

411

Length Required

OPTIONS

Lets the client ask the server what it can do with a specified resource.

URL Uniform Resource Locator

Like a URI, in addition provides network location for the resource

Synchronized Block

Like a try block but following this pattern: synchronized (arg) {} where arg is the synchronized object. For example, you could use System.out as the arg.

A specific routing protocol quickly identifies changes within the network to find the fastest route and distributes this information to all routers on the segment. Which routing protocol is being described?

OSPF

Which routing protocol quickly identifies changes within the network to find the fastest route and distributes information to all routers on the segment?

OSPF.

11001100.11010011.00100110.00110100

Observe the given IP address: 204.211.38.52

InetAddress[] address = InetAddress.getAllByName("www.company.org");

Observe the given code statement: InetAddress address = InetAddress.getByName("www.company.org"); If the hostname has more than one address, which code should replace this line?

The array will only read the bytes available and then wait.

Observe the given code: int binitread = 0; int bleftread = 512; byte[] input = new byte[bleftread]; while(binitread < bleftread){ binitread += in.read(input,binitread, bleftread - binitread); } What happens if there is less than 512 bytes of data available from the input stream?

Why are string arguments safe from deadlock?

Once created, a string object is immutable.

Terminating state:

Once execution leaves a thread's run() method, that thread is in the ________ state, that is... the thread ceases to exist.

How many URL cache does Java allow at a time?

One

Each virtual machine has exactly ___ ProxySelector. To change the Proxy Selector, pass the new selector to the static ___ method.

One ProxySelector.setDefault( )

Client-Server

One remote process acts as a Client and requests some resource from another application process acting as Server.

What does this code do? Socket socket = new Socket("dict.org", 2628); socket.setSoTimeout(15000);

Opens a socket to a dictionary server and sets a timeout in case the server hangs.

What receives characters from a Java program and converts these into bytes according to a specified encoding and writes them onto an underlying output stream?

OutpuStreamWriter.

What writes data in Java?

OutputStream

How would you write to the client?

OutputStream out = connection.getOutputStream(); Writer writer = new OutputStream(writer, "ASCII"); Date now = new Date(); out.write(now.toString() + "\r\n"); out.flush(); connection.close();

What converts characters to bytes according to specified encoding?

OutputStreamWriter

What is the most important concrete subclass of writer?

OutputStreamWriter

Which receives characters from a Java program and converts these into bytes according to a specified encoding and writes them onto an underlying output stream?

OutputStreamWriter

Writer's most important subclass?

OutputStreamWriter

toExternalForm()

Outside of print statements, it's more proper to use toExternalForm() instead: public String toExternalForm() The toExternalForm() method converts a URL object to a string that can be used in an HTML link or a web browser's Open URL dialog. The toExternalForm() method returns a human-readable String representing the URL. It is identical to the toString() method. In fact, all the toString() method does is return toExternalForm().

A subclass of Writer must?

Overwrite at least write(char[] text, int offset, int length), flush() and close().

What MIME subtype would be used for images?

PNG, JPG, GIF

AutoCloseable

Post java 6, you can declare autoclosable objects in the try block's argument list and they will auto-close when the try block ends. In java 6 and earlier, you should close using a finally block after your catch block.

Where is the ACTION attribute of the FORM element placed?

Precedes the query string

428

Precondition Required

Which term is used to describe a thread that has its allotted CPU time, pauses the thread, and then hands off control of the CPU to a different thread?

Preemption

What is the primary reason to code in the Host-To-Network layer?

Primary reason to code in Host-To-Network layer is to update performance.

What stream is System.out part of?

PrintStream

Evil.. should be avoided like the plague

PrintStream's println() is platform-dependent PrintStream assumes default encoding PrintStream eats all exceptions

Filter Readers And Writers

PrintWriter It prints formatted representations of objects to a text-output stream. PushbackReader It allows characters to be inserted or pushed back into the stream. BufferedReader It reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. LineNumberReader It is a buffered character-input stream that keeps track of line numbers. BufferedWriter It writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Filter Readers And Writers

PrintWriter It prints formatted representations of objects to a text-output stream. PushbackReader It allows characters to be inserted or pushed back into the stream. BufferedReader It reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. LineNumberReader It is a buffered character-input stream that keeps track of line numbers. BufferedWriter It writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

New code should use PrintWriter instead of PrintStream because?

PrintWriter properly handles multibyte character sets and international text. PrintWriter class has an almost identical collection of methods to PrintStream.

A programmer has been advised by the security department to report whenever a user is denied connectivity to a server because failed authentication is considered to be high risk. Which lines of code will the programmer need to add to trigger an alert of the high risk activity?

Private final static logger userAudit = logger.getLogger("userLogins"); catch(Exception z){useraudit.log(Level.SEVERE, "DOS", z);}

trigger an alert of the high risk activity

Private final static logger userAudit = logger.getLogger("userLogins"); catch(Exception z){useraudit.log(Level.SEVERE, "DOS", z);}

A set of rules defining how computers communicate with each other.

Protocol

URL Syntax

Protocol://userInfo@host:port/path?query#fragment

413

Request Entity Too Large

431

Request Header Fields Too Large

2XX

Request Succeeded

414

Request URI Too Long

416

Requested Range Not Satisfiable

205

Reset Content

Finally, you need a simple ___ subclass that stores and retrieves the cached values as requested while paying attention to the original Cache-control header.

ResponseCache

To install or change the cache, use the static _______ method.

ResponseCache.setDefault()

Transport layer

Responsible for ensuring packets are received in order and no data is lost or corrupted. TCP reliable protocol UDP unreliable protocol

GET

Retrieves a representation of a resource.

What does the 5XX line of HTTP response codes mean?

Server Error 500 - Internal Server Error 501 - Not Implemented 502 - Bad Gateway 503 - Service Unavailable 504 - Gateway Input 505 - HTTP Version not supported 507 - Insufficient storage 511 - Network Authentication Required

Define the HTTP Response Code: 5XX series

Server side error

Which Java class is used to represent server sockets?

ServerSocket

How would you construct a Server object?

ServerSocket server = new ServerSocket(13);

503

Service Unavailable

Define the HTTP Response Code: 503

Service unavailable

InetAddress addresses = InetAddress.getByName(ip); System.out.println(address.getHostName()); What is being printed out here?

The DNS resolution is being printed out by this code.

public String getUserInfo()

Some URLs include usernames and occasionally even password information. This information comes after the scheme and before the host; an @ symbol delimits it. For instance, in the URL http://[email protected]/, the user info is elharo. Some URLs also include passwords in the user info. For instance, in the URL ftp:// mp3:[email protected]/c%3a/stuff/mp3/, the user info is mp3:secret. However, most of the time, including a password in a URL is a security risk. If the URL doesn't have any user info, getUserInfo() returns null.

write, flush, close

Standard OutputStream Methods

What is this code doing? Thread t = new Thread(); t.start();

Starting a new thread running in the virtual machine.

What is the best practice in preventing against a man-in-the-middle attack?

Store and verify their public with a trusted third-party certification authority

To URL encode a string, pass the string and the character set name to the ___ method. For example, using plus signs, the code would look something like:

String encoded = URLEncoder.encode("This+string+has+plus+signs", "UTF-8");

NetworkInterface class

The NetworkInterface class represents a local IP address. This can either be a physical interface such as an additional Ethernet card (common on firewalls and routers) or it can be a virtual interface bound to the same physical hardware as the machine's other IP addresses. The NetworkInterface class provides methods to enumerate all the local addresses, regardless of interface, and to create InetAddress objects from them. These InetAddress objects can then be used to create sockets, server sockets, and so forth. getByInetAddress() This method returns a NetworkInterface object representing the network interface bound to the specified IP address. getNetworkInterfaces This method returns a java.util.Enumeration listing all the network interfaces on the local host. getInetAddresses() This method returns an Enumeration with all or a subset of the InetAddresses bound to this network interface. getByName() This method returns a NetworkInterface object representing the network interface with the particular name. getDisplayName() This method returns a more human-friendly name for the particular NetworkInterface object.

PasswordAuthentication class

The PasswordAuthentication class is a very simple final class that supports two read-only properties: username and password. The username is a String. The password is a char array so that the password can be erased when it's no longer needed.

Proxy Class

The Proxy class allows more fine-grained control of proxy servers from within a Java program. Specifically, it allows you to choose different proxy servers for different remote hosts. The proxies themselves are represented by instances of the java.net.Proxy class. There are still only three kinds of proxies, HTTP, SOCKS, and direct connections (no proxy at all), represented by three constants in the Proxy.Type enum: Proxy.Type.DIRECT Proxy.Type.HTTP Proxy.Type.SOCKS Besides its type, the other important piece of information about a proxy is its address and port, given as a SocketAddress object. For example, this code fragment creates a Proxy object representing an HTTP proxy server on port 80 of proxy.example.com: SocketAddress address = new InetSocketAddress("proxy.example.com", 80); Proxy proxy = new Proxy(Proxy.Type.HTTP, address);

toString() method

The String produced by toString() is always an absolute URL, such as http://www.cafeaulait.org/javatutorial. html. It's uncommon to call toString() explicitly. Print statements call to String() implicitly

ways that the URI class differs from the URL class

The URI class is more conformant to the relevant specifications than the URL class A URI object can represent a relative URI. The URL class absolutizes all URIs before storing them The URI class is purely about identification of resources and parsing of URIs

URI class differs from the URL class

The URI class is purely about identification of resources and parsing of URIs A URI object can represent a relative URI. The URL class absolutizes all URIs before storing The URI class is more conformant to the relevant specifications than the URL class

Which are ways that the URI class differs from the URL class?

The URI class is purely about identification of resources and parsing of URIs The URI class is more conformant to the relevant specifications than the URL class A URI object can represent a relative URI. The URL class absolutizes all URIs before storing them

URI Class

The URI class is purely about identification of resources and parsing of URIs. It provides no methods to retrieve a representation of the resource identified by its URI. The URI class is more conformant to the relevant specifications than the URL class. A URI object can represent a relative URI. The URL class absolutizes all URIs before storing them.

What is the end result of this code? URI absolute = new URI("http://www.example.com/images/logo.png"); URI top = new URI("http://www.example.com/"); URI relative = top.relativize(absolute);

The URI object relative now contains the relative URI images/logo.png.

equals() and hashCode() methods

The URL class contains the usual ________. These behave almost as you'd expect. Two URLs are considered equal if and only if both URLs point to the same resource on the same host, port, and path, with the same fragment identifier and query string. However there is one surprise here. The equals() method actually tries to resolve the host with DNS so that, for example, it can tell that http:// www.ibiblio.org/ and http://ibiblio.org/ are the same.

What type of method does Java's URL class use for communications with HTTP servers?

The URL class uses the GET method.

result of running this against several of the URL examples in this chapter: % java URLSplitter \ ftp://mp3:[email protected]:21000/c%3a/ \ http://www.oreilly.com \ http://www.ibiblio.org/nywc/compositions.phtml?category=Piano \ http://[email protected]:8080/ \

The URL is ftp://mp3:[email protected]:21000/c%3a/ The scheme is ftp The user info is mp3:mp3 The host is 138.247.121.61 The port is 21000 The path is /c%3a/ The ref is null The query string is null The URL is http://www.oreilly.com The scheme is http The user info is null The host is www.oreilly.com The port is -1 The path is The ref is null The query string is null The URL is http://www.ibiblio.org/nywc/compositions.phtml?category=Piano The scheme is http The user info is null The host is www.ibiblio.org The port is -1 The path is /nywc/compositions.phtml The ref is null The query string is category=Piano The URL is http://[email protected]:8080/ The scheme is http The user info is admin The host is www.blackstar.com The port is 8080 The path is / The ref is null The query string is null</programlisting>

Writer Synchronization

The Writer classes all have their own internal synchronization, which protects one thread from interfering with a write() method in another thread. (This is not true of input and output streams, with the exception of PrintStream.

javax.net.ssl

The abstract classes that define Java's API for secure network communication. (This package provides classes for the secure socket package.)

Javax.net

The abstract socket factory classes used instead of constructors to create secure sockets. (This package provides classes for networking applications. These classes include factories for creating sockets.)

What does the following code print? public class MSByName { public static void main ( String [] args ) { InetAddress address = InetAddress . getByName ( "" www . microsoft . com "" ); System . out . println ( address ); } catch ( UnknownHostException ex ) { System . out . println ( "" Could not find www . microsoft . com "" ); }}

The address of www.microsoft.com

Authority

The authority responsible for resolving a URI request, usually the FQDN. (e.g. google.com, youtube.com, facebook.com)

What is this code doing? public void calculateDigest() { ListCallbackDigest cb = new ListCallbackDigest(filename); cb.addDigestListener(this); Thread t = new Thread(cb); t.setPriority(8); t.start(); }

The calculateDigest() method sets the priority of each spawned thread to 8.

java.security.cert

The classes for handling the public-key certificates needed for SSL. (This package provides classes and interfaces for parsing and managing certificates, certificate revocation lists (CRLs), and certification paths.)

What describes the role of the client?

The client initiates communication.

Sending request from client to server

The client opens a TCP connection to the server on port 80, by default; other ports may be specified in the URL. The client sends a message to the server requesting the resource at a specified path. The request includes a header, and optionally (depending on the nature of the request) a blank line followed by data for the request. The server sends a response to the client. The response begins with a response code, followed by a header full of metadata, a blank line, and the requested document or an error message. The server closes the connection.

Which of the following will be the next step after the client opens a TCP connection to the server on port 80?

The client sends the message to the server requesting the resource at a specified path.

What does invoking the close() method do for streams?

The close() method releases resources for streams.

public boolean sameFile(URL other)

The comparison is essentially the same as with equals(), DNS queries included, except that sameFile() does not consider the fragment identifier. This sameFile() returns true when comparing http://www.oreilly.com/index.html#p1 and http://www.oreilly. com/index.html#q2 while equals() would return false.

com.sun.net.ssl

The concrete classes that implement the encryption algorithms and protocols in SUn's reference implementation of the JSSE. (This package provides classes that implement the encryption algorithms and protocols in Sun's reference implementation of the JSSE.)

Scheme-Specific-Part

The contents of a URI string (e.g. //youtube.com, //[email protected], //pbay.org/the-complete-works-of-shakespeare.torrent)

What protocol is on port 13?

The daytime protocol. It provides ASCII representation of the current time on the server.

What happens if no encoding is specified?

The default platform encoding is used

What protocol is on port 8?

The discard protocol is on port 8. It is a less useful test protocol where data received by the server is ignored.

What protocol is on port 7?

The echo protocol. It is a test protocol used to verify that two machines are able to connect by having one echo the other's input.

What are 3 problems with using PrintStream?

The first problem is that the output from println( ) is platform dependent. The second problem is that PrintStream assumes the default encoding of the platform on which it's running. The third problem is that PrintStream eats all exceptions. Zero exceptions are or can be thrown. The outdated checkError( ) method needs to be used. Gross.

Server Program Life Cycle

The following stages are involved in basic life cycle of a server program: A new ServerSocket is created on a particular port using a ServerSocket() constructor. The ServerSocket listens for incoming connection attempts on that port using its accept() method. accept() blocks until a client attempts to make a connection, at which point accept() returns a Socket object connecting the client and the server. Depending on the type of server, either the Socket's getInputStream() method, getOutputStream() method, or both are called to get input and output streams that communicate with the client. The server and the client interact according to an agreed-upon protocol until it is time to close the connection. The server, the client, or both close the connection. The server returns to step 2 and waits for the next connection.

getInetAddress() and getPort()

The getInetAddress() and getPort() methods tell you the remote host and port the Socket is connected to; or, if the connection is now closed, which host and port the Socket was connected to when it was connected.

public String getProtocol()

The getProtocol() method returns a String containing the scheme of the URL (e.g., "http", "https", or "file"). For example, this code fragment prints https: URL u = new URL("https://xkcd.com/727/"); System.out.println(u.getProtocol());

What protocol is on port 37?

The time protocol. A time server returns the number of seconds that have elapsed on the server since midnight, January 1, 1900 as a four-byte unsigned, big-endian integer.

Observe the given code statement: try{ Socket s = new Socket(); SocketAddress a = new InetSocketAddress("dropbox.test.com",21); s.connect(a,0); } What does the 0 represent in this socket connection java code?

The timeout is set to wait forever.

try{ Socket s = new Socket(); SocketAddress a = new InetSocketAddress("dropbox.test.com",21); s.connect(a,0); } What does the 0 represent in this socket connection java code?

The timeout is set to wait forever.

MIN_PRIORITY

The value of ______PRIORITY is 1

MAX_PRIORITY

The value of ______PRIORITY is 10

java.util.logging.Level

There are seven levels defined as named constants in descending order of seriousness: Level.SEVERE (highest value) Level.WARNING Level.INFO Level.CONFIG Level.FINE Level.FINER Level.FINEST (lowest value)

java.util.logging.Level

There are seven levels defined as named constants in java.util.logging.Level in descending order of seriousness: Level.SEVERE (highest value) Level.WARNING Level.INFO Level.CONFIG Level.FINE Level.FINER Level.FINEST (lowest value)

dataOutputStream

These write methods belong to ______ write boolean write byte write short write char write int write long write float write double write chars write bytes write UTF

How does peer-to-peer work?

They act as both the client and the server

What can be said about Filter Streams?

They all share (input and output) the same write, close and flush methods as java.io.InputStream and java.io.OutputStream

What are hosts?

They are nodes that are computers.

How are cookies stored inside a CookieStore?

They are stored as objects HttpCookie. Many of the internal methods of HttpCookie are obsolete like comment, comment URL and discard.

What are RFC 2045, 2046, and 2047?

They are the Multipurpose Internet Mail Extensions (MIME). It's a means of encoding binary data and non-ASCII text for transmission through Internet email and other ASCII-oriented protocols.

Place warning, info, config, and finer in order from most serious 1 to least serious 4.

They go from most serious to least serious.

What layer do the protocols TCP and UDP reside in?

They reside in the transport layer.

What is the benefit of sockets to a programmer?

They treat network connections like any other data stream.

RFC 5000

This document is published by the RFC Editor to provide a summary of the current standards protocols (as of 18 February 2008). It lists those official protocol standards, Best Current Practice, and Experimental RFCs that have not been obsoleted; it is not a complete index to the RFC series. Newly published RFCs and RFCs whose status has changed are starred.

Which method should be invoked to start a new thread running in a virtual machine?

Thread t = new Thread(); t.start ();

How do you start a new thread?

Thread t = new Thread(); t.start()

What method should be invoked to start a new thread running in a virtual machine?

Thread t = new Thread(); t.start(); should be invoked to start a new thread running in a virtual machine.

This signals to the virtual machine that it can run another thread if one is ready to run.

Thread.yield( )

Yielding

Thread.yield() - some VMs may ignore this, especially real-time operating systems.

Thread performance vs processes

Threads share memory unlike processes so they are easier on resources. Its about a factor of 3 increase in performance to use threads over processes.

hat is the purpose of threading?

To efficiently use available resources

Thread safe sets

To get a thread safe view of a set, use Collections.synchronizedSet()

You should inspect every run() method for?

To make sure that one of the 10 ways a thread can pause will occur with reasonable frequency.

What is the use of the echo protocol?

To test the network for making sure that data is not destroyed by a faulty router

Which layer is responsible for ensuring that packets are received in the order they were sent and that no data is lost or corrupted?

Transport

Responsible for ensuring that packets are received in the order they were sent and that no data is lost or corrupted

Transport (Layer)

TCP/UDP layer?

Transport (Layer)

Transmission Control Protocol(TCP), is a high-overhead protocol that allows for retransmission of lost of corrupted data and delivery of bytes in the order they were sent. What layer is it on?

Transport (Layer)

User Datagram Protocol(UDP), allows the receiver to detect corrupted packets but does not guarantee that packets are delivered in the correct order(or at all). What layer is it on?

Transport (Layer)

The Java URL class is final

True

URL objects are immutable

True

What can replace a finally{ } call in Java 7+ ?

Try with resources

RFC 768

UDP

Which is a connectionless protocol?

UDP

Which is faster, UDP or TCP?

UDP

Which protocol is used where signal degradation is less noticeable?

UDP

Which is an advantage of UDP over TCP?

UDP is faster than TCP

Which protocols reside in the transport layer?

UDP, TCP

What is a string of characters in a particular syntax that identifies a resource, such as a file on a server, an email address, a news message, a book, a person's name, an Internet host, or other identifier?

URI

How would a URI absolute constructor look differently than a URI relative constructor?

URI absolute = new URI("http", "//www.ibiblio.org" , null); URI relative = new URI(null, "/javafaq/index.shtml", "today");

What would a URI constructor look like for a phone number? A webpage? A book?

URI voice = new URI("tel:+1-800-9988-9938"); URI web = new URI("http://www.xml.com/pub/a/2003/09/17/stax.html#id=_hbc"); URI book = new URI("urn:isbn:1-565-92870-9");

IllegalArgumentException

URI.Create() throws _____

Constructing a URI

URIs are built from strings. You can either pass the entire URI to the constructor in a single string, or the individual pieces:

A ___ is a URI that, as well as identifying a resource, provides a specific network location for the resource that a client can use to retrieve a representation of that resource.

URL

abstract

URL connection classes are _____ (abstract/concrete)

filter readers and writers

bufferedReader bufferedWriter lineNumberReader pushbackReader pushbackWriter are examples of ___ ___ ___ ___?

casting a URLC to HttpURLC

URL u = new URL("http://hellomoto.com"); HttpURLConnection http = (HtttpURLConnection) u.openConnection();

Which line of code would construct a new URL from a string?

URL u = new URL("http://www.abc.com/");

an HTML file to be returned as a String, but your second choice is a Reader and your third choice is an InputStream, write:

URL u = new URL("http://www.nwu.org"); Class<?>[] types = new Class[3]; types[0] = String.class; types[1] = Reader.class; types[2] = InputStream.class; Object o = u.getContent(types); - If the content handler knows how to return a string representation of the resource, then it returns a String. If it doesn't know how to return a string representation of the resource, then it returns a Reader. And if it doesn't know how to present the resource as a reader, then it returns an InputStream.

___ is an abstract class that represents an active connection to a resource specified by a URL

URLConnection

instance

URLConnection has 7 ___ fields: URL url boolean doInput= true boolean doOutput=false boolean allowUserInteraction= defaultAllowUserInteraction boolean useCaches = defaultUseCaches long isModifiedSince = 0 boolean connected = false

guessContentTypeFromStream

URLConnection.___(InputStream in) looks at the first few bytes of data in a connection to guess the content type.

guessContentFromName

URLConnection.___(String Name) uses the extension to guess the file time returns a string looks at content-type properties file

MIME guessing

URLConnection.guessContentTypeFromName() URLConnection.guessContentTypeFromStream()

The corresponding ___ class has a static ___ method that decodes strings encoded in x-www-form-url-encoded format. That is, it converts all plus signs to spaces and all percent escapes to their corresponding character.

URLDecoder decode( )

URL Encoder

URLEncoder.encode(String, Format); Convert a string to the specified encoding.

Are URLs thread safe?

URLs are thread safe and immutable.

Java's native character set

UTF-16

Java's native character set is the

UTF-16 encoding of unicode

451

Unavailable For Legal Reasons

URI

Uniform Resource Identifier.

getByAddress throws the exception ___ only if a byte array of an illegal size (neither 4 nor 16 bytes long) is passed as the address argument.

UnknownHostException

422

Unprocessable Entity

Although OutputStream takes an int as an argument, it actually writes an -

Unsigned byte

415

Unsupported Media Type

426

Upgrade Required

What is an alternative to synchronization?

Use fields instead of local variables whenever possible is an alternative to synchronization.

Which is not an alternative to synchronization?

Use fields instead of local variables wherever possible

Filters are connected to streams

by their constructors

Note: unsolicited submission by a W3C member. Working drafts: reflection of current thinking of some members of a working group. Candidate recommendation: working group has reached a consensus on all major issues. Proposed recommendation: mostly complete and not likely to undergo more than minor changes. Recommendation: highest level and is a work that represents consensus within W3C and has the directors stamp of approval.

W3C 5 basic levels of standards

What is on port 43?

WHOIS. It is a simple directory service for Internet network administrators.

___ releases the lock on the object and pauses until it is notified by some other thread.

Waiting

preemptive, cooperative

What are the two types of thread scheduling?

Initiate communication

What describes the role of a client?

It releases resources.

What does invoking the close() method do for streams?

java.io.OutputStream class

What does the writer class mirror?

ConnectionException

What exception is thrown when a connection is refused at the remote host.

Packets can be checked for damages in transit using checksums.

What is the advantage of breaking data into packets over a network?

To efficiently use available resources

What is the purpose of threading?

synchronized()

What is used to ensure that a single thread is finished before proceeding to the next thread in multi-threading?

Filter streams

What should be chained to an output stream to convert an int to bytes and write those bytes to an underlying output stream?

Waking from sleep is not guaranteed

When a Thread.Sleep() is used, there is no guarantee that the thread will wake on time. When the appointed time comes around, the VM may be too busy to immediately wake the thread. Also, another thread could use interrupt() on the sleeping thread to wake it early.

Blocked state:

When a thread executes the sleep(), wait(), or join() methods, when a thread attempts to read data not yet available from a network, and when a thread waits to acquire a lock, that thread is in the blocked state: it is neither running nor in a position to run

What is a race condition?

When two threads would consume the same resource and it is unclear which thread will claim that resource. - It is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time, but because of the nature of the device or system, the operations must be done in the proper sequence to be done correctly.

prefixes

Whois ___: domain gateway group handle or ! expand or * summary or $ host network organization mailbox or @ full or = subdisplay or % person ASN (autonomous system number) name or : partial or suffix.

Once created, a string object is immutable.

Why are string arguments safe from deadlock?

BufferedStreams

Write data to a buffer until it reaches a specified size and then writes to the Stream's target source. Can improve performance.

What can be buffered, either directly or chained to BufferedWriter?

Writers

What is never used directly, but used polymorphically?

Writers

What mirrors the java.io.OutputStream class?

Writers

System.out

Writing to the console through several System.out.print() statements may not finish in one thread prior to the next utilizing System.out which can cause text to become garbled as different threads mix their outputs. - is a PrintStream

Is HTTP closely related to the URLConnection class?

Yes

is java.net.URLConnection abstract?

Yes it is abstract. To implement, you write a subclass.

Is 209:117:62:36:8080 a valid IPv4 address?

Yes,

Does the InetAddress cache results of lookups?

Yes, the InetAddress class caches the result of lookups in an effort to speed up requests.

What does this code demonstrate? public void run() { while (true) { // Do the thread's work... Thread.yield( ); } }

Yielding

Sleeping vs Yielding

Yielding is the process's willingness to pause and let another equal-priority thread run, but sleeping is more powerful. A sleeping thread will pause regardless of weather or not other threads need to operate. Its like stopping at a 4 way stop sign when no one is around. Sleeping threads hold their locks.

Synchronizing a method

You can synchronize a method using 'synchronized' in the method declaration. EX: public synchronized void methodName(){}

How do you build a reference to a NetworkInterface?

You can't arbitrarily create a NetworkInterface object since they can refer to actual hardware. You get a NetworkInterface by using the .getByName(""), getByInetAddress(""), getNetworkInterfaces()

synchronizing their task by using synchronized blocks...

You keep shared resources within this block

What is true about using the GET method?

You need to know the combination of names and values the program expects to receive

What is the problem with assigning too high a priority to a thread?

You run the risk of starving other, lower priority threads.

What is the most common way to create a URLConnection object?

You use the .openConnection() method from the URL object to return a URLConnection for a specific URL.

How do you create a new Object that reperesnts an IP? or an internet address?

You use the InetAddress class, here is an example: InetAddress address = InetAddress.getByName("www.oreilly.com");

echo protocol

___ ___ is to test the network to make sure data is not being destroyed by a faulty router

thread scheduling

___ ___ policies make sure threads get at least some time to run more important things get more time avoid thread starvation assign priorities to threads VM runs the highest priority thread first Java: 10 highest, 0 lowest Unix: 0 highest, 10 lowest

Cache record

___ ___ should contain: timestamp client address specific information about requests if exists exception error

HTTP 2.0

based on SPDY invented by Google, optimizes HTTP transfers through header compression, pipe-lining request responses and asynchronous connection multiplexing

URL

___ connections: provide more control over interaction with a server can inspect header sent by server then respond accordingly set header field using client requests send data back to the web server with POST, PUT, and the like are part of the protocol handler's mechanism, which includes URLStreamHandler classes. Has separate details of processing from data type processing, providing user interfaces and other web browser work.

URL

___ has the following attributes a toString method a toExternalForm form that makes a string for the browser a toURI that throws URISyntaxException

URI

___ has the following attributes is about identifying resources and pausing data is more conformant to relevant specifications URI can represent a relative URI URL absolutizes all URIs before storing them

algorithms

___ have: a protocol a key exchange algorithm an encryption angorithm a checksum

Whois

___ protocol: 1)client opens a TCP socket to port 43 2)client sends a search string terminated by a carriage return 3)server sends an unspecified amount of human-readable information in response to the command then closes the connection 4)client displays information to the user

isBound

___ tells if the object has ever been bound to a port -returns true if the object has EVER been bound to a port.

printWriter

_____ replaces printStream

Scheme

a URI or URL's current ____ could include: data: base 64 encoded data included directly in the link file: a file located on a local disk FTP: a ftp server http: a www server using http mailto: an email address magnet: a resource available for download via peer-to-peer networks like Bit Torrent telnet: a connection to a telnet-based server urn: a unified resource name

a URI that has a scheme is an absolute URI whereas

a URI without a scheme is relative

parent doccument

a URL may inherit the protocol, hostname, and path of it's ___ ___

thread starvation

a VM that uses cooperative thread scheduling is more susceptible to ___ ___ than a VM that uses preemptive thread scheduling.

request log

a ___ ___ contains client errors like disconnects or malformed requests

InputStreamReader GZIPInputStream CipherInputStream BufferedInputStream TelnetInputStream

a compressed, encrypted text file arrives from the local network interface, where native code presents it to the undocumented TelnetInputStream. A BufferedInputStream buffers the data to speed up the entire process. A CipherInputStream decrypts the data. A GZIPInputStream decompresses the deciphered data. An InputStreamReader converts the decompressed data to Unicode text. Finally, the text is read into the application and processed.

URL Connection

a program that uses a ___ ___: constructs the URL object invokes the URL Object's openConnection() method Configures the URL connection gets the header file gets the input stream and reads the data gets the output stream and writes the data closes the connection

terminates

a server ___ when the client closes the connection

interrupt

a sleeping thread can be woken with

preemptive

a type of thread scheduling that determines when a thread has had a fair share of CUP time, pauses the thread, and hands off control of the CUP to another thread.

cooperative

a type of thread scheduling that waits for the running thread to pause itself before handing off control to a different thread.

What format is the data written in for a DataOutputStream?

big endian format

DataInputStream and DataOutputStream read and write in what format?

binary

class selector

binary values xxx000

javax.net

abstract socket factory classes used instead of constructors to create secure sockets

After a ServerSocket is created, what method is used to listen for incoming connections?

accept()

What method is run after instantiation of the server socket to listen for incoming connections?

accept() - blocks the client until attempts to make a connection at which point accept() returns a Socket object connecting the client to the server.

synchronize

action of multiple threads and make sure that only one thread can access the resource at a given point in time

Which method is not a member of the Reader class? read / active / skip / mark

active

run

all the work in the thread is done in this method. invokes other methods. constructs other objects. spawns threads. thread dies when complete. the main() of threaded programs.

pushbackReader

allows a character to be inserted back into the stream

Which InetAddress method returns true if the address is isSiteLocalAddress()

an IPv6 site-local address, false otherwise?

IRI

an Internationalized Resource Identifier easier to type and much easier to read, but a lot of software and protocols expect and support only ASCII URIs. If you don't hexadecimally encode non-ASCII characters like this, but just include them directly, then instead of a URI

Audit Log

an ___ ___ contains one entry for each connection made to the server one enter for each operation

Error log

an ___ ___ contains unexpected expectations that occur while the server was running things like NPEs

java.net.URL class

an abstraction of a Uniform Resource Locator such as http://www.lolcats.com/ or ftp://ftp.redhat.com/pub/. It extends java.lang.Object, and it is a final class that cannot be subclassed. Rather than relying on inheritance to configure instances for different kinds of URLs, it uses the strategy design pattern. Protocol handlers are the strategies, and the URL class itself forms the context through which the different strategies are selected. - you can construct instances

java.util.concurrent

an atomic class that is: thread safe but mutable. has atomic Integer, Long, etc. . Stores references to variables in atomic reference. sets and gets of reference variables are then thread safe.

Unlike the URL class, the URI class does not depend on

an underlying protocol handler. As long as the URI is syntactically correct, Java does not need to understand its protocol in order to create a representative URI object. Thus, unlike the URL class, the URI class can be used for new and experimental URI schemes.

.getHostAdress() returns

and IPV4 address

GET

any page accessed with ___ should be cached.

JPasswordField

anything that the user types echoes and asterisk. i.e. password:*******

yes

are URLs immutable?

JVM threads

are green threads, or user threads, ____ divides its sole thread of execution into multiple threads. (not the underlying platform's operating system)

In public key (or ___ ) encryption, different keys are used to encrypt and decrypt the data.

asymmetric

.getLocalHost();

attempts to return a hostname, if it fails, returns the loopback address

hirearchical structure

authority/path?query#fragment is an example of what?

If you do not want to wait until all the bytes you need are immediately available, you can use the _____ method to determine how many bytes can be read without blocking.

available( )

How does Peer-To-Peer work in Java?

both sides act as the Client and Server - Java does not explicitly handle peer-to-peer connections

Getting the correct result when using threads can depend on what factors?

can depend on how many CPU's the system uses, the speed of the CPU, how many threads a program spawns, and the algorithm the JVM uses to allot time to different threads.

Filters

can modify the data as it's read or written

dispose pattern

catch, write to log, ignore

no-cache

chached, but must be re-verified on each access

Filters are organized in a

chain

Most of these methods behave the same for PrintWriter as they do for PrintStream. The exceptions are the four write( ) methods, which write ___ rather than ___;

characters , bytes

Not all inputStreams support marking and resetting, you should always do what? prior to trying to use mark and reset?

check whether the markSupported() method returns true.

The specific SecurityManager method used to test whether a host can be resolved is :

checkConnect( ) public void checkConnect(String hostname, int port)

-1

checks if a DNS connection can be invoked on the specific host.

URI resolved URI = absoluteURI.resolve(relativeURI);

combines a absolute URI + the relative URI

absolute URL

completely specified URL

InputStreamReader is the most _____________ subclass or Reader

concrete

openStream()

connects resource referenced by URL allows you to read from an InputStream

a socket

connects to a remote machine, send data, receive data, close a connection, bind to a port, listen for incoming data, accepts connections from remote machines on the bound port

URL

constructors for __ -public URL(string URL) throws MalformedURLException -public URL(String protocol, String hostname, String file) throws MalformedURLException -public URL(String protocol, String host, int port, String file) throws MalformedURLException -public URL(URL base, String relative) throws MalformedURLException

The SingleFileHTTPServer class holds the ___ to send, the ___ to send, and the ___ to bind to.

content, header, port

toURI() method

converts a URL object to an equivalent URI object: public URI toURI() throws URISyntaxException

Many websites use small strings of text known as ___ to store persistent client-side state between connections.

cookies

ASCII

cookies are limited to nonwhitespace ___ text

name-value

cookies have a _______ pair but also several attributes like: expiration date version path security options domain port

A ___ thread scheduler waits for the running thread to pause itself before handing off control of the CPU to a different thread.

cooperative

executor service

create an ____ ____ to create to create threads as needed. Submit callable jobs to it, then return a future for each one, then get the returned value from the service. Poll until it gives a value. This way you can spawn lots of threads and order the results.

What method would you use after instantiating the socket object to open the port?

createSocket(host,port); createSocket(host,port,interface,localPort); createSocket(host,port); createSocket(host,port,interface,localPort); createSocket(proxy, host, port, autoClose);

java doesn't natively support

data format (32-bit unsigned integers)

These write methods belong to ______ write boolean write byte write short write char write int write long write float write double write chars write bytes write UTF

dataOutputStream

Data is transmitted across the Internet in packets of finite size called ___.

datagrams

20

date tcp

13

daytime tcp/udp

However, it's also possible for two threads to be too careful, each waiting for exclusive access to resources it will never get. This can lead to ___, in which two threads are each waiting for resources the other possesses

deadlock

java 7 / try with resources

declare a stream inside an argument list of the try block

bidirectional TCP protocol dict

defined in RFC 2229

.getAddress() allows to look at raw bytes of an IP address to...

determine if it is IPv4 or IPv6

public boolean isOpaque()

determine if the URI is hierarchical or non-hierarchical

What is on port 2628?

dict. It is a UTF-8 encoded dictionary service that provides definitions of words.

URLConnection

differences between URL and ______: ____ provides access to the HTTP header. ____ can configure request parameters set by the server ____ can write data to the server and read data from the server.

9

discard tcp/udp

Filters cannot...

disconnect from a stream; connection is permanent

constructor

don't start threads in the ___ because the object might not be initialized by the time the callback is done.

In java 6 or earlier it is wise to close a stream with a

finally block

OSPF

finds the fastest route and distributes this information to all routers on the segment

What is on port 79?

finger. It is a service that returns information about a user or users on the local system.

What method pushes all the data to the other end of the pipe even if the byte size is not big enough to send?

flush( )

What forces the stream to print the buffer, but does not close the stream?

flush()

What should you do to all streams before you close them?

flush()

Which of the following methods forcefully breaks the deadlock to send the buffered stream data even if the buffer isn't yet filled?

flush()

breaks deadlocks by forcing the buffered stream to send its data even if the buffer isn't full.

flush()

What method forcefully breaks the deadlock to sent the buffered stream data even if the buffer isn't yet filled?

flush().

21

ftp tcp

If, for some reason, you need all the addresses of a host, call the ___ method, which returns an array of all the addreses.

getAllByName( )

Using the URI "abc://admin:[email protected]:1234/path/data ?key=value&key2=value2#fragid1" What method would return the authority, and what would it return?

getAuthority( ); admin:[email protected]

What returns a NetworkInterface object representing the network interface bound to the specified IP address?

getByInetAddress()

Which NetworkInterface method returns a NetworkInterface object representing the network interface bound to the specified IP address?

getByInetAddress()

Which NetworkInterface method returns a NetworkInterface object representing the network interface bound to the specific IP address? getNetwork() getNetworkInterfaces() getByInetAddress() getByName()

getByInetAddress() is the NetworkInterface method that returns a NetworkInterface object representing the network interface bound to the specific IP address.

Which InetAddress method connects to a DNS server to resolve a hostname?

getByName

Which InetAddress method connects to a DNS server to resolve a hostname? getDNS() resolveName() getByName() getIPName()

getByName() is the InetAddress method that connects to a DNS server to resolve a hostname.

The ___ method calls DNS if it can, and may replace the existing cached hostname.

getCanonicalHostName( )

If the server does not use MIME headers or sends an unfamiliar Content-type, ___ returns some sort of InputStream with which the data can be read.

getContent() public final Object getContent(Class[ ] classes) throws IOException

The ___ method returns a String that tells you how the content is encoded.

getContentEncoding( )

It returns a string that tells you how the content is encoded.

getContentEncoding()

The ___ method tells you how many bytes there are in the content.

getContentLength( )

Which are methods for retrieving specific header fields?

getContentType() getContentLength() getContentEncoding()

Retrieving Specific Header Fields

getContentType() It returns the MIME media type of the response body. getContentLength() It tells how many bytes there are in the content. getLastModified() It returns the date on which the document was last modified. getDate() Returns a long that tells you when the document was sent, in milliseconds since midnight, Greenwich Mean Time (GMT), January 1, 1970. getContentEncoding() It returns a string that tells you how the content is encoded.

You can retrieve the store in which the CookieManager saves its cookies with the ___ method:

getCookieStore( ) Code: CookieStore store = manager.getCookieStore();

The ___ method returns a long that tells you when the document was sent, in milliseconds since midnight, Greenwich Mean Time (GMT), January 1, 1970.

getDate( )

Returns a long that tells you when the document was sent, in milliseconds since midnight, Greenwich Mean Time (GMT), January 1, 1970.

getDate()

___ returns a long indicating the number of milliseconds after 12:00 A.M., GMT, January 1, 1970, at which the document expires

getExpiration( )

Read-only access to these parts of a URL is provided by nine public methods:

getFile(), getHost(), getPort(), getProtocol(), getRef(), getQuery(), getPath(), getUserInfo(), and getAuthority()

Using the URI "abc://admin:[email protected]:1234/path/data ?key=value&key2=value2#fragid1" What method would return the fragment, and what would it return?

getFragment( ); fragid1

The ___ method returns the value of a named header field.

getHeaderField( ) Example: String contentType = uc.getHeaderField("content-type");

client server

getHeaderFieldKey() and GetHeaderField() get the HTTP header sent from ___ to ___

InetAdress getter methods

getHorstName() getCanonicalHostName() getAddress() getHostAddress()

Which of the following methods returns a string containing the dotted quad format of the IP address?

getHostAddress()

Which of the following methods returns a string containing the dotted quad format of the IP address? getAddress() isAnyLocalAddress() getHostAddress() getLocalHost()

getHostAddress() returns a string containing the dotted quad format of the IP address.

The ___ method returns a String that contains the name of the host with the IP address represented by this InetAddress object.

getHostName( )

Observe the given Java code: InetAddress address = InetAddress.getByName(ip); System.out.println(address._____); What is the appropriate method that should be used in this code to print out DNS resolution?.

getHostName()

The ___ and ___ methods tell you the remote host and port the Socket is connected to; or, if the connection is now closed, which host and port the Socket was connected to when it was connected.

getInetAddress( ) getPort( )

Which of the following methods tells that the remote host socket is connected to which port?

getInetAddress()

The ___ method returns a java.util.Enumeration containing an InetAddress object for each IP address the interface is bound to.

getInetAddresses( )

Which method returns an Enumeration with all or a subset of the InetAddresses bound to a network interface?

getInetAddresses()

What method is used to communicate with the client?

getInputStream(); and getOutputStream();

___ returns the date on which the document was last modified.

getLastModified( )

The ___ and ___ methods tell you the network interface and port the Socket is connected from.

getLocalAddress( ) getLocalPort( )

Which InetAddress method returns an InetAddress object for the host on which your code is running?

getLocalHost

The ___ method returns an InetAddress object for the host on which your code is running:

getLocalHost( )

The ___ method returns the name of a particular NetworkInterface object, such as eth0 or lo.

getName( )

Which NetworkInterface returns a java.util.Enumeration listing all the network interfaces on the local host?

getNetworkInterfaces()

The ___ method returns an OutputStream on which you can write data for transmission to a server.

getOutputStream( )

Socket Class methods

getOutputStream() Returns an output stream for this socket.

Using the URI "abc://admin:[email protected]:1234/path/data ?key=value&key2=value2#fragid1" What method would return the path, and what would it return?

getPath( ); /path/data

URLConnection

gives you access to everything sent by the server: in addition to the document itself in its raw form (e.g., HTML, plain text, binary image data), you can access all the metadata specified by the protocol. For example, if the scheme is HTTP or HTTPS, the URLConnection lets you access the HTTP headers as well as the raw HTML. The URLConnection class also lets you write data to as well as read from a URL —for instance, in order to send email to a mailto URL or post form data.

Whereas yielding indicates only that a thread is willing to pause and let other equal-priority threads have a turn, a thread that ___ will pause whether any other thread is ready to run or not.

goes to sleep

readers writers

handle special cases of text in encodings, like UTF-8 and ISO 8859-1

ftp://mp3:[email protected]:33/VanHalen-Jump.mp3

has the authority mp3:[email protected]:33. This authority has the username mp3, the password mp3, the host ci43198-a.ashvil1.nc.home.com, and the port 33. It has the scheme ftp and the path /VanHalen-Jump.mp3. (In most cases, including the password in the URI is a big security hole unless, as here, you really do want everyone in the universe to know the password.)

Every filter input stream

has the same read(), close(), and available methods as java.io.InputStream

Every filter output stream

has the same write(), close() and flush() methods as java.io.OutputStream

The URI http://www.powells.com/cgibin/ biblio?inkey=62-1565928709-0

has the scheme http, the authority www.powells.com, the path /cgi-bin/biblio, and the query inkey=62-1565928709-0. The URI urn:isbn:156592870 has the scheme urn but doesn't follow the hierarchical //authority/ path?query form for scheme-specific parts.

The ___ contains the address and port to which the packet is going, the address and port from which the packet came, a checksum to detect data corruption, and various other housekeeping information used to ensure reliable transmission. The ___ contains the data itself.

header payload

a datagram contains

header + payload

SingleFileHTTPServer

hold the content to send, the header to send and the port to bind to

Which of the following fields define the state of a Whois object?

host and port

which defines the state of a Whois object?

host and port

content encoding

how bytes are encoded in other bytes

thread or runnable

how do objects register interest in the result of a callback method.

openConnection()

how do you create a URL object in the URL class?

2

how many isReachable() methods does InetAddress have? These methods test if a node is reachable from the current host. They check for proxy servers, firewalls, misbehaving routers, etc use traceroute to find out if the specified address is reachable if the host responds within the timeout, the methods return true, otherwise they return false. - how many protected constructors does java.io.outputStream have?

3 (char[] text, int offset, int length)

how many parameters does the base write method of java.io.outputStream take?

2

how many protected constructors does java.io.outputStream have?

0 (it has a static factory method that connects to a DNS server) algorithms

how many public constructors does inetAddress have?

when a host must not use a proxy and must connect directly instead

http.nonProxyHosts

To refer to this point, a URL includes not only the document's filename but the fragment identifier separated from the rest of the URL by a #:

http://www.cafeaulait.org/javafaq.html#xtocid1902914

While browsing http://www.company.com/history/projects, a user clicks on a link for < a href="/founders/johnsmith/">. Which URL would the user be redirected to?

http://www.company.com/founders/johnsmith/

Given https://www.company.com/current/sfs/index.html?isbn=44322#toc What is the protocol?

https

default protocol

if URL(String protocol, String host, int port, String file) sets the port to -1, which protocol will be used?

call back

if more than one object wants the result of a calculation, the thread can keep a list of objects to ___ ___.

IOException

if the call to openConnection() fails, what is thrown by the network?

143

imap tcp

URLs are

immutable. After a URL object has been constructed, its fields do not change. This has the side effect of making them thread safe.

How to make a class callable

implement Callable<Object> for example, implement Callable<Integer>

What is an import statement that will import InetAddress?

import java.net.*;

The ___ method returns true if the address is a wildcard address, false otherwise.

isAnyLocalAddress( )

Which InetAddress method returns true if the address is a wildcard address, false otherwise?

isAnyLocalAddress()

The parts of a URL

import java.net.*; public class URLSplitter { public static void main(String args[]) { for (int i = 0; i < args.length; i++) { try { URL u = new URL(args[i]); System.out.println("The URL is " + u); System.out.println("The scheme is " + u.getProtocol()); System.out.println("The user info is " + u.getUserInfo()); String host = u.getHost(); if (host != null) { int atSign = host.indexOf('@'); if (atSign != -1) host = host.substring(atSign+1); System.out.println("The host is " + host); } else { System.out.println("The host is null."); } System.out.println("The port is " + u.getPort()); System.out.println("The path is " + u.getPath()); System.out.println("The ref is " + u.getRef()); System.out.println("The query string is " + u.getQuery()); } catch (MalformedURLException ex) { System.err.println(args[i] + " is not a URL I understand."); } System.out.println(); } } }

finally block

in Java 6 and earlier, it's wise to close the stream in a finally block.

in java 7 Socket implements autocloseable where as...

in java 6 and earlier is necessary to use a finally statement

HTTP header

includes information about content and content encoding

writeUTF()

includes length of string Encodes the string itself in a variant of the UTF-8 encoding of Unicode incompatible with most non-java software

NullPointerException

indicates a bug in the server that needs to be fixed.

getUseClientMode()

indicates whether this socket will use authentication in its first handshake

UnknownHostException

inetAddress.getByAddress() throws this if a byte array of an illegal size is passed as the address argument.

What does the 1XX line of HTTP response codes represent?

informational 100 - Continue 101 - Switching Protocols

a client...

initiates communication

Given the URI, http://www.powells.com/cgi-bin/biblio?inkey=62-1565928709-0, what is the query portion?

inkey=62-1565928709-0

Filter streams can be chained to either a ___ or a ___

input stream, output stream

setDefault

install the subclass of ResponseCache by passing it to ResponseCache.___()

test for the type of the returned object using

instanceof

How do you convert a signed byte to an unsigned byte?

int i = b >= 0 ? b : 256 + b;

java.io.inputStream

int read() reads a single byte of data from the input stream and returns an int from 0 to 255 int read(byte [] input) int read(byte [] input, int offset, int length) long skip(long n) boolean available() close()

HTTP 500

internal server error

Callback

invoking a method in the main class that started it

The getPath() method

is a near synonym for getFile(); that is, it returns a String containing the path and file portion of a URL. However, unlike getFile(), it does not include the query string in the String it returns, just the path.

a URL object

is a representation of an application layer protocol for network retrieval, whereas a URI object is purely for string parsing and manipulation. The URI class has no network retrieval capabilities. The URL class has some string parsing methods, such as getFile() and getRef(), but many of these are broken and don't always behave exactly as the relevant specifications say they should. Normally, you should use the URL class when you want to download the content at a URL and the URI class when you want to use the URL for identification rather than retrieval, for instance, to represent an XML namespace. When you need to do both, you may convert from a URI to a URL with the toURL() method, and from a URL to a URI using the toURI() method.

The syntax of a URI

is composed of a scheme and a scheme-specific part, separated by a colon, like this: scheme:scheme-specific-part

getInetAddress() tells about the remote host socket

is connected to or if the connection is closed then to which host socket was connected to when it was connected.

java.net.Socet

is java's fundamental class for performing client-side TCP operations

println()

is platform dependent

URL class

is the simplest way for a Java program to locate and retrieve data from the network. - abolutizes all the URIs before storing them

The getContent() method

is the third way to download data referenced by a URL. This method retrieves the data referenced by the URL and tries to make it into some type of object.

The ___ method returns true if the URI is absolute, false if it's relative:

isAbsolute( )

Which InetAddress method returns true if the address is a wildcard address, false otherwise? isMulticastAddress() isAnyLocalAddress() isLoopbackAddress() isLinkLocalAddress()

isAnyLocalAddress() is the InetAddress method that returns true if the address is a wildcard address and false otherwise.

What is the method to check if a socket is closed?

isClosed() - returns true if closed, false if open

What is the method to check if a socket is connected?

isConnected() - returns true if socket has been connected

The ___ method returns true if the address is an IPv6 LINK-local address, false otherwise.

isLinkLocalAddress( )

The ___ method returns true if the address is the loopback address, false otherwise.

isLoopbackAddress( )

The ___ method returns true if the address is a global multicast address, false otherwise.

isMCGlobal( )

Which method returns true if the IPv6 address starts with FF0E?

isMCGlobal()

Which method returns true of the IPv6 address starts with FF0E?

isMCGlobal() returns true if the IPv6 address starts with FF0E.

The ___ method returns true if the address is a subnet-wide multicast address, false otherwise.

isMCLinkLocal( )

The ___ method returns true if the address is an interface-local multicast address, false otherwise.

isMCNodeLocal( )

The ___ method returns true if the address is an organization-wide multicast address, false otherwise.

isMCOrgLocal( )

The ___ method returns true if the address is a site-wide multicast address, false otherwise.

isMCSiteLocal( )

The ___ method returns true if the address is a multicast address, false otherwise.

isMulticastAddress( )

determine if a URL is hierarchical

isOpaque()

The ___ method returns true if the address is an IPv6 SITE-local address, false otherwise.

isSiteLocalAddress( )

How does PrintStream deal with the platform it's running on?

it assumes the default encoding of the platform it's running on.

How does PrintStream handle exceptions?

it eats them

Why should you not use polling to resolve a race condition?

it is not guaranteed to work

Socket Exension

java secure ___ ___ is devided into four packages java.net.ssl: -abstract classes that define java's API for secure network communication javax.net: -abstract socket factory classes used instead of constructors to create secure sockets java.security.cert -classes for handeling public-key certs for SSL com.sun.net.ssl -concrete class to implement encryption angorithims and protocols in suns reference implementation of JSSE

this package has fileReader fileWriter stringReader stringWriter charArrayWriter charArrayReader

java.io

What uses the 5 fundamental methods of OutputStream to write data into an expandable byte array?

java.io.ByteArrayOutputStream

What uses the 5 fundamental methods of OutputStream to write data into a file?

java.io.FileOutputStream

Java's basic input class

java.io.InputStream

Java's basic input class is

java.io.InputStream

The Reader class mirrors what class?

java.io.InputStream

basic java input class

java.io.InputStream

Java's basic output class

java.io.OutputStream

Java's output class

java.io.OutputStream

The Writer class mirrors what class?

java.io.OutputStream. Just like OutputStream, Writer is never used directly instead it is used via one of its subclasses.

What does the writer class mirror?

java.io.Outputstream.

Which class specified by the API by which characters are read?

java.io.Reader

jWhich class specified the API by which characters are read?

java.io.Reader

what does the java reader class mirror?

java.io.inputStream

what class do writer classes mirror

java.io.outputStream

A user logs into the e-mail client via the web GUI using the username and password. The user wants to ensure that credentials are not easily obtainable by sniffing network traffic. Which class can be imported to create a secure socket?

javax.net.*

A user logs into the e-mail client via the web GUI using the username and password. The user wants to ensure that credentials are not easily obtainable by sniffing network traffic. Which class can be imported to create a secure socket?

javax.net.*

What class can be imported to create secure sockets?

javax.net.* can be imported

SSL-enabled server sockets

javax.net.SSLServerSocket

Secure client sockets are only half of the equation. The other half is SSL-enabled server sockets. These are instances of the ___ class.

javax.net.SSLServerSocket

Which is a package is the Java Secure Socket Extension?

javax.net.ssl javax.net java.security.cert

Java Secure Socket Extension

javax.net.ssl This package provides classes for the secure socket package. javax.net This package provides classes for networking applications. These classes include factories for creating sockets. java.security.cert This package provides classes and interfaces for parsing and managing certificates, certificate revocation lists (CRLs), and certification paths. com.sun.net.ssl This package provides classes that implement the encryption algorithms and protocols in Sun's reference implementation of the JSSE.

join(), join(long milliseconds), join(long milliseconds, int nanoseconds)

join() waits indeterminately to join. the other two join methods wait for their specified times and then proceed regardless of the join outcome.

Which is not a way to wake up a thread?

joining it with another thread

The ___ method returns a String containing the whois response to a given query.

lookUpNames( )

iterative servers

loop through program code so that every time the progam ends or a socket closes, it starts again. This works well for simple clients.

TCP defines four general traffic classes

low cost high reliability maximum throughput minimum delay

Which method is returned when a single thread program exits?

main()

mark() and reset()

mark a position in the stream and reset to the marked position using these methods, if not supported. reset will throw an IOException

What three methods allow programs to re-read data?

mark( ) reset( ) markSupported( )

How do you set the current position of the stream?

mark()

primitive

method arguments of ___ types are thread safe because they are passed by value. These methods should be declared static.

POST

method, most general method. uploads a representation of a resource to a server at a known URL. should be used for unsafe operations, such as making a purchase. Uploads a representation of a resource to a server at a known URL but does not specify what the server is to do with the newly supplied resource.

Construct a URL object. Invoke the URL object's openConnection() method to retrieve a URLConnection object for that URL. Invoke the URLConnection's getInputStream() method. Read from the input stream using the usual stream API.

minimal set of steps needed to retrieve data from a URL using an URLConnection object:

what does sleep(mS) do for threading?

more powerful than yielding

internet host

most current examples of URIs use an ___ ___ as an authority

is MCLinkLocal()

multicast, starts with FF02 or FF12

is MCSiteLocal()

multicast, starts with FF05 or FF15

is MCGlobal()

multicast, starts with FF0E or FF1E

Assured forwarding AF

multiple binary values

JavaMail Transport objects

need to be disposed explicitly

fileOutputStream

needs to use native code to write data files to the host program

119

nntp tcp

Can filters be disconnected from the stream?

no

Does BufferedOutputStream declare any of it's own methods?

no

no-sotore

no chache entry will be stored

Should PrintStream be used for network connections?

no, it is too unreliable

What is the basic InputStream method?

noargs read( )

basic method of InputStream

noargs read() method

equals()

on a URL is potentially a blocking I/O operation! For this reason, you should avoid storing URLs in data structure that depend on equals() such as java.util.HashMap. Prefer java.net.URI for this, and convert back and forth from URIs to URLs when necessary.

pool.shutdown()

once all files are in a pool, you can call ___.___ this doesn't abort the pending jobs this notifies the pool that no additional tasks are to be added.

URLs are immutable, meaning:

once constructed, fields do not change, making them thread safe

if multiple threads try to write within a same file then they may corrupt the data because

one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file

common object

one way to use synchronization to create a thread safe program is to pick a ___ ___ to synchronize everything on, that way everything must run in series.

commit

only ___ operations should use post

The ___ method opens a socket to the specified URL and returns a URLConnection object.

openConnection( );

HTTP 1.0

opens a new connection for each request

openConnection()

opens a socket to the specified URL and returns a URLConnection object

getContent()

operates by looking at the Content-type field in the header of the data it gets from the server. If the server does not use MIME headers or sends an unfamiliar Content-type, getContent() returns some sort of InputStream with which the data can be read. An IOException is thrown if the object can't be retrieved.

ASCII

output stream is passed this to generate characters() in out.

POST

pages accessed with ___ should never be cached.

NetworkInterface object represents

physical hardware and virtual addresses

SO_KEEPALIVE

pings the server every 2 hours to make sure it has not crashed

println() line seperator

platform dependent so its not good for networking where you need consistency.

110

pop3 tcp

form

post data to a ___ by: decide the name-value pairs to send to the serverside program write the serverside program to accept and process requests create a query string in the Java program and pass each name and value in the string to URLEncoder.encode() Open URLConnection to the URL of the program that will accept the data set doOutput to true via setDoOutput(true) write a query string onto URLConnection's outputStream close URLConnection's outputStream read the server response from URLConnection's inputSTream

A ___ thread scheduler determines when a thread has had its fair share of CPU time, pauses that thread, and then hands off control of the CPU to a different thread.

preemptive

what PrintStream method is platform independent?

println()

A JVM's thread scheduler schedules green threads according to

priority

Reader methods

protected Reader() protected Reader(Object lock) public abstract int read(char[] text, int offset, int length) throws IOException public int read() throws IOException public int read(char[] text) throws IOException public long skip(long n) throws IOException public boolean ready() public boolean markSupported() public void mark(int readAheadLimit) throws IOException public void reset() throws IOException public abstract void close() throws IOException

What are the 5 fundamental methods and the close and flush methods of Writer class?

protected Writer( ) protected Writer(Object lock) public abstract void write(char[ ] text, int offset, int length) throws IOException public void write(int c) throws IOException public void write(char[ ] text) throws IOException public void write(String s) throws IOException public void write(String s, int offset, int length) throws IOException public abstract void flush( ) throws IOException public abstract void close( ) throws IOException

Writer methods

protected Writer()protected Writer(Object lock) public abstract void write(char[] text, int offset, int length) throws IOException public void write(int c) throws IOException public void write(char[] text) throws IOException public void write(String s) throws IOException public void write(String s, int offset, int length) throws IOException public abstract void flush() throws IOException public abstract void close() throws IOException

Know the parts of a URL

protocol://authority:port/path?query#fragment

Know the parts of the URI

protocol://authority:port/path?query#fragment

Components of URL

protocol://userInfo@host:port/path?query#fragment The host part of a URL is the name of the server that provides the resource you want. It can be a hostname such as www.ucertify.com or www.jigyaasa.net or an IP address, such as 204.148.40.9 or 128.238.3.21. The userInfo is optional login information for the server. If present, it contains a username and, rarely, a password. The port number is also optional. It's not necessary if the service is running on its default port (port 80 for HTTP servers). Here, the protocol is another word for what was called the scheme of the URI. In a URL, the protocol part can be file, ftp, http, https, magnet, telnet, or various other strings. The path points to a particular resource on the specified server. The query string provides additional arguments for the server. It's commonly used only in http URLs, where it contains form data for input to programs running on the server. Finally, the fragment references a particular part of the remote resource. If the remote resource is HTML, the fragment identifier names an anchor in the HTML document. If the remote resource is XML, the fragment identifier is an XPointer.

DataInputStream and DataOutputStream

provide methods for reading and writing Java's primitive data types and strings in a binary format. The binary formats used are primarily intended for exchanging data between two different Java programs through a network connection, a datafile, a pipe, or some other intermediary. read and write in a binary format -Intended for exchanging data between two Java programs through network connection, a datafile, a pipe, or some other intermediary -All data is written in big-endian format

What acts as go-between restricting connections or forwarding them along?

proxy server

What filters traffic like firewalls, but generally operate at the application layer?

proxy server

What are the constructors for BufferedInputStream?

public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream in, int bufferSize) *BufferedOutputStream is the same, essentially

BufferedReader and BufferedWriter constructors

public BufferedReader(Reader in, int bufferSize) public BufferedReader(Reader in) public BufferedWriter(Writer out) public BufferedWriter(Writer out, int bufferSize)

Retrieving Data from a URL

public InputStream openStream() throws IOException public URLConnection openConnection() throws IOException public URLConnection openConnection(Proxy proxy) throws IOException public Object getContent() throws IOException public Object getContent(Class[] classes) throws IOException

The URL class has several methods that retrieve data from a URL:

public InputStream openStream() throws IOException public URLConnection openConnection() throws IOException public URLConnection openConnection(Proxy proxy) throws IOException public Object getContent() throws IOException public Object getContent(Class[] classes) throws IOException

What is the constructor for PasswordAuthentication?

public PasswordAuthentication(String userName, char[] password)

Which is a constructor for the PasswordAuthentication class?

public PasswordAuthentication(String userName, char[] password)

This constructor creates an unconnected socket that connects through a specified proxy server:

public Socket(Proxy proxy)

Socket Contructors

public Socket(String host, int port, InetAddress interface, int localPort) throws IOException, UnknownHostException public Socket(InetAddress host, int port, InetAddress interface, int localPort) throws IOException. This socket connects to the host and port specified in the first two arguments. It connects from the local network interface and port specified by the last two arguments. The network interface may be either physical (e.g., an Ethernet card) or virtual (a multihomed host with more than one IP address). If 0 is passed for the localPort argument, Java chooses a random available port between 1024 and 65535. By passing 0 for the local port number, I say that I don't care which port is used but I do want to use the network interface bound to the local hostname router.

getContentType

public String ___() returns the MIME media type of the response body throws no exceptions, and returns null if the content type isn't available.

getHeaderField

public String ___(String name): returns the value of the named header field is not case sensitive does not require a closing colon, returns a String.

InetAddress Class

public String getHostName() The getHostName() method returns a String that contains the name of the host with the IP address represented by this InetAddress object public String getCanonicalHostName() getCanonicalHostName() calls DNS if it can, and may replace the existing cached hostname. public byte[] getAddress() If you want to know the IP address of a machine (and you rarely do), then use the getAddress() method, which returns an IP address as an array of bytes in network byte order. public String getHostAddress() The getHostAddress() method returns a string containing the dotted quad format of the IP address.

If you want the raw, encoded parts of the URI, there are five parallel getRaw_Foo_() methods:

public String getRawAuthority( ) public String getRawFragment( ) public String getRawPath( ) public String getRawQuery( ) public String getRawUserInfo( )

What methods access a username and password?

public String getUserName( ); public char[] getPassword( );

You can call ___ to force the authority to be reparsed:

public URI parseServerAuthority() throws URISyntaxException

The URI class has three methods for converting back and forth between relative and absolute URIs:

public URI resolve(URI uri) public URI resolve(String uri) public URI relativize(URI uri)

Java.net.URI Constructing a URI

public URI(String uri) throws URISyntaxException public URI(String scheme, String schemeSpecificPart, String fragment) throws URISyntaxException public URI(String scheme, String host, String path, String fragment) throws URISyntaxException public URI(String scheme, String authority, String path, String query, String fragment) throws URISyntaxException public URI(String scheme, String userInfo, String host, int port, String path, String query, String fragment) throws URISyntaxException

URIs are built from strings. You can either pass the entire URI to the constructor in a single string, or the individual pieces:

public URI(String uri) throws URISyntaxException public URI(String scheme, String schemeSpecificPart, String fragment) throws URISyntaxException public URI(String scheme, String host, String path, String fragment) throws URISyntaxException public URI(String scheme, String authority, String path, String query, String fragment) throws URISyntaxException public URI(String scheme, String userInfo, String host, int port, String path, String query, String fragment) throws URISyntaxException

openConnection

public URL connection ___(proxy proxy) throws IOException if no proxies are supported, this proxy is ignored.

List the java.net.URL constructors

public URL(String url) throws MalformedURLException public URL(String protocol, String hostname, String file) throws MalformedURLException public URL(String protocol, String host, int port, String file) throws MalformedURLException public URL(URL base, String relative) throws MalformedURLException

Java.net.URL Constructing a URL

public URL(String url) throws MalformedURLException public URL(String protocol, String hostname, String file) throws MalformedURLException public URL(String protocol, String host, int port, String file) throws MalformedURLException public URL(URL base, String relative) throws MalformedURLException

java.net.URL Constructor

public URL(String url) throws MalformedURLException public URL(String protocol, String hostname, String file) throws MalformedURLException public URL(String protocol, String host, int port, String file) throws MalformedURLException public URL(URL base, String relative) throws MalformedURLException

URL

public ___(URL base, String relative) throws MalformedURLException makes an absolute URL out of a relative URL

get

public abstract CacheResponse ___(URI uri, String requestMethod, map <String, list<String>> requestHeaders) throws IOException and public abstract CacheRequest get(URI uri, URLConnection connection) throws IOException are both methods to store and retrieve data from the system's single cache. put returns a cacheRequest object that wraps an OutputStream into which the URL will write cacheable data .

Which is an overloaded createSocket() method to build an SSLSocket?

public abstract Socket createSocket(String host, int port) throws IOException, UnknownHostException public abstract Socket createSocket(InetAddress host, int port) throws IOException public abstract Socket createSocket(String host, int port, InetAddress interface, int localPort) throws IOException, UnknownHostException

Overloaded constructors for SSLSocketFactory

public abstract Socket createSocket(String host, int port) throws IOException, UnknownHostException public abstract Socket createSocket(InetAddress host, int port) throws IOException public abstract Socket createSocket(String host, int port, InetAddress interface, int localPort) throws IOException, UnknownHostException public abstract Socket createSocket(InetAddress host, int port, InetAddress interface, int localPort) throws IOException, UnknownHostException public abstract Socket createSocket(Socket proxy, String host, int port, boolean autoClose) throws IOException

createSocket Methods

public abstract Socket createSocket(String host, int port) throws IOException, UnknownHostException public abstract Socket createSocket(InetAddress host, int port) throws IOException public abstract Socket createSocket(String host, int port, InetAddress interface, int localPort) throws IOException, UnknownHostException public abstract socket createSocket(InetAddress host, int port, InetAddress interface, int localPort) throws IOException, UnknownHostException public abstract Socket createSocket(Socket proxy, String host, int port, boolean AutoClose) throws IOExceptions. tunnels through the proxy server to the specified host and port.

The ___ method in SSLSocketFactory tells you which combination of algorithms is available on a given socket

public abstract String[ ] getSupportedCipherSuites( )

The ___ method returns true if multisocket sessions are allowed, false if they're not.

public abstract boolean getEnableSessionCreation( )

The ___ method tells you whether the particular HttpURLConnection is going through a proxy server:

public abstract boolean usingProxy( )

The java.net package includes the ___ class you can use to provide a username and password for sites that protect themselves using HTTP authentication:

public abstract class Authenticator extends Object

This class provides the fundamental methods needed to read data as raw bytes.

public abstract int read() throws IOException public int read(byte[] input) throws IOException public int read(byte[] input, int offset, int length) throws IOException public long skip(long n) throws IOException public int available() throws IOException public void close() throws IOException

java.io.InputStream

public abstract int read() throws IOException public int read(byte[] input) throws IOException public int read(byte[] input, int offset, int length) throws IOException public long skip(long n) throws IOException // skip over data without reading it. public int available() throws IOException public void close() throws IOException // releases any resources associated with the stream, such as file handles or ports. SubClasses FileInputStream ( read data from a file) TelnetInputStream ( read data from a network) ByteArrayInputStream (read data from an array of bytes)

The ___ method determines whether the socket needs to use authentication in its first handshake.

public abstract void setUseClientMode(boolean mode) throws IllegalArgumentException

OutputStream

public abstract void write(int b) throwsIOException public void write(byte[] data) throws IOException public void write(byte[] data, int offset, int length) throws IOException public void flush() throws IOException public void close() throws IOException

java.io.OutputStream contains the fundamental methods needed to write data

public abstract void write(int b) throwsIOException public void write(byte[] data) throws IOException public void write(byte[] data, int offset, int length) throws IOException public void flush() throws IOException public void close() throws IOException

java.io.OutputStream

public abstract void write(int b) throwsIOException public void write(byte[] data) throws IOException public void write(byte[] data, int offset, int length) throws IOException public void flush() throws IOException // breaks the deadlock by forcing the buffered stream to send its data even if the buffer isn't yet full. public void close() throws IOException // resources associated with the stream, such as file handles or ports. SubClasses --- FileOutputStream (write data to file) TelnetOutputStream (write data to the network) ByteArrayOutputStream (write data into expandable byte array)

Java includes 10 methods for testing whether an InetAddress object meets any of these criteria of a special or reserved IP address:

public boolean isAnyLocalAddress( ) public boolean isLoopbackAddress( ) public boolean isLinkLocalAddress( ) public boolean isSiteLocalAddress( ) public boolean isMulticastAddress( ) public boolean isMCGlobal( ) public boolean isMCNodeLocal( ) public boolean isMCLinkLocal( ) public boolean isMCSiteLocal( ) public boolean isMCOrgLocal( )

This method returns true if and only if the address is essentially an IPv4 address stuffed into an IPv6 container—which means only the last four bytes are nonzero.

public boolean isIPv4CompatibleAddress( )

These two methods attempt to use traceroute (more specifically, ICMP echo requests) to find out if the specified address is reachable and not blocked by a firewall or proxy.

public boolean isReachable(int timeout) throws IOException public boolean isReachable(NetworkInterface interface, int ttl, int timeout) throws IOException

The URL class also has a ____ method that checks whether two URLs point to the same resource:

public boolean sameFile(URL other)

openStream

public final InputStream __() connects to a resource referenced by a URL performs handshaking between the client and server returns an InputStream that data can be read from

getContent

public final Object ___() throws IOException operates by looking at the content type field in the header of the data it gets from the server. If the server doesn't use MIME headers or sends an unfimilliar content type, it returns an InputStream that the data can be read from. An IOException is thrown if the object can't be retrieved.

getContent

public final Object ___(class [] classes) lets you chose which class you want the content to be returned as. array positions are preferences.

DataInputStream

public final boolean readBoolean() throws IOException public final byte readByte() throws IOException public final char readChar() throws IOException public final short readShort() throws IOException public final int readInt() throws IOException public final long readLong() throws IOException public final float readFloat() throws IOException public final double readDouble() throws IOException public final String readUTF() throws IOException public final int read(byte[] input) throws IOException public final int read(byte[] input, int offset, int length) throws IOException public final void readFully(byte[] input) throws IOException public final void readFully(byte[] input, int offset, int length) throws IOException public final String readLine() throws IOException public final int readUnsignedByte() throws IOException public final int readUnsignedShort() throws IOException

Java uses two classes, ___ and ___, in order to distinguish IPv4 addresses from IPv6 addresses:

public final class Inet4Address extends InetAddress public final class Inet6Address extends InetAddress

Java provides three join() methods to allow one thread to wait for another thread to finish before continuing. These are:

public final void join() throws InterruptedException public final void join(long milliseconds) throws InterruptedException public final void join(long milliseconds, int nanoseconds) throws InterruptedException

What method is used to set up the priority for a thread?

public final void setPriority(int newPriority)

DataOutputStream

public final void writeBoolean(boolean b) throws IOException public final void writeByte(int b) throws IOException public final void writeShort(int s) throws IOException public final void writeChar(int c) throws IOException public final void writeInt(int i) throws IOException public final void writeLong(long l) throws IOException public final void writeFloat(float f) throws IOException public final void writeDouble(double d) throws IOException public final void writeChars(String s) throws IOException public final void writeBytes(String s) throws IOException public final void writeUTF(String s) throws IOException public final boolean readBoolean() throws IOException public final byte readByte() throws IOException public final char readChar() throws IOException public final short readShort() throws IOException public final int readInt() throws IOException public final long readLong() throws IOException public final float readFloat() throws IOException public final double readDouble() throws IOException public final String readUTF() throws IOException

What are the 11 methods of DataOutputStream?

public final void writeBoolean(boolean b) throws IOException public final void writeByte(int b) throws IOException public final void writeShort(int s) throws IOException public final void writeChar(int c) throws IOException public final void writeInt(int i) throws IOException public final void writeLong(long l) throws IOException public final void writeFloat(float f) throws IOException public final void writeDouble(double d) throws IOException public final void writeChars(String s) throws IOException public final void writeBytes(String s) throws IOException public final void writeUTF(String s) throws IOException

getLocalPort

public int ___() find out what port you are listening on returns -1 if ServerSocket has not yet been bound

getContentLength

public int ___(): shows how many bytes of data exist if there is no header for this field, -1 is returned. if the size exceeds the max int length, -1 is returned.

in asymmetric encryption

public key encrypts the data and the private key decrypts the data

The ___ method returns a java.util.Enumeration listing all the network interfaces on the local host.

public static Enumeration getNetworkInterfaces() throws SocketException

getByInetAddress

public static NetworkInterface ___(InetAddress address) throws SocketException returns a network interface object representing the network interface bound to the specific IP address.

getByName

public static NetworkInterface ___(String name) throws SocketException returns a NetworkInterface object representing the interface with a particular name if the underlying network stack encounters a problem while locating the relevant network interface, a SocketException is thrown

Guessing MIME Media Types

public static String guessContentTypeFromName(String name) This method tries to guess the content type of an object based upon the extension in the filename portion of the object's URL public static String guessContentTypeFromStream(InputStream in) This method tries to guess the content type by looking at the first few bytes of data in the stream

getNetworkInterfaces

public static enumeration ____() throws SocketException returns a java.util.enumeration with all local network interfaces on the local host.

What methods are used to invoke the Thread.sleep( ) method?

public static void sleep(long milliseconds) throws InterruptedException public static void sleep(long milliseconds, int nanoseconds) throws InterruptedException

The InputStream class has three less commonly used methods that allow programs to back up and reread data they've already read.

public void mark(int readAheadLimit) public void reset() throws IOException public boolean markSupported()

What new method does BufferedWriter( ) add?

public void newLine( ) throws IOException

Which of the following is a valid PrintStream method?

public void println()

By default, Java ignores urgent data received from a socket. However, if you want to receive urgent data inline with regular data, you need to set the OOBINLINE option to true using these methods:

public void setOOBInline(boolean on) throws SocketException public boolean getOOBInline() throws SocketException

As an alternative way to express preferences, the ___ method assigns relative preferences to connection time, latency, and bandwidth:

public void setPerformancePreferences( int connectionTime, int latency, int bandwidth);

Which method will allow Java to store IP addresses in an array by using an output stream?

public void write(byte[] a)

Which class of writers will write characters in an array?

public void write(char[] test)

Which is a method of the Writer class?

public void write(int c) throws IOException

How many threads the program spawns, the speed of the CPU and disk on the system where this is run, how many CPUs the system uses, and the algorithm the Java virtual machine uses to allot time to different threads are all called ___ conditions.

race

InputStream and OutputStream

read and write bytes singly or in groups, but that's all. Deciding what those bytes mean-whether they're integers or IEEE 754 floating-point numbers or Unicode text-is completely up to the programmer and the code.

The ____ method waits and blocks execution of any code that follows it until a byte of data is available and ready to be read.

read( )

inputStream

read() close() and available() in filters work with

what methods does any subclass of inputStream need to overwrite?

read, close

what should not be used as it is deprecated and buggy?

readLine()

You should never use which of DataInputStream's methods?

readLine() because it is depreciated and buggy.

TelnetInputStream

reads data from a network connection

ByteArrayInputStream

reads data from an array of bytes

outputStreamWriter

receives chars converts to bytes writes bytes to underlying outputStream

synchronized(objectidentifier)

reference to an object whose lock associates with the monitor that the synchronized statement represents synchronized(objectidentifier) { // Access shared variables and other shared resources }

The ___ method creates a new URI object from the uri argument that is relative to the invoking URI.

relativize( )

close() method

releases any resources associated with the stream such as file handlers and ports / if stream derives from a network connection; it closes the connection.

what does wait do for threading?

releases lock until notified by another thread

DELETE

removes a resource from an specified URL

PUT

replaces all current representations of the target resource with the uploaded content idempotent - it can repeat without concern if it fails. Uploads a representation of a resource to the server at a known URL.

what to log>

requests and server errors

reset()

reset the stream to marked position

how do you return the stream to the marked position?

reset()

If markSupported() returns false

reset() will throw IOException

The ___ methods compare the uri argument to this URI and use it to construct a new URI object that wraps an absolute URI.

resolve( )

com.sun.net.ssl.SSLContext

responsible for creating fully configured and initialized secure server sockets

header files

retrieved in specific ____ ____: Content type content length content encoding data last modified date expires

inetAddress.getLocalHost

returns InetAddress object for the host that the code is running on

what does the getLocalHost() method do in the InetAddress class?

returns InetAddress object(hostname) for the host that your code is running

getDocumentBase()

returns URL of the page that contains the applet

getByInetAddress()

returns a NetworkInterface object representing the network interface bound to the specific IP address

getByInetAddress()

returns a NetworkInterface object representing the network interface bound to the specified IP address.

getByInterAddress()

returns a NetworkInterface object representing the network interface bound to the specified IP address; or returns SocketException

The getHost() method

returns a String containing the hostname of the URL. For example, this code fragment prints xkcd.com: URL u = new URL("https://xkcd.com/727/"); System.out.println(u.getHost());

The getFile() method

returns a String that contains the path portion of a URL; remember that Java does not break a URL into separate path and file parts. Everything from the first slash (/) after the hostname until the character preceding the # sign that begins a fragment identifier is considered to be part of the file. For example: URL page = this.getDocumentBase(); System.out.println("This page's path is " + page.getFile()); If the URL does not have a file part, Java sets the file to the empty string.

what does the isLoopBackAddress() method do in the InetAddress class?

returns a boolean true if address is the loopback address, it returns false for every other address

read()

returns a single value character as an int with a value from 0 to 65545 (or -1)

getCodeBase()

returns the URL of the applet .class file

The getDefaultPort() method

returns the default port used for this URL's protocol when none is specified in the URL. If no default port is defined for the protocol, then getDefaultPort() returns -1. For example, if the URL is http://www.userfriendly.org/, getDefaultPort() returns 80; if the URL is ftp://ftp.userfriendly.org:8000/, getDefault Port() returns 21.

The getRef() method

returns the fragment identifier part of the URL. If the URL doesn't have a fragment identifier, the method returns null. In the following code, getRef() returns the string xtocid1902914: URL u = new URL( "http://www.ibiblio.org/javafaq/javafaq.html#xtocid1902914"); System.out.println("The fragment ID of " + u + " is " + u.getRef());

getName()

returns the name of a particular NetworkInterface object

getHeaderField(int n)

returns the nth heather field. in HTTP the starter line containing the request method and path is header field zero and the first actual header is one

The getPort() method

returns the port number specified in the URL as an int. If no port was specified in the URL, getPort() returns -1 to signify that the URL does not specify the port explicitly, and will use the default port for the protocol.

The getQuery() method

returns the query string of the URL. If the URL doesn't have a query string, the method returns null. In the following code, getQuery() returns the string category=Piano: URL u = new URL( "http://www.ibiblio.org/nywc/compositions.phtml?category=Piano"); System.out.println("The query string of " + u + " is " + u.getQuery());

isIPv4CompatibleAddress

returns true if the address is a IPv4 address stuffed into an IPv6 container such as 0:0:0:0:0:0:0:xxxx

isSiteLocalAddress()

returns true if the address is an IPv6 site-local address, false otherwise.

isConnected()

returns true is there was ever a connection even if it has been closed.

InetAddress.getByName("www.google.com");

returns www.google.com/208.201.239.23

Which Thread method should you override and put all the Thread's work into? start / run / main / join

run

all the work in the thread is done in this method. invokes other methods. constructs other objects. spawns threads. thread dies when complete. the main() of threaded programs.

run

Which of the following cache policies defines the number of seconds from now before the cached entry should expire from a shared cache?

s-max-age=[second]

time in seconds before a cached page should expire

s-maxage=[second]

URI Parts

scheme:scheme-specific-part:fragment public String getScheme() public String getSchemeSpecificPart() public String getRawSchemeSpecificPart() public String getFragment() public String getRawFragment()

HTTP 1.1 and later

server does not have to close the socket after it sends a response, leaves it open and waits for a new request from the client on the same socket

executors

set up thread pools in java.util.concurrent submit each task as a runnable object to the pool receive a future object you can use to check the progress of the task.

A URLConnection doesn't allow output by default, so you have to call ___ before asking for an output stream.

setDoOut put(true)

Which of the following methods determines whether the socket needs to authenticate itself or not in its first handshake?

setUseClientmode()

java.util.logging.Level

seven levels of ___.___.___.___: level.SEVERE level.WARNING level.INFO level.CONFIG level.FINE level.FINER level.FINEST

Which of the following is the highest log level represented by the class java.util.logging.Level?

severe

Synchronization must be considered any time multiple threads __ ___.

share resources

Print streams

should be explicitly flushed. -If autoFlush is true the stream will flush every time a byte array linefeed is written or a println() invoked

readLine()

should not be used because it is deprecated and buggy

Sub classing Thread

should override run() and nothing else! The various other methods of the Thread class-for example, start(), interrupt(), join(), sleep(), and so on-all have very specific semantics and interactions with the virtual machine that are difficult to reproduce in your own code.

shutdownInput()

shut down only the input of a connection.

What method is used to shut down only the input of a connection?

shutdownInput()

read() methods return -1 to...

signal the end of a stream

what does yield do?

signals to the VM that another

When does blocking occur?

signals to the VM that another thread has to stop and wait for a resource it does not have.

OOBINLINE

single byte of "urgent" data out of band. sent immediately.

Thread Scheduling

sleep() It causes the currently executing thread to pause for the specified number of milliseconds. wait() It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for the object. join() It waits for a particular thread to die. notifyAll() It wakes up all threads that are waiting on the object's monitor. yield() It causes the currently executing thread object to temporarily pause and allow other threads to execute. Blocking

HTTP Mime Type

text/* for human-readable words image/* for pictures model/* for 3D models such as VRML files audio/* for sound video/* for moving pictures, possibly including sound application/* for binary data message/* for protocol-specific envelopes such as email messages and HTTP responses multipart/* for containers of multiple documents and resources

Thread Scheduling

sleep() It causes the currently executing thread to pause for the specified number of milliseconds. wait() It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for the object. join() It waits for a particular thread to die. notifyAll() It wakes up all threads that are waiting on the object's monitor. yield() It causes the currently executing thread object to temporarily pause and allow other threads to execute. Blocking sleep() It causes the currently executing thread to pause for the specified number of milliseconds. wait() It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for the object. join() It waits for a particular thread to die. notifyAll() It wakes up all threads that are waiting on the object's monitor. yield() It causes the currently executing thread object to temporarily pause and allow other threads to execute.

Thread Scheduling

sleep() It causes the currently executing thread to pause for the specified number of milliseconds. wait() It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for the object. join() It waits for a particular thread to die. notifyAll() It wakes up all threads that are waiting on the object's monitor. yield() It causes the currently executing thread object to temporarily pause and allow other threads to execute.

A ___ is a connection between two hosts

socket

queryString()

solution to encode(); encodes successive pairs in a Java object with the add() method.

java.security.Permission

specified what permission is needed to connect to a URL, returns null if no permission is needed

java.io.Reader

specifies the API that the characters are read with

java.io.Writer

specifies the API that the characters are written with.

overloaded variant of the URLConnection method

specifies the proxy server to pass the connection through: public URLConnection openConnection(Proxy proxy) throws IOException This overrides any proxy server set with the usual socksProxyHost, socksProxyPort, http.proxyHost, http.proxyPort, http.nonProxyHosts, and similar system properties. If the protocol handler does not support proxies, the argument is ignored and the connection is made directly if possible.

22

ssh tcp

URI Uniform Resource Identifier

string of characters in a particular syntax that identifies a resource

FileInputStream

subclass of InputStream is used to read data from a file

outputStream

subclasses of _____ use write, flush, and close to write data to a file

What uses the 5 fundamental methods of OutputStream to write data onto a network connection?

sun.net.TelnetOutputStream

In traditional secret key (or ___ ) encryption, the same key is used to encrypt and decrypt the data.

symmetric

What is used to ensure that a single thread is finished before proceeding to the next thread in multi-threading?

synchronized()

deadlock

synchronizing increases the chance of ___.

bufferedReader

takes text directly from the buffer

callable

tasks are much more efficient than spawning a thread

established a telnet connection on port 25

telnet locahost 25

Which establishes a telnet connection on port 25?

telnet localhost 25

23

telnet tcp

Which two Java testProtocol methods will determine if a server supports web traffic? Choose 2 answers

testProtocol("http://www.company.com"); & testProtocol("https://www.company.com");

MIME classification

text image model audio video application message (protocol-specific) multipart (containers)

bufferedWriter

text is placed in a buffer. has the method readLine()

Which are MIME top-level types?

text/* image/* video/*

unsupportedCodingException

what does public outputStreamWriter(outputStream out, String encoding) throw?

URL vs URI

the URI class provides much more accurate, specification-conformant behavior than the URL class. For operations like absolutization and encoding, you should prefer the URI class where you have the option. You should also prefer the URI class if you need to store URLs in a hashtable or other data structure, since its equals() method is not blocking. The URL class should be used primarily when you want to download content from a server.

getPath() vs getFile()

the first returns path and file; the latter returns the same + a query string

getPath() vs. getFile()

the getPath() method does not return only the directory path and getFile() does not return only the filename, as you might expect. Both getPath() and getFile() return the full path and filename. The only difference is that getFile() also returns the query string and getPath() does not.

construct a serversocket with no binding

the noargs contructor creates an object but doesnt bind it to a port, later can be bound with the bind() method.

authority

the part of the URI that is responsible for resolving the rest of the uri.

What is the Ethernet address?

the physical address for the interface

in symmetric encryption

the same (secret) key encrypts/decrypts data

If the relative link begins with a /

then it is relative to the document root instead of relative to the current file. Thus, if you click on the following link while browsing http://www.ibiblio.org/javafaq/javatutorial.html: <a href="/projects/ipv6/">

cipher suites

these are used to chose ___ ___ getSupportedCipherSuites() method in SSLSocketFactory not all return values are allowed on connections. getEnabledCipherSuites() tells which ones can be used.

class loaders

these are used to load resources like images and files.

InetAddress object

these methods test if a ___ ___ meets the necessary criteria: isAnyLocalAddress() isLoopbackAddress() isLinkLocalAddress() isSiteLocalAddress() isMulticastAddress() isMCGlobal() isMCNodeLocal() isMCLinkLocal() isMCSiteLocal() isMCOrgLocal()

SpamCheck

these resources include real time blackhole lists, process a high load, and can allow IP addresses to query them to determine if the thing trying to connect to them is spam or not. They have to be cacheable fast distributed using only DNS if the host succeeds and returns the address, the host is a known spammer if it fails, then it throws UnknownHostException if you use one you have to stay on top of blackhole list changes.

UnknownHostException, NoRouteToHostException, ConnectException

these three exceptions are thrown when a DNS address changes for a while before it can cached.

Should you flush PrintStream?

they should explicitly be flushed

inputStream

this class has mark(int readAheadLimit) reset() markSupported()

java.io.File

this class has a toURL() method that: returns a file URL matching the given file the exact format returned is platform dependant java file URLs often cannot be interchanged with the URLs used by web browsers and other programs

java.net.inetAddress

this class is used by most networking classes like socket, serverSocket, URL, datagram socket. includes both a hostname and an IP address.

URL

this is a URI that provides a specific network location of a resource

inetAddress.getByName(url)

this method makes a connection to the local DNS server to lookup name and numeric addresses. Throws an UnknownHostException if it can't find the address If you can't pass the IP, do a reverseDNS. If it can't find the hostname, it returns the IP

Joining

this method of indicating a thread is ready to pause: one thread needs the results of another thread indicates to the thread that it needs to wait for another thread before continuing. the thread that invokes it is the one that waits. one of these types of threads can be interrupted. acts as normal after InterruptedException moving from the catch foreward similar to using an extractor and a future thread.

Sleeping

this method of indicating a thread is ready to pause: pauses even if no other threads are available holds locks gives opportunity to run to lower priority threads will cause deadlock if it is called when synchronized

finish

this method of signaling a thread is ready to give up control: gives up control by returning from the run() method

Waiting on an object

this method of signaling a thread is ready to give up control: releases locks on an object until notified by another thread neither threads have to finish for the other to continue. pauses execution until an object reaches a certain state obtain a lock on the object with synchronized, then invoke wait() wait is part of java.lang.Object can stop if a timeout expires, the thread is interrupted, or the object is notified. the notification occures when a thread invokees notify() or notifyAll() on an object.

getDisplayName

this method returns a human friendly name for the particular network interface

getDocumentBase

this method returns the URL of the page that contains the applet getCodeBase() and returns the URL of the applet .classfile

getName

this method returns the name of a NetworkInterface object

networkInterface

this object can be a physical address like an Ethernet card, or a virtual interface bound to the same physical hardware as the machine's other IP addresses. it provides methods to enumerate all local addresses can create objects from local addresses that can be used to create sockets, server sockets, and other similar objects.

java.io

this package has fileReader fileWriter stringReader stringWriter charArrayWriter charArrayReader

multithreaded

this type of program exists when the main() and run() methods of all nondeamon threads return

daemon

this type of thread performs background tasks

What is being leveraged in this code? try (OutputStream out = new FileOutputStream("/tmp/data.txt")) { // work with the output stream... } catch (IOException ex) { System.err.println(ex.getMessage()); }

try with resources

URL

unambiguously identifies the location of a resource on the Internet. the most common type of URI

telnetInputStream

undocumented class in sun.net

ethernet interfaces

unix: eth0, et1... lookback address "lo" windows: CE31 and ELX100

what does public outputStreamWriter(outputStream out, String encoding) throw?

unsupportedCodingException

InetAddress object

untrusted code can construct an ___ ___ from the string form of an IP address, with no DNS lookups performed.

to see what any proxy servers between the server and the client might be changing

use TRACE

to return all the addresses of a host

use getAllByName()

serverSocket()

use the noargs ___ constructor does not throw exceptions does not bind to a port call bind() to bind after serverSocket() object has been constructed

the echo protocol TCP port 7

useful for testing the network to make sure that data is not mangled by a misbehaving router or firewall

high priority

user interaction and quick completion threads get what type of priority

authority

userinfo, host, port

FileOutputStream

uses these methods to write data into a file

Using the URL "http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING" What method would return the authority, and what would it return?

variableURL.getAuthority( ); example.com:80

Using the URL "http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING" What method would return the filename, and what would it return?

variableURL.getFile( ); /docs/books/tutorial/index.html?name=networking

Using the URL "http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING" What method would return the host, and what would it return?

variableURL.getHost( ); example.com

Using the URL "http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING" What method would return the path, and what would it return?

variableURL.getPath( ); /docs/books/tutorial/index.html

Using the URL "http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING" What method would return the port, and what would it return?

variableURL.getPort( ); 80

Using the URL "http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING" What method would return the protocol, and what would it return?

variableURL.getProtocol( ); http

Using the URL "http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING" What method would return the query, and what would it return?

variableURL.getQuery( ); name=networking

Using the URL "http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING" What method would return the reference, and what would it return?

variableURL.getRef( ); DOWNLOADING

Java.io.OutputStream

void close() This method closes this output stream and releases any system resources associated with this stream. void flush() This method flushes this output stream and forces any buffered output bytes to be written out. void write(byte[] b) This method writes b.length bytes from the specified byte array to this output stream. void write(byte[] b, int off, int len) This method writes len bytes from the specified byte array starting at offset off to this output stream. abstract void write(int b) This method writes the specified byte to this output str

SO_LINGER

wait to send data, then close

requests, server errors

what are the two things that are stored in logs?

InetAddress

what class do these getter methods belong to? getHostName() gets a host with the ip address getCanonicalHostName() calls DNS getAddresses() dotted quad IP getHostAddresses() There are no setter methods so this is thread safe.

java.io.outputStream

what class do writer classes mirror

open connection

what do getInputStream(), getContent() and getHeaderField() require, and will create if they don't see one in the URL Connection class?

Read Data

what do these steps do with a URL Connection Object? 1) construct a URL object 2) invoke the URL Object's openCOnnection() method to get a URLConnection object for the URL 3) invoke the URL object's getInputStream() method 4) read from the input stream using the stream API

outputStreamWriter

what do you use to send binary data that writes a byte array instead of a writer that writes a string

IOException

what does connect throw in URL?

java.securty.permission

what does getPermission return that specifies what permission is needed to connect to the URL? (Returns null if there is not one)

encoding scheme

what does inputStreamReader convert characters based on

java.lang.Object

what does java.net.URL extend? URL is a final class uses a strategy design pattern to configure instances for different kinds of URLS

OutputStream's Fundamental Method

write(int b) - This method takes an integer from 0 to 255 as an argument and writes the corresponding byte to the output stream. This method is declared abstract because subclasses need to change it to handle their particular medium. For instance, a ByteArrayOutputStream can implement this method with pure Java code that copies the byte into its array. However, a FileOutputStream will need to use native code that understands how to write data in files on the host platform.

While browsing www.company.com/history/projects a user clicks on the link for <a href="/founders/johnsmith">, what URL will the user be redirected to?

www.company.com/founders/johnsmith.

When sending the command to retrieve and print a website address, what will the result be?

www.oreilly.com/208.201.239.36

synchronized

you can synchronize a method on the current object (this) by adding ___ to the method declaration

to use the GET method

you need to know the combination of names and values the program expects to receive

IPv6

you shouldn't make assumption about the length of an array when using getAddress() because it might return what type of address instead of an IPv4?

What are the 5 subclasses of the java.io.FilterWriter and java.io.FilterReader classes (5 total combined)

• BufferedReader • BufferedWriter • LineNumberReader • PushbackReader • PrintWriter

What are the three levels of CookiePolicy?

• CookiePolicy.ACCEPT_ALL All cookies allowed • CookiePolicy.ACCEPT_NONE No cookies allowed • CookiePolicy.ACCEPT_ORIGINAL_SERVER Only first party cookies allowed

What raw classes are given by the java.io package for reading and writing data?

• FileReader • FileWriter • StringReader • StringWriter • CharArrayReader • CharArrayWriter

There are four main HTTP methods:

• GET • POST • PUT • DELETE

What are 10 ways a thread can pause in favor of other threads or indicate it's ready to pause?

• It can block on I/O. • It can block on a synchronized object. • It can yield. • It can go to sleep. • It can join another thread. • It can wait on an object. • It can finish. • It can be preempted by a higher-priority thread. • It can be suspended. • It can stop.

There are seven levels defined as named constants in java.util.logging.Level in descending order of seriousness:

• Level.SEVERE (highest value) • Level.WARNING • Level.INFO • Level.CONFIG • Level.FINE • Level.FINER • Level.FINEST (lowest value)

There are still only three kinds of proxies, represented by three constants in the Proxy.Type enum:

• Proxy.Type.DIRECT (no proxy at all) • Proxy.Type.HTTP • Proxy.Type.SOCKS

There are two primary things you want to store in your logs:

• Requests • Server errors

By default, Java does not cache anything. To install a system-wide cache of the URL class will use, you need the following 3 subclasses:

• ResponseCache • CacheRequest • CacheResponse

For server sockets, Java supports three out of the nine options that were used for client sockets:

• SO_TIMEOUT • SO_REUSEADDR • SO_RCVBUF

Java supports nine options for client-side sockets:

• TCP_NODELAY • SO_BINDADDR • SO_TIMEOUT • SO_LINGER • SO_SNDBUF • SO_RCVBUF • SO_KEEPALIVE • OOBINLINE • IP_TOS

The URI Class differs from the java.net.URL class in three important ways:

• The URI class is purely about identification of resources and parsing of URIs. It provides no methods to retrieve a representation of the resource identified by its URI. • The URI class is more conformant to the relevant specifications than the URL class. • A URI object can represent a relative URI. The URL class absolutizes all URIs before storing them.

URLs are composed of five pieces:

• The scheme, also known as the protocol • The authority • The path • The fragment identifier, also known as the section or ref • The query string


Set pelajaran terkait

Management of Patients with Oncologic Disorders (15) PrepU

View Set

HY 102 Test 2 Inquisitive Questions

View Set

Priority Setting Frameworks Beginning Test

View Set

Chapter 20 California Life Insurance

View Set

INSY 3330 e-Commerce Final Exam (all quizzes combined)

View Set

Gilded Age, Gilded Age, The Gilded Age

View Set

Marianna Sidoryanskaya Macroeconomics Quiz 3

View Set