List of usage examples for java.net ProtocolException ProtocolException
public ProtocolException(String message)
From source file:org.apache.hawq.pxf.plugins.ignite.IgniteAccessor.java
/** * readNextObject() implementation// ww w. j ava 2s .co m */ @Override public OneRow readNextObject() throws Exception { if (urlReadFetch == null) { LOG.error( "readNextObject(): urlReadFetch is null. This means the Ignite qryfldexe query was not executed properly"); throw new ProtocolException( "readNextObject(): urlReadFetch is null. This means the Ignite qryfldexe query was not executed properly"); } if (bufferRead.isEmpty()) { // Refill buffer if (isLastReadFinished) { if (LOG.isDebugEnabled()) { LOG.debug("readNextObject(): All the data received from Ignite"); } return null; } JsonElement response = sendRestRequest(urlReadFetch); isLastReadFinished = response.getAsJsonObject().get("last").getAsBoolean(); // Parse 'items' Iterator<JsonElement> itemsIterator = response.getAsJsonObject().get("items").getAsJsonArray() .iterator(); while (itemsIterator.hasNext()) { if (!bufferRead.add(itemsIterator.next().getAsJsonArray())) { throw new IOException("readNextObject(): not enough memory in 'bufferRead'"); } } // Check again in case "response" contains no elements if (bufferRead.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("readNextObject(): Buffer refill failed"); LOG.debug("readNextObject(): All the data received from Ignite"); } return null; } } return new OneRow(bufferRead.pollFirst()); }
From source file:io.codis.nedis.handler.RedisResponseDecoder.java
private boolean decode(ByteBuf in, List<Object> out, Object nullValue) throws Exception { if (in.readableBytes() < 2) { return false; }/*from w w w . ja v a 2 s . c o m*/ byte b = in.readByte(); switch (b) { case '+': { String reply = decodeString(in); if (reply == null) { return false; } out.add(reply); return true; } case '-': { String reply = decodeString(in); if (reply == null) { return false; } out.add(new RedisResponseException(reply)); return true; } case ':': { Long reply = decodeLong(in); if (reply == null) { return false; } out.add(reply); return true; } case '$': { Long numBytes = decodeLong(in); if (numBytes == null) { return false; } if (numBytes.intValue() == -1) { out.add(nullValue); return true; } if (in.readableBytes() < numBytes.intValue() + 2) { return false; } if (in.getByte(in.readerIndex() + numBytes.intValue()) != '\r' || in.getByte(in.readerIndex() + numBytes.intValue() + 1) != '\n') { throw new ProtocolException("Response is not ended by CRLF"); } byte[] reply = new byte[numBytes.intValue()]; in.readBytes(reply); // skip CRLF in.skipBytes(2); out.add(reply); return true; } case '*': { Long numReplies = decodeLong(in); if (numReplies == null) { return false; } if (numReplies.intValue() == -1) { out.add(nullValue); return true; } List<Object> replies = new ArrayList<>(); for (int i = 0; i < numReplies.intValue(); i++) { if (!decode(in, replies, null)) { return false; } } out.add(replies); return true; } default: throw new ProtocolException("Unknown leading char: " + (char) b); } }
From source file:it.scoppelletti.programmerpower.web.security.CasClient.java
/** * Richiede un ticket di autenticazione. * // ww w . j a v a 2s.c om * @param userName Nome dell’utente. * @param pwd Password. * @return Ticket di autenticazione. */ public String newTicketGrantingTicket(String userName, SecureString pwd) throws ProtocolException { String text; Matcher matcher; Client client; Request req; Response resp; Form form; Status status; WebResources res = new WebResources(); SecurityResources secRes = new SecurityResources(); if (Strings.isNullOrEmpty(userName)) { throw new ArgumentNullException("userName"); } if (Values.isNullOrEmpty(pwd)) { throw new ArgumentNullException("pwd"); } if (Strings.isNullOrEmpty(myServerUrl)) { throw new PropertyNotSetException(toString(), "serverUrl"); } if (myServiceProps == null) { throw new PropertyNotSetException(toString(), "serviceProperties"); } form = new Form(); form.add("username", userName); form.add("password", pwd.toString()); req = new Request(Method.POST, myServerUrl); req.setEntity(form.getWebRepresentation(CharacterSet.UTF_8)); client = new Client(Protocol.HTTPS); resp = client.handle(req); status = resp.getStatus(); if (status.equals(Status.CLIENT_ERROR_BAD_REQUEST)) { throw new BadCredentialsException(secRes.getFailedLoginException()); } if (status.equals(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE)) { throw new ProtocolException(res.getUnsupportedMediaTypeException()); } if (!status.equals(Status.SUCCESS_CREATED)) { throw new ProtocolException( res.getUnexpectedStatusCodeException(status.getCode(), status.getDescription())); } text = resp.getEntityAsText(); if (Strings.isNullOrEmpty(text)) { throw new ProtocolException(res.getEmptyResponseException()); } matcher = myTGTFormat.matcher(text); if (!matcher.matches()) { throw new ProtocolException(res.getInvalidResponseException(text)); } return matcher.group(1); }
From source file:org.ardverk.daap.bio.HttpParser.java
/** * Parses headers from the given stream. Headers with the same name are not * combined.//from w w w . j a v a 2 s. c o m * * @param is * the stream to read headers from * @param charset * the charset to use for reading the data * * @return an array of headers in the order in which they were parsed * * @throws IOException * if an IO error occurs while reading from the stream * @throws HttpException * if there is an error parsing a header value * * @since 3.0 */ public static Header[] parseHeaders(InputStream is, String charset) throws IOException, HttpException { LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)"); List<Header> headers = new ArrayList<Header>(); String name = null; StringBuffer value = null; for (;;) { String line = HttpParser.readLine(is, charset); if ((line == null) || (line.trim().length() < 1)) { break; } // Parse the header name and value // Check for folded headers first // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2 // discussion on folded headers if ((line.charAt(0) == ' ') || (line.charAt(0) == '\t')) { // we have continuation folded header // so append value if (value != null) { value.append(' '); value.append(line.trim()); } } else { // make sure we save the previous name,value pair if present if (name != null) { headers.add(new BasicHeader(name, value.toString())); } // Otherwise we should have normal HTTP header line // Parse the header name and value int colon = line.indexOf(":"); if (colon < 0) { throw new ProtocolException("Unable to parse header: " + line); } name = line.substring(0, colon).trim(); value = new StringBuffer(line.substring(colon + 1).trim()); } } // make sure we save the last name,value pair if present if (name != null) { headers.add(new BasicHeader(name, value.toString())); } return (Header[]) headers.toArray(new Header[headers.size()]); }
From source file:se.kth.infosys.lumberjack.protocol.LumberjackClient.java
public int readAckFrame() throws ProtocolException, IOException { byte protocolVersion = input.readByte(); if (protocolVersion != PROTOCOL_VERSION) { throw new ProtocolException("Protocol version should be 1, received " + protocolVersion); }/* ww w .java2 s . co m*/ byte frameType = input.readByte(); if (frameType != FRAME_ACK) { throw new ProtocolException("Frame type should be Ack, received " + frameType); } int sequenceNumber = input.readInt(); logger.trace("Received ack sequence: {}", sequenceNumber); return sequenceNumber; }
From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java
public int readAckFrame() throws ProtocolException, IOException { byte protocolVersion = input.readByte(); if (protocolVersion != PROTOCOL_VERSION) { throw new ProtocolException("Protocol version should be 1, received " + protocolVersion); }/* w w w. jav a2 s . com*/ byte frameType = input.readByte(); if (frameType != FRAME_ACK) { throw new ProtocolException("Frame type should be Ack, received " + frameType); } int sequenceNumber = input.readInt(); if (logger.isDebugEnabled()) { logger.debug("Received ack sequence : " + sequenceNumber); } return sequenceNumber; }
From source file:it.scoppelletti.programmerpower.web.security.CasClient.java
/** * Richiede un ticket di servizio.// w w w .j av a2s .c om * * @param ticketGrantingTicket Ticket di autenticazione. * @return Ticket di servizio. */ public String newServiceTicket(String ticketGrantingTicket) throws ProtocolException { String text, url; Client client; Request req; Response resp; Form form; Status status; WebResources res = new WebResources(); SecurityResources secRes = new SecurityResources(); if (Strings.isNullOrEmpty(ticketGrantingTicket)) { throw new ArgumentNullException("ticketGrantingTicket"); } if (Strings.isNullOrEmpty(myServerUrl)) { throw new PropertyNotSetException(toString(), "serverUrl"); } if (myServiceProps == null) { throw new PropertyNotSetException(toString(), "serviceProperties"); } if (myServerUrl.endsWith("/")) { url = myServerUrl; } else { url = myServerUrl.concat("/"); } url = url.concat(ticketGrantingTicket); form = new Form(); form.add(myServiceProps.getServiceParameter(), myServiceProps.getService()); req = new Request(Method.POST, url); req.setEntity(form.getWebRepresentation(CharacterSet.UTF_8)); client = new Client(Protocol.HTTPS); resp = client.handle(req); status = resp.getStatus(); if (status.equals(Status.CLIENT_ERROR_BAD_REQUEST)) { throw new BadCredentialsException(secRes.getFailedLoginException()); } if (status.equals(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE)) { throw new ProtocolException(res.getUnsupportedMediaTypeException()); } if (!status.equals(Status.SUCCESS_OK)) { throw new ProtocolException( res.getUnexpectedStatusCodeException(status.getCode(), status.getDescription())); } text = resp.getEntityAsText(); if (Strings.isNullOrEmpty(text)) { throw new ProtocolException(res.getEmptyResponseException()); } return text; }
From source file:com.aptana.core.epl.downloader.RepositoryStatusHelper.java
/** * Check if the given exception represents that a switch to the JRE HTTP Client is required. ECF sets the HTTP * status code 477 to indicate this. If the JRE HTTP client is required a ProtocolException with a * "JRE Http Client Required" message is thrown. *///w w w.j a v a 2 s.c o m public static void checkJREHttpClientRequired(Throwable t) throws ProtocolException { if (t instanceof IncomingFileTransferException) { if (((IncomingFileTransferException) t).getErrorCode() == 477) throw new ProtocolException("JRE Http Client Required"); //$NON-NLS-1$ } else if (t instanceof BrowseFileTransferException) { if (((BrowseFileTransferException) t).getErrorCode() == 477) throw new ProtocolException("JRE Http Client Required"); //$NON-NLS-1$ } }
From source file:net.hiroq.rxwsc.RxWebSocketClient.java
/** * Connect to WebSocketServer with additional Header. * When unsubscribe is called, the observable will disconnect automatically. * <p>// w w w . j a va2s . c o m * Caution: This method run on same thread of caller. So if you want to run on NOT UI THREAD, * you have to use subscribeOn to specify thread model. * * @param uri * @param extraHeaders * @return */ public Observable<Event> connect(Uri uri, List<Pair<String, String>> extraHeaders) { this.disconnect(false); this.mUri = uri; this.mExtraHeaders = extraHeaders; this.mParser = new HybiParser(this); this.mHandlerThread = new HandlerThread(getClass().getName()); this.mHandlerThread.start(); this.mHandler = new Handler(mHandlerThread.getLooper()); return Observable.create(new Observable.OnSubscribe<Event>() { @Override public void call(Subscriber<? super Event> subscriber) { try { mSubscriber = subscriber; String secret = createSecret(); String scheme = mUri.getScheme(); // uri have invalid scheme throw MalformedURLException if (scheme == null || !(scheme.equals("ws") || scheme.equals("wss"))) { new MalformedURLException("Url scheme has to be specified as \"ws\" or \"wss\"."); } int port = (mUri.getPort() != -1) ? mUri.getPort() : (scheme.equals("wss") ? 443 : 80); String path = TextUtils.isEmpty(mUri.getPath()) ? "/" : mUri.getPath(); if (!TextUtils.isEmpty(mUri.getQuery())) { path += "?" + mUri.getQuery(); } String originScheme = scheme.equals("wss") ? "https" : "http"; Uri origin = Uri.parse(originScheme + "://" + mUri.getHost()); SocketFactory factory = scheme.equals("wss") ? getSSLSocketFactory() : SocketFactory.getDefault(); mSocket = factory.createSocket(mUri.getHost(), port); PrintWriter out = new PrintWriter(mSocket.getOutputStream()); out.print("GET " + path + " HTTP/1.1\r\n"); out.print("Upgrade: websocket\r\n"); out.print("Connection: Upgrade\r\n"); out.print("Host: " + mUri.getHost() + "\r\n"); out.print("Origin: " + origin.toString() + "\r\n"); out.print("Sec-WebSocket-Key: " + secret + "\r\n"); out.print("Sec-WebSocket-Version: 13\r\n"); if (mExtraHeaders != null) { for (Pair<String, String> pair : mExtraHeaders) { out.print(String.format("%s: %s\r\n", pair.first, pair.second)); } } out.print("\r\n"); out.flush(); HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream( mSocket.getInputStream()); // Read HTTP response status line. StatusLine statusLine = parseStatusLine(readLine(stream)); if (statusLine == null) { throw new ConnectException("Received no reply from server."); } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) { throw new ProtocolException( "Server sent invalid response code " + statusLine.getStatusCode() + ". WebSocket server must return " + HttpStatus.SC_SWITCHING_PROTOCOLS); } // Read HTTP response headers. String line; boolean validated = false; while (!TextUtils.isEmpty(line = readLine(stream))) { Header header = parseHeader(line); if (header.getName().equals("Sec-WebSocket-Accept")) { String expected = createSecretValidation(secret); String actual = header.getValue().trim(); if (!expected.equals(actual)) { throw new ProtocolException("Bad Sec-WebSocket-Accept header value."); } validated = true; } } if (!validated) { throw new ProtocolException("No Sec-WebSocket-Accept header."); } mIsConnected = true; emitterOnNext(new Event(EventType.CONNECT)); // Now decode websocket frames. mParser.start(stream); } catch (Exception e) { emitterOnError(e); } } }).doOnUnsubscribe(new Action0() { @Override public void call() { RxWebSocketClient.this.disconnect(false); } }); }
From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java
public void setRequestMethod(String methodName) throws ProtocolException { if (connected) throw new ProtocolException("Can't reset method: already connected"); if ("GET".equals(methodName)) method = new HttpGet(url.toString()); else if ("POST".equals(methodName)) method = new HttpPost(url.toString()); else if ("HEAD".equals(methodName)) method = new HttpHead(url.toString()); else if ("OPTIONS".equals(methodName)) method = new HttpOptions(url.toString()); else if ("PUT".equals(methodName)) method = new HttpPut(url.toString()); else if ("DELETE".equals(methodName)) method = new HttpDelete(url.toString()); else if ("TRACE".equals(methodName)) method = new HttpTrace(url.toString()); else/*www.jav a2 s . c o m*/ throw new ProtocolException("Method " + methodName + " not supported"); }