code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.json; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Key; /** * Data class representing a container of {@link GoogleJsonError}. * * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ public class GoogleJsonErrorContainer extends GenericJson { @Key private GoogleJsonError error; /** Returns the {@link GoogleJsonError}. */ public final GoogleJsonError getError() { return error; } /** Sets the {@link GoogleJsonError}. */ public final void setError(GoogleJsonError error) { this.error = error; } @Override public GoogleJsonErrorContainer set(String fieldName, Object value) { return (GoogleJsonErrorContainer) super.set(fieldName, value); } @Override public GoogleJsonErrorContainer clone() { return (GoogleJsonErrorContainer) super.clone(); } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * Google's JSON support (see detailed package specification). * * <h2>Package Specification</h2> * * <p> * User-defined Partial JSON data models allow you to defined Plain Old Java Objects (POJO's) to * define how the library should parse/serialize JSON. Each field that should be included must have * an @{@link com.google.api.client.util.Key} annotation. The field can be of any visibility * (private, package private, protected, or public) and must not be static. By default, the field * name is used as the JSON key. To override this behavior, simply specify the JSON key use the * optional value parameter of the annotation, for example {@code @Key("name")}. Any unrecognized * keys from the JSON are normally simply ignored and not stored. If the ability to store unknown * keys is important, use {@link com.google.api.client.json.GenericJson}. * </p> * * <p> * Let's take a look at a typical partial JSON-C video feed from the YouTube Data API (as specified * in <a href="http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html">YouTube * Developer's Guide: JSON-C / JavaScript</a>) * </p> * * <pre><code> "data":{ "updated":"2010-01-07T19:58:42.949Z", "totalItems":800, "startIndex":1, "itemsPerPage":1, "items":[ {"id":"hYB0mn5zh2c", "updated":"2010-01-07T13:26:50.000Z", "title":"Google Developers Day US - Maps API Introduction", "description":"Google Maps API Introduction ...", "tags":[ "GDD07","GDD07US","Maps" ], "player":{ "default":"http://www.youtube.com/watch?v\u003dhYB0mn5zh2c" }, ... } ] } </code></pre> * * <p> * Here's one possible way to design the Java data classes for this (each class in its own Java * file): * </p> * * <pre><code> import com.google.api.client.util.*; import java.util.List; public class VideoFeed { &#64;Key public int itemsPerPage; &#64;Key public int startIndex; &#64;Key public int totalItems; &#64;Key public DateTime updated; &#64;Key public List&lt;Video&gt; items; } public class Video { &#64;Key public String id; &#64;Key public String title; &#64;Key public DateTime updated; &#64;Key public String description; &#64;Key public List&lt;String&gt; tags; &#64;Key public Player player; } public class Player { // "default" is a Java keyword, so need to specify the JSON key manually &#64;Key("default") public String defaultUrl; } </code></pre> * * <p> * You can also use the @{@link com.google.api.client.util.Key} annotation to defined query * parameters for a URL. For example: * </p> * * <pre><code> public class YouTubeUrl extends GoogleUrl { &#64;Key public String author; &#64;Key("max-results") public Integer maxResults; public YouTubeUrl(String encodedUrl) { super(encodedUrl); this.alt = "jsonc"; } </code></pre> * * <p> * To work with the YouTube API, you first need to set up the * {@link com.google.api.client.http.HttpTransport}. For example: * </p> * * <pre><code> private static HttpTransport setUpTransport() throws IOException { HttpTransport result = new NetHttpTransport(); GoogleUtils.useMethodOverride(result); HttpHeaders headers = new HttpHeaders(); headers.setApplicationName("Google-YouTubeSample/1.0"); headers.gdataVersion = "2"; JsonCParser parser = new JsonCParser(); parser.jsonFactory = new JacksonFactory(); transport.addParser(parser); // insert authentication code... return transport; } </code></pre> * * <p> * Now that we have a transport, we can execute a request to the YouTube API and parse the result: * </p> * * <pre><code> public static VideoFeed list(HttpTransport transport, YouTubeUrl url) throws IOException { HttpRequest request = transport.buildGetRequest(); request.url = url; return request.execute().parseAs(VideoFeed.class); } </code></pre> * * <p> * If the server responds with an error the {@link com.google.api.client.http.HttpRequest#execute} * method will throw an {@link com.google.api.client.http.HttpResponseException}, which has an * {@link com.google.api.client.http.HttpResponse} field which can be parsed the same way as a * success response inside of a catch block. For example: * </p> * * <pre><code> try { ... } catch (HttpResponseException e) { if (e.response.getParser() != null) { Error error = e.response.parseAs(Error.class); // process error response } else { String errorContentString = e.response.parseAsString(); // process error response as string } throw e; } </code></pre> * * <p> * NOTE: As you might guess, the library uses reflection to populate the user-defined data model. * It's not quite as fast as writing the wire format parsing code yourself can potentially be, but * it's a lot easier. * </p> * * <p> * NOTE: If you prefer to use your favorite JSON parsing library instead (there are many of them * listed for example on <a href="http://json.org">json.org</a>), that's supported as well. Just * call {@link com.google.api.client.http.HttpRequest#execute()} and parse the returned byte stream. * </p> * * @since 1.0 * @author Yaniv Inbar */ package com.google.api.client.googleapis.json;
Java
/* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.json; import com.google.api.client.http.HttpMediaType; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.json.Json; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonParser; import com.google.api.client.json.JsonToken; import com.google.api.client.util.Preconditions; import com.google.api.client.util.StringUtils; import java.io.IOException; /** * Exception thrown when an error status code is detected in an HTTP response to a Google API that * uses the JSON format, using the format specified in <a * href="http://code.google.com/apis/urlshortener/v1/getting_started.html#errors">Error * Responses</a>. * * <p> * To execute a request, call {@link #execute(JsonFactory, HttpRequest)}. This will throw a * {@link GoogleJsonResponseException} on an error response. To get the structured details, use * {@link #getDetails()}. * </p> * * <pre> static void executeShowingError(JsonFactory factory, HttpRequest request) throws IOException { try { GoogleJsonResponseException.execute(factory, request); } catch (GoogleJsonResponseException e) { System.err.println(e.getDetails()); } } * </pre> * * @since 1.6 * @author Yaniv Inbar */ public class GoogleJsonResponseException extends HttpResponseException { private static final long serialVersionUID = 409811126989994864L; /** Google JSON error details or {@code null} for none (for example if response is not JSON). */ private final transient GoogleJsonError details; /** * @param builder builder * @param details Google JSON error details */ GoogleJsonResponseException(Builder builder, GoogleJsonError details) { super(builder); this.details = details; } /** * Returns the Google JSON error details or {@code null} for none (for example if response is not * JSON). */ public final GoogleJsonError getDetails() { return details; } /** * Returns a new instance of {@link GoogleJsonResponseException}. * * <p> * If there is a JSON error response, it is parsed using {@link GoogleJsonError}, which can be * inspected using {@link #getDetails()}. Otherwise, the full response content is read and * included in the exception message. * </p> * * @param jsonFactory JSON factory * @param response HTTP response * @return new instance of {@link GoogleJsonResponseException} */ public static GoogleJsonResponseException from(JsonFactory jsonFactory, HttpResponse response) { HttpResponseException.Builder builder = new HttpResponseException.Builder( response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); // details Preconditions.checkNotNull(jsonFactory); GoogleJsonError details = null; String detailString = null; try { if (!response.isSuccessStatusCode() && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, response.getContentType()) && response.getContent() != null) { JsonParser parser = null; try { parser = jsonFactory.createJsonParser(response.getContent()); JsonToken currentToken = parser.getCurrentToken(); // token is null at start, so get next token if (currentToken == null) { currentToken = parser.nextToken(); } // check for empty content if (currentToken != null) { // make sure there is an "error" key parser.skipToKey("error"); if (parser.getCurrentToken() != JsonToken.END_OBJECT) { details = parser.parseAndClose(GoogleJsonError.class); detailString = details.toPrettyString(); } } } catch (IOException exception) { // it would be bad to throw an exception while throwing an exception exception.printStackTrace(); } finally { if (parser == null) { response.ignore(); } else if (details == null) { parser.close(); } } } else { detailString = response.parseAsString(); } } catch (IOException exception) { // it would be bad to throw an exception while throwing an exception exception.printStackTrace(); } // message StringBuilder message = HttpResponseException.computeMessageBuffer(response); if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) { message.append(StringUtils.LINE_SEPARATOR).append(detailString); builder.setContent(detailString); } builder.setMessage(message.toString()); // result return new GoogleJsonResponseException(builder, details); } /** * Executes an HTTP request using {@link HttpRequest#execute()}, but throws a * {@link GoogleJsonResponseException} on error instead of {@link HttpResponseException}. * * <p> * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the * response stream is properly closed. Example usage: * </p> * * <pre> HttpResponse response = GoogleJsonResponseException.execute(jsonFactory, request); try { // process the HTTP response object } finally { response.disconnect(); } * </pre> * * @param jsonFactory JSON factory * @param request HTTP request * @return HTTP response for an HTTP success code (or error code if * {@link HttpRequest#getThrowExceptionOnExecuteError()}) * @throws GoogleJsonResponseException for an HTTP error code (only if not * {@link HttpRequest#getThrowExceptionOnExecuteError()}) * @throws IOException some other kind of I/O exception * @since 1.7 */ public static HttpResponse execute(JsonFactory jsonFactory, HttpRequest request) throws GoogleJsonResponseException, IOException { Preconditions.checkNotNull(jsonFactory); boolean originalThrowExceptionOnExecuteError = request.getThrowExceptionOnExecuteError(); if (originalThrowExceptionOnExecuteError) { request.setThrowExceptionOnExecuteError(false); } HttpResponse response = request.execute(); request.setThrowExceptionOnExecuteError(originalThrowExceptionOnExecuteError); if (!originalThrowExceptionOnExecuteError || response.isSuccessStatusCode()) { return response; } throw GoogleJsonResponseException.from(jsonFactory, response); } }
Java
/* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.json; import com.google.api.client.http.HttpResponse; import com.google.api.client.json.GenericJson; import com.google.api.client.json.Json; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.util.Data; import com.google.api.client.util.Key; import java.io.IOException; import java.util.Collections; import java.util.List; /** * Data class representing the Google JSON error response content, as documented for example in <a * href="https://code.google.com/apis/urlshortener/v1/getting_started.html#errors">Error * responses</a>. * * @since 1.4 * @author Yaniv Inbar */ public class GoogleJsonError extends GenericJson { /** * Parses the given error HTTP response using the given JSON factory. * * @param jsonFactory JSON factory * @param response HTTP response * @return new instance of the Google JSON error information * @throws IllegalArgumentException if content type is not {@link Json#MEDIA_TYPE} or if expected * {@code "data"} or {@code "error"} key is not found */ public static GoogleJsonError parse(JsonFactory jsonFactory, HttpResponse response) throws IOException { JsonObjectParser jsonObjectParser = new JsonObjectParser.Builder(jsonFactory).setWrapperKeys( Collections.singleton("error")).build(); return jsonObjectParser.parseAndClose( response.getContent(), response.getContentCharset(), GoogleJsonError.class); } static { // hack to force ProGuard to consider ErrorInfo used, since otherwise it would be stripped out // see http://code.google.com/p/google-api-java-client/issues/detail?id=527 Data.nullOf(ErrorInfo.class); } /** Detailed error information. */ public static class ErrorInfo extends GenericJson { /** Error classification or {@code null} for none. */ @Key private String domain; /** Error reason or {@code null} for none. */ @Key private String reason; /** Human readable explanation of the error or {@code null} for none. */ @Key private String message; /** * Location in the request that caused the error or {@code null} for none or {@code null} for * none. */ @Key private String location; /** Type of location in the request that caused the error or {@code null} for none. */ @Key private String locationType; /** * Returns the error classification or {@code null} for none. * * @since 1.8 */ public final String getDomain() { return domain; } /** * Sets the error classification or {@code null} for none. * * @since 1.8 */ public final void setDomain(String domain) { this.domain = domain; } /** * Returns the error reason or {@code null} for none. * * @since 1.8 */ public final String getReason() { return reason; } /** * Sets the error reason or {@code null} for none. * * @since 1.8 */ public final void setReason(String reason) { this.reason = reason; } /** * Returns the human readable explanation of the error or {@code null} for none. * * @since 1.8 */ public final String getMessage() { return message; } /** * Sets the human readable explanation of the error or {@code null} for none. * * @since 1.8 */ public final void setMessage(String message) { this.message = message; } /** * Returns the location in the request that caused the error or {@code null} for none or * {@code null} for none. * * @since 1.8 */ public final String getLocation() { return location; } /** * Sets the location in the request that caused the error or {@code null} for none or * {@code null} for none. * * @since 1.8 */ public final void setLocation(String location) { this.location = location; } /** * Returns the type of location in the request that caused the error or {@code null} for none. * * @since 1.8 */ public final String getLocationType() { return locationType; } /** * Sets the type of location in the request that caused the error or {@code null} for none. * * @since 1.8 */ public final void setLocationType(String locationType) { this.locationType = locationType; } @Override public ErrorInfo set(String fieldName, Object value) { return (ErrorInfo) super.set(fieldName, value); } @Override public ErrorInfo clone() { return (ErrorInfo) super.clone(); } } /** List of detailed errors or {@code null} for none. */ @Key private List<ErrorInfo> errors; /** HTTP status code of this response or {@code null} for none. */ @Key private int code; /** Human-readable explanation of the error or {@code null} for none. */ @Key private String message; /** * Returns the list of detailed errors or {@code null} for none. * * @since 1.8 */ public final List<ErrorInfo> getErrors() { return errors; } /** * Sets the list of detailed errors or {@code null} for none. * * @since 1.8 */ public final void setErrors(List<ErrorInfo> errors) { this.errors = errors; } /** * Returns the HTTP status code of this response or {@code null} for none. * * @since 1.8 */ public final int getCode() { return code; } /** * Sets the HTTP status code of this response or {@code null} for none. * * @since 1.8 */ public final void setCode(int code) { this.code = code; } /** * Returns the human-readable explanation of the error or {@code null} for none. * * @since 1.8 */ public final String getMessage() { return message; } /** * Sets the human-readable explanation of the error or {@code null} for none. * * @since 1.8 */ public final void setMessage(String message) { this.message = message; } @Override public GoogleJsonError set(String fieldName, Object value) { return (GoogleJsonError) super.set(fieldName, value); } @Override public GoogleJsonError clone() { return (GoogleJsonError) super.clone(); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * Google API's support based on the Apache HTTP Client. * * @since 1.14 * @author Yaniv Inbar */ package com.google.api.client.googleapis.apache;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.apache; import com.google.api.client.googleapis.GoogleUtils; import com.google.api.client.http.apache.ApacheHttpTransport; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; /** * Utilities for Google APIs based on {@link ApacheHttpTransport}. * * @since 1.14 * @author Yaniv Inbar */ public final class GoogleApacheHttpTransport { /** * Returns a new instance of {@link ApacheHttpTransport} that uses * {@link GoogleUtils#getCertificateTrustStore()} for the trusted certificates using * {@link com.google.api.client.http.apache.ApacheHttpTransport.Builder#trustCertificates(KeyStore)}. */ public static ApacheHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException { return new ApacheHttpTransport.Builder().trustCertificates( GoogleUtils.getCertificateTrustStore()).build(); } private GoogleApacheHttpTransport() { } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis; import com.google.api.client.http.EmptyContent; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.UrlEncodedContent; import java.io.IOException; /** * Thread-safe HTTP request execute interceptor for Google API's that wraps HTTP requests inside of * a POST request and uses {@link #HEADER} header to specify the actual HTTP method. * * <p> * Use this for example for an HTTP transport that doesn't support PATCH like * {@code NetHttpTransport} or {@code UrlFetchTransport}. By default, only the methods not supported * by the transport will be overridden. When running behind a firewall that does not support certain * verbs like PATCH, use the {@link MethodOverride.Builder#setOverrideAllMethods(boolean)} * constructor instead to specify to override all methods. POST is never overridden. * </p> * * <p> * This class also allows GET requests with a long URL (> 2048 chars) to be instead sent using * method override as a POST request. * </p> * * <p> * Sample usage, taking advantage that this class implements {@link HttpRequestInitializer}: * </p> * * <pre> public static HttpRequestFactory createRequestFactory(HttpTransport transport) { return transport.createRequestFactory(new MethodOverride()); } * </pre> * * <p> * If you have a custom request initializer, take a look at the sample usage for * {@link HttpExecuteInterceptor}, which this class also implements. * </p> * * @since 1.4 * @author Yaniv Inbar */ public final class MethodOverride implements HttpExecuteInterceptor, HttpRequestInitializer { /** * Name of the method override header. * * @since 1.13 */ public static final String HEADER = "X-HTTP-Method-Override"; /** Maximum supported URL length. */ static final int MAX_URL_LENGTH = 2048; /** * Whether to allow all methods (except GET and POST) to be overridden regardless of whether the * transport supports them. */ private final boolean overrideAllMethods; /** Only overrides HTTP methods that the HTTP transport does not support. */ public MethodOverride() { this(false); } MethodOverride(boolean overrideAllMethods) { this.overrideAllMethods = overrideAllMethods; } public void initialize(HttpRequest request) { request.setInterceptor(this); } public void intercept(HttpRequest request) throws IOException { if (overrideThisMethod(request)) { String requestMethod = request.getRequestMethod(); request.setRequestMethod(HttpMethods.POST); request.getHeaders().set(HEADER, requestMethod); if (requestMethod.equals(HttpMethods.GET)) { // take the URI query part and put it into the HTTP body request.setContent(new UrlEncodedContent(request.getUrl().clone())); // remove query parameters from URI request.getUrl().clear(); } else if (request.getContent() == null) { // Google servers will fail to process a POST unless the Content-Length header is specified request.setContent(new EmptyContent()); } } } private boolean overrideThisMethod(HttpRequest request) throws IOException { String requestMethod = request.getRequestMethod(); if (requestMethod.equals(HttpMethods.POST)) { return false; } if (requestMethod.equals(HttpMethods.GET) ? request.getUrl().build().length() > MAX_URL_LENGTH : overrideAllMethods) { return true; } return !request.getTransport().supportsMethod(requestMethod); } /** * Builder for {@link MethodOverride}. * * @since 1.12 * @author Yaniv Inbar */ public static final class Builder { /** * Whether to allow all methods (except GET and POST) to be overridden regardless of whether the * transport supports them. */ private boolean overrideAllMethods; /** Builds the {@link MethodOverride}. */ public MethodOverride build() { return new MethodOverride(overrideAllMethods); } /** * Returns whether to allow all methods (except GET and POST) to be overridden regardless of * whether the transport supports them. */ public boolean getOverrideAllMethods() { return overrideAllMethods; } /** * Sets whether to allow all methods (except GET and POST) to be overridden regardless of * whether the transport supports them. * * <p> * Default is {@code false}. * </p> */ public Builder setOverrideAllMethods(boolean overrideAllMethods) { this.overrideAllMethods = overrideAllMethods; return this; } } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; import com.google.api.client.util.Objects; import com.google.api.client.util.Preconditions; /** * {@link Beta} <br/> * Notification metadata sent to this client about a watched resource. * * <p> * Implementation is not thread-safe. * </p> * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public abstract class AbstractNotification { /** Message number (a monotonically increasing value starting with 1). */ private long messageNumber; /** {@link ResourceStates Resource state}. */ private String resourceState; /** Opaque ID for the watched resource that is stable across API versions. */ private String resourceId; /** * Opaque ID (in the form of a canonicalized URI) for the watched resource that is sensitive to * the API version. */ private String resourceUri; /** Notification channel UUID provided by the client in the watch request. */ private String channelId; /** Notification channel expiration time or {@code null} for none. */ private String channelExpiration; /** * Notification channel token (an opaque string) provided by the client in the watch request or * {@code null} for none. */ private String channelToken; /** Type of change performed on the resource or {@code null} for none. */ private String changed; /** * @param messageNumber message number (a monotonically increasing value starting with 1) * @param resourceState {@link ResourceStates resource state} * @param resourceId opaque ID for the watched resource that is stable across API versions * @param resourceUri opaque ID (in the form of a canonicalized URI) for the watched resource that * is sensitive to the API version * @param channelId notification channel UUID provided by the client in the watch request */ protected AbstractNotification(long messageNumber, String resourceState, String resourceId, String resourceUri, String channelId) { setMessageNumber(messageNumber); setResourceState(resourceState); setResourceId(resourceId); setResourceUri(resourceUri); setChannelId(channelId); } /** Copy constructor based on a source notification object. */ protected AbstractNotification(AbstractNotification source) { this(source.getMessageNumber(), source.getResourceState(), source.getResourceId(), source .getResourceUri(), source.getChannelId()); setChannelExpiration(source.getChannelExpiration()); setChannelToken(source.getChannelToken()); setChanged(source.getChanged()); } @Override public String toString() { return toStringHelper().toString(); } /** Returns the helper for {@link #toString()}. */ protected Objects.ToStringHelper toStringHelper() { return Objects.toStringHelper(this).add("messageNumber", messageNumber) .add("resourceState", resourceState).add("resourceId", resourceId) .add("resourceUri", resourceUri).add("channelId", channelId) .add("channelExpiration", channelExpiration).add("channelToken", channelToken) .add("changed", changed); } /** Returns the message number (a monotonically increasing value starting with 1). */ public final long getMessageNumber() { return messageNumber; } /** * Sets the message number (a monotonically increasing value starting with 1). * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setMessageNumber(long messageNumber) { Preconditions.checkArgument(messageNumber >= 1); this.messageNumber = messageNumber; return this; } /** Returns the {@link ResourceStates resource state}. */ public final String getResourceState() { return resourceState; } /** * Sets the {@link ResourceStates resource state}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setResourceState(String resourceState) { this.resourceState = Preconditions.checkNotNull(resourceState); return this; } /** Returns the opaque ID for the watched resource that is stable across API versions. */ public final String getResourceId() { return resourceId; } /** * Sets the opaque ID for the watched resource that is stable across API versions. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setResourceId(String resourceId) { this.resourceId = Preconditions.checkNotNull(resourceId); return this; } /** * Returns the opaque ID (in the form of a canonicalized URI) for the watched resource that is * sensitive to the API version. */ public final String getResourceUri() { return resourceUri; } /** * Sets the opaque ID (in the form of a canonicalized URI) for the watched resource that is * sensitive to the API version. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setResourceUri(String resourceUri) { this.resourceUri = Preconditions.checkNotNull(resourceUri); return this; } /** Returns the notification channel UUID provided by the client in the watch request. */ public final String getChannelId() { return channelId; } /** * Sets the notification channel UUID provided by the client in the watch request. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setChannelId(String channelId) { this.channelId = Preconditions.checkNotNull(channelId); return this; } /** Returns the notification channel expiration time or {@code null} for none. */ public final String getChannelExpiration() { return channelExpiration; } /** * Sets the notification channel expiration time or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setChannelExpiration(String channelExpiration) { this.channelExpiration = channelExpiration; return this; } /** * Returns the notification channel token (an opaque string) provided by the client in the watch * request or {@code null} for none. */ public final String getChannelToken() { return channelToken; } /** * Sets the notification channel token (an opaque string) provided by the client in the watch * request or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setChannelToken(String channelToken) { this.channelToken = channelToken; return this; } /** * Returns the type of change performed on the resource or {@code null} for none. */ public final String getChanged() { return changed; } /** * Sets the type of change performed on the resource or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setChanged(String changed) { this.changed = changed; return this; } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Standard resource states used by notifications. * * @author Yaniv Inbar * @since 1.16 */ @Beta public final class ResourceStates { /** Notification that the subscription is alive (comes with no payload). */ public static final String SYNC = "SYNC"; /** Resource exists, for example on a create or update. */ public static final String EXISTS = "EXISTS"; /** Resource does not exist, for example on a delete. */ public static final String NOT_EXISTS = "NOT_EXISTS"; private ResourceStates() { } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import java.util.UUID; /** * Utilities for notifications and notification channels. * * @author Yaniv Inbar * @since 1.16 */ public final class NotificationUtils { /** Returns a new random UUID string to be used as a notification channel ID. */ public static String randomUuidString() { return UUID.randomUUID().toString(); } private NotificationUtils() { } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; import com.google.api.client.util.Objects; import com.google.api.client.util.Preconditions; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import java.io.Serializable; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * {@link Beta} <br/> * Notification channel information to be stored in a data store. * * <p> * Implementation is thread safe. * </p> * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public final class StoredChannel implements Serializable { /** Default data store ID. */ public static final String DEFAULT_DATA_STORE_ID = StoredChannel.class.getSimpleName(); private static final long serialVersionUID = 1L; /** Lock on access to the store. */ private final Lock lock = new ReentrantLock(); /** Notification callback called when a notification is received for this subscription. */ private final UnparsedNotificationCallback notificationCallback; /** * Arbitrary string provided by the client associated with this subscription that is delivered to * the target address with each notification or {@code null} for none. */ private String clientToken; /** * Milliseconds in Unix time at which the subscription will expire or {@code null} for an infinite * TTL. */ private Long expiration; /** Subscription UUID. */ private final String id; /** * Opaque ID for the subscribed resource that is stable across API versions or {@code null} for * none. */ private String topicId; /** * Constructor with a random UUID using {@link NotificationUtils#randomUuidString()}. * * @param notificationCallback notification handler called when a notification is received for * this subscription */ public StoredChannel(UnparsedNotificationCallback notificationCallback) { this(notificationCallback, NotificationUtils.randomUuidString()); } /** * Constructor with a custom UUID. * * @param notificationCallback notification handler called when a notification is received for * this subscription * @param id subscription UUID */ public StoredChannel(UnparsedNotificationCallback notificationCallback, String id) { this.notificationCallback = Preconditions.checkNotNull(notificationCallback); this.id = Preconditions.checkNotNull(id); } /** * Stores this notification channel in the notification channel data store, which is derived from * {@link #getDefaultDataStore(DataStoreFactory)} on the given data store factory. * * <p> * It is important that this method be called before the watch HTTP request is made in case the * notification is received before the watch HTTP response is received. * </p> * * @param dataStoreFactory data store factory */ public StoredChannel store(DataStoreFactory dataStoreFactory) throws IOException { return store(getDefaultDataStore(dataStoreFactory)); } /** * Stores this notification channel in the given notification channel data store. * * <p> * It is important that this method be called before the watch HTTP request is made in case the * notification is received before the watch HTTP response is received. * </p> * * @param dataStore notification channel data store */ public StoredChannel store(DataStore<StoredChannel> dataStore) throws IOException { lock.lock(); try { dataStore.set(getId(), this); return this; } finally { lock.unlock(); } } /** * Returns the notification callback called when a notification is received for this subscription. */ public UnparsedNotificationCallback getNotificationCallback() { lock.lock(); try { return notificationCallback; } finally { lock.unlock(); } } /** * Returns the arbitrary string provided by the client associated with this subscription that is * delivered to the target address with each notification or {@code null} for none. */ public String getClientToken() { lock.lock(); try { return clientToken; } finally { lock.unlock(); } } /** * Sets the the arbitrary string provided by the client associated with this subscription that is * delivered to the target address with each notification or {@code null} for none. */ public StoredChannel setClientToken(String clientToken) { lock.lock(); try { this.clientToken = clientToken; } finally { lock.unlock(); } return this; } /** * Returns the milliseconds in Unix time at which the subscription will expire or {@code null} for * an infinite TTL. */ public Long getExpiration() { lock.lock(); try { return expiration; } finally { lock.unlock(); } } /** * Sets the milliseconds in Unix time at which the subscription will expire or {@code null} for an * infinite TTL. */ public StoredChannel setExpiration(Long expiration) { lock.lock(); try { this.expiration = expiration; } finally { lock.unlock(); } return this; } /** Returns the subscription UUID. */ public String getId() { lock.lock(); try { return id; } finally { lock.unlock(); } } /** * Returns the opaque ID for the subscribed resource that is stable across API versions or * {@code null} for none. */ public String getTopicId() { lock.lock(); try { return topicId; } finally { lock.unlock(); } } /** * Sets the opaque ID for the subscribed resource that is stable across API versions or * {@code null} for none. */ public StoredChannel setTopicId(String topicId) { lock.lock(); try { this.topicId = topicId; } finally { lock.unlock(); } return this; } @Override public String toString() { return Objects.toStringHelper(StoredChannel.class) .add("notificationCallback", getNotificationCallback()).add("clientToken", getClientToken()) .add("expiration", getExpiration()).add("id", getId()).add("topicId", getTopicId()) .toString(); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof StoredChannel)) { return false; } StoredChannel o = (StoredChannel) other; return getId().equals(o.getId()); } @Override public int hashCode() { return getId().hashCode(); } /** * Returns the stored channel data store using the ID {@link #DEFAULT_DATA_STORE_ID}. * * @param dataStoreFactory data store factory * @return stored channel data store */ public static DataStore<StoredChannel> getDefaultDataStore(DataStoreFactory dataStoreFactory) throws IOException { return dataStoreFactory.getDataStore(DEFAULT_DATA_STORE_ID); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for notification channels to listen for changes to watched Google API resources. * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.notifications;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications.json; import com.google.api.client.googleapis.notifications.TypedNotificationCallback; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.util.Beta; import java.io.IOException; /** * {@link Beta} <br/> * A {@link TypedNotificationCallback} which uses an JSON content encoding. * * <p> * Must NOT be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Implementation should be thread-safe. * </p> * * <b>Example usage:</b> * * <pre> static class MyNotificationCallback extends JsonNotificationCallback{@literal <}ListResponse{@literal >} { private static final long serialVersionUID = 1L; {@literal @}Override protected void onNotification( StoredChannel channel, TypedNotification{@literal <}ListResponse{@literal >} notification) { ListResponse content = notification.getContent(); switch (notification.getResourceState()) { case ResourceStates.SYNC: break; case ResourceStates.EXISTS: break; case ResourceStates.NOT_EXISTS: break; } } {@literal @}Override protected JsonFactory getJsonFactory() throws IOException { return new JacksonFactory(); } {@literal @}Override protected Class{@literal <}ListResponse{@literal >} getDataClass() throws IOException { return ListResponse.class; } } * </pre> * * @param <T> Type of the data contained within a notification * @author Yaniv Inbar * @since 1.16 */ @Beta public abstract class JsonNotificationCallback<T> extends TypedNotificationCallback<T> { private static final long serialVersionUID = 1L; @Override protected final JsonObjectParser getObjectParser() throws IOException { return new JsonObjectParser(getJsonFactory()); } /** Returns the JSON factory to use to parse the notification content. */ protected abstract JsonFactory getJsonFactory() throws IOException; }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * JSON-based notification handling for notification channels. * * @author Yaniv Inbar * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.notifications.json;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.http.HttpMediaType; import com.google.api.client.util.Beta; import com.google.api.client.util.ObjectParser; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.nio.charset.Charset; /** * {@link Beta} <br/> * Callback to receive notifications for watched resource in which the . Callback which is used to * receive typed {@link AbstractNotification}s after subscribing to a topic. * * <p> * Must NOT be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Implementation should be thread-safe. * </p> * * <b>Example usage:</b> * * <pre> static class MyNotificationCallback extends JsonNotificationCallback{@literal <}ListResponse{@literal >} { private static final long serialVersionUID = 1L; {@literal @}Override protected void onNotification( StoredChannel subscription, Notification notification, ListResponse content) { switch (notification.getResourceState()) { case ResourceStates.SYNC: break; case ResourceStates.EXISTS: break; case ResourceStates.NOT_EXISTS: break; } } {@literal @}Override protected ObjectParser getObjectParser(Notification notification) throws IOException { return new JsonObjectParser(new JacksonFactory()); } {@literal @}Override protected Class{@literal <}ListResponse{@literal >} getDataClass() throws IOException { return ListResponse.class; } } * </pre> * * @param <T> Java type of the notification content * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public abstract class TypedNotificationCallback<T> implements UnparsedNotificationCallback { private static final long serialVersionUID = 1L; /** * Handles a received typed notification. * * @param storedChannel stored notification channel * @param notification typed notification */ protected abstract void onNotification( StoredChannel storedChannel, TypedNotification<T> notification) throws IOException; /** Returns an {@link ObjectParser} which can be used to parse this notification. */ protected abstract ObjectParser getObjectParser() throws IOException; /** * Returns the data class to parse the notification content into or {@code Void.class} if no * notification content is expected. */ protected abstract Class<T> getDataClass() throws IOException; public final void onNotification(StoredChannel storedChannel, UnparsedNotification notification) throws IOException { TypedNotification<T> typedNotification = new TypedNotification<T>(notification); // TODO(yanivi): how to properly detect if there is no content? String contentType = notification.getContentType(); if (contentType != null) { Charset charset = new HttpMediaType(contentType).getCharsetParameter(); Class<T> dataClass = Preconditions.checkNotNull(getDataClass()); typedNotification.setContent( getObjectParser().parseAndClose(notification.getContentStream(), charset, dataClass)); } onNotification(storedChannel, typedNotification); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Notification metadata and parsed content sent to this client about a watched resource. * * <p> * Implementation is not thread-safe. * </p> * * @param <T> Java type of the notification content * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public class TypedNotification<T> extends AbstractNotification { /** Parsed notification content or {@code null} for none. */ private T content; /** * @param messageNumber message number (a monotonically increasing value starting with 1) * @param resourceState {@link ResourceStates resource state} * @param resourceId opaque ID for the watched resource that is stable across API versions * @param resourceUri opaque ID (in the form of a canonicalized URI) for the watched resource that * is sensitive to the API version * @param channelId notification channel UUID provided by the client in the watch request */ public TypedNotification(long messageNumber, String resourceState, String resourceId, String resourceUri, String channelId) { super(messageNumber, resourceState, resourceId, resourceUri, channelId); } /** * @param sourceNotification source notification metadata to copy */ public TypedNotification(UnparsedNotification sourceNotification) { super(sourceNotification); } /** * Returns the parsed notification content or {@code null} for none. */ public final T getContent() { return content; } /** * Sets the parsed notification content or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public TypedNotification<T> setContent(T content) { this.content = content; return this; } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setMessageNumber(long messageNumber) { return (TypedNotification<T>) super.setMessageNumber(messageNumber); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setResourceState(String resourceState) { return (TypedNotification<T>) super.setResourceState(resourceState); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setResourceId(String resourceId) { return (TypedNotification<T>) super.setResourceId(resourceId); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setResourceUri(String resourceUri) { return (TypedNotification<T>) super.setResourceUri(resourceUri); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setChannelId(String channelId) { return (TypedNotification<T>) super.setChannelId(channelId); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setChannelExpiration(String channelExpiration) { return (TypedNotification<T>) super.setChannelExpiration(channelExpiration); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setChannelToken(String channelToken) { return (TypedNotification<T>) super.setChannelToken(channelToken); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setChanged(String changed) { return (TypedNotification<T>) super.setChanged(changed); } @Override public String toString() { return super.toStringHelper().add("content", content).toString(); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; import java.io.IOException; import java.io.Serializable; /** * {@link Beta} <br/> * Callback to receive unparsed notifications for watched resource. * * <p> * Must NOT be implemented in form of an anonymous class since this would break serialization. * </p> * * <p> * Should be thread-safe as several notifications might be processed at the same time. * </p> * * <b>Example usage:</b> * * <pre> static class MyNotificationCallback implements UnparsedNotificationCallback { private static final long serialVersionUID = 1L; {@literal @}Override public void onNotification(StoredChannel storedChannel, UnparsedNotification notification) { String contentType = notification.getContentType(); InputStream contentStream = notification.getContentStream(); switch (notification.getResourceState()) { case ResourceStates.SYNC: break; case ResourceStates.EXISTS: break; case ResourceStates.NOT_EXISTS: break; } } } * </pre> * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public interface UnparsedNotificationCallback extends Serializable { /** * Handles a received unparsed notification. * * @param storedChannel stored notification channel * @param notification unparsed notification */ void onNotification(StoredChannel storedChannel, UnparsedNotification notification) throws IOException; }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; import java.io.InputStream; /** * {@link Beta} <br/> * Notification metadata and unparsed content stream sent to this client about a watched resource. * * <p> * Implementation is not thread-safe. * </p> * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public class UnparsedNotification extends AbstractNotification { /** Notification content media type for the content stream or {@code null} for none or unknown. */ private String contentType; /** Notification content input stream or {@code null} for none. */ private InputStream contentStream; /** * @param messageNumber message number (a monotonically increasing value starting with 1) * @param resourceState {@link ResourceStates resource state} * @param resourceId opaque ID for the watched resource that is stable across API versions * @param resourceUri opaque ID (in the form of a canonicalized URI) for the watched resource that * is sensitive to the API version * @param channelId notification channel UUID provided by the client in the watch request */ public UnparsedNotification(long messageNumber, String resourceState, String resourceId, String resourceUri, String channelId) { super(messageNumber, resourceState, resourceId, resourceUri, channelId); } /** * Returns the notification content media type for the content stream or {@code null} for none or * unknown. */ public final String getContentType() { return contentType; } /** * Sets the notification content media type for the content stream or {@code null} for none or * unknown. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public UnparsedNotification setContentType(String contentType) { this.contentType = contentType; return this; } /** * Returns the notification content input stream or {@code null} for none. */ public final InputStream getContentStream() { return contentStream; } /** * Sets the notification content content input stream or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public UnparsedNotification setContentStream(InputStream contentStream) { this.contentStream = contentStream; return this; } @Override public UnparsedNotification setMessageNumber(long messageNumber) { return (UnparsedNotification) super.setMessageNumber(messageNumber); } @Override public UnparsedNotification setResourceState(String resourceState) { return (UnparsedNotification) super.setResourceState(resourceState); } @Override public UnparsedNotification setResourceId(String resourceId) { return (UnparsedNotification) super.setResourceId(resourceId); } @Override public UnparsedNotification setResourceUri(String resourceUri) { return (UnparsedNotification) super.setResourceUri(resourceUri); } @Override public UnparsedNotification setChannelId(String channelId) { return (UnparsedNotification) super.setChannelId(channelId); } @Override public UnparsedNotification setChannelExpiration(String channelExpiration) { return (UnparsedNotification) super.setChannelExpiration(channelExpiration); } @Override public UnparsedNotification setChannelToken(String channelToken) { return (UnparsedNotification) super.setChannelToken(channelToken); } @Override public UnparsedNotification setChanged(String changed) { return (UnparsedNotification) super.setChanged(changed); } @Override public String toString() { return super.toStringHelper().add("contentType", contentType).toString(); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.testing.json; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.json.JsonFactory; import com.google.api.client.testing.http.HttpTesting; import com.google.api.client.testing.http.MockHttpTransport; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.api.client.util.Beta; import java.io.IOException; /** * {@link Beta} <br/> * Factory class that builds {@link GoogleJsonResponseException} instances for * testing. * * @since 1.18 */ @Beta public final class GoogleJsonResponseExceptionFactoryTesting { /** * Convenience factory method that builds a {@link GoogleJsonResponseException} * from its arguments. The method builds a dummy {@link HttpRequest} and * {@link HttpResponse}, sets the response's status to a user-specified HTTP * error code, suppresses exceptions, and executes the request. This forces * the underlying framework to create, but not throw, a * {@link GoogleJsonResponseException}, which the method retrieves and returns * to the invoker. * * @param jsonFactory the JSON factory that will create all JSON required * by the underlying framework * @param httpCode the desired HTTP error code. Note: do nut specify any codes * that indicate successful completion, e.g. 2XX. * @param reasonPhrase the HTTP reason code that explains the error. For example, * if {@code httpCode} is {@code 404}, the reason phrase should be * {@code NOT FOUND}. * @return the generated {@link GoogleJsonResponseException}, as specified. * @throws IOException if request transport fails. */ public static GoogleJsonResponseException newMock(JsonFactory jsonFactory, int httpCode, String reasonPhrase) throws IOException { MockLowLevelHttpResponse otherServiceUnavaiableLowLevelResponse = new MockLowLevelHttpResponse() .setStatusCode(httpCode) .setReasonPhrase(reasonPhrase); MockHttpTransport otherTransport = new MockHttpTransport.Builder() .setLowLevelHttpResponse(otherServiceUnavaiableLowLevelResponse) .build(); HttpRequest otherRequest = otherTransport .createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); otherRequest.setThrowExceptionOnExecuteError(false); HttpResponse otherServiceUnavailableResponse = otherRequest.execute(); return GoogleJsonResponseException.from(jsonFactory, otherServiceUnavailableResponse); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the {@code com.google.api.client.googleapis.json} package. * * @since 1.18 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.json;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.testing.notifications; import com.google.api.client.googleapis.notifications.StoredChannel; import com.google.api.client.googleapis.notifications.UnparsedNotification; import com.google.api.client.googleapis.notifications.UnparsedNotificationCallback; import com.google.api.client.util.Beta; import java.io.IOException; /** * {@link Beta} <br/> * Mock for the {@link UnparsedNotificationCallback} class. * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @SuppressWarnings("rawtypes") @Beta public class MockUnparsedNotificationCallback implements UnparsedNotificationCallback { private static final long serialVersionUID = 0L; /** Whether this handler was called. */ private boolean wasCalled; /** Returns whether this handler was called. */ public boolean wasCalled() { return wasCalled; } public MockUnparsedNotificationCallback() { } @SuppressWarnings("unused") public void onNotification(StoredChannel storedChannel, UnparsedNotification notification) throws IOException { wasCalled = true; } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the {@code com.google.api.client.googleapis.notifications} package. * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.notifications;
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.testing.services; import com.google.api.client.googleapis.services.AbstractGoogleClient; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Beta; import com.google.api.client.util.ObjectParser; /** * {@link Beta} <br/> * Thread-safe mock Google client. * * @since 1.12 * @author Yaniv Inbar */ @Beta public class MockGoogleClient extends AbstractGoogleClient { /** * @param transport The transport to use for requests * @param rootUrl root URL of the service. Must end with a "/" * @param servicePath service path * @param objectParser object parser or {@code null} for none * @param httpRequestInitializer HTTP request initializer or {@code null} for none * * @since 1.14 */ public MockGoogleClient(HttpTransport transport, String rootUrl, String servicePath, ObjectParser objectParser, HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, rootUrl, servicePath, objectParser, httpRequestInitializer)); } /** * @param builder builder * * @since 1.14 */ protected MockGoogleClient(Builder builder) { super(builder); } /** * Builder for {@link MockGoogleClient}. * * <p> * Implementation is not thread-safe. * </p> */ @Beta public static class Builder extends AbstractGoogleClient.Builder { /** * @param transport The transport to use for requests * @param rootUrl root URL of the service. Must end with a "/" * @param servicePath service path * @param objectParser object parser or {@code null} for none * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ public Builder(HttpTransport transport, String rootUrl, String servicePath, ObjectParser objectParser, HttpRequestInitializer httpRequestInitializer) { super(transport, rootUrl, servicePath, objectParser, httpRequestInitializer); } @Override public MockGoogleClient build() { return new MockGoogleClient(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the {@code com.google.api.client.googleapis.services} package. * * @since 1.12 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.services;
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the {@code com.google.api.client.googleapis.services.json} package. * * @since 1.12 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.services.json;
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.testing.services.json; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.UriTemplate; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe mock Google JSON request. * * @param <T> type of the response * @since 1.12 * @author Yaniv Inbar */ @Beta public class MockGoogleJsonClientRequest<T> extends AbstractGoogleJsonClientRequest<T> { /** * @param client Google client * @param method HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param content A POJO that can be serialized into JSON or {@code null} for none */ public MockGoogleJsonClientRequest(AbstractGoogleJsonClient client, String method, String uriTemplate, Object content, Class<T> responseClass) { super(client, method, uriTemplate, content, responseClass); } @Override public MockGoogleJsonClient getAbstractGoogleClient() { return (MockGoogleJsonClient) super.getAbstractGoogleClient(); } @Override public MockGoogleJsonClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (MockGoogleJsonClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public MockGoogleJsonClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (MockGoogleJsonClientRequest<T>) super.setRequestHeaders(headers); } }
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.testing.services.json; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe mock Google JSON client. * * @since 1.12 * @author Yaniv Inbar */ @Beta public class MockGoogleJsonClient extends AbstractGoogleJsonClient { /** * @param builder builder * * @since 1.14 */ protected MockGoogleJsonClient(Builder builder) { super(builder); } /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @param legacyDataWrapper whether using the legacy data wrapper in responses */ public MockGoogleJsonClient(HttpTransport transport, JsonFactory jsonFactory, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer, boolean legacyDataWrapper) { this(new Builder( transport, jsonFactory, rootUrl, servicePath, httpRequestInitializer, legacyDataWrapper)); } /** * {@link Beta} <br/> * Builder for {@link MockGoogleJsonClient}. * * <p> * Implementation is not thread-safe. * </p> */ @Beta public static class Builder extends AbstractGoogleJsonClient.Builder { /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @param legacyDataWrapper whether using the legacy data wrapper in responses */ public Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer, boolean legacyDataWrapper) { super( transport, jsonFactory, rootUrl, servicePath, httpRequestInitializer, legacyDataWrapper); } @Override public MockGoogleJsonClient build() { return new MockGoogleJsonClient(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.testing.services; import com.google.api.client.googleapis.services.AbstractGoogleClient; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.UriTemplate; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe mock Google request. * * @param <T> type of the response * @since 1.12 * @author Yaniv Inbar */ @Beta public class MockGoogleClientRequest<T> extends AbstractGoogleClientRequest<T> { /** * @param client Google client * @param method HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param content HTTP content or {@code null} for none * @param responseClass response class to parse into */ public MockGoogleClientRequest(AbstractGoogleClient client, String method, String uriTemplate, HttpContent content, Class<T> responseClass) { super(client, method, uriTemplate, content, responseClass); } @Override public MockGoogleClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (MockGoogleClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public MockGoogleClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (MockGoogleClientRequest<T>) super.setRequestHeaders(headers); } @Override public MockGoogleClientRequest<T> set(String fieldName, Object value) { return (MockGoogleClientRequest<T>) super.set(fieldName, value); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for <a href="https://developers.google.com/compute/">Google Compute Engine</a>. * * @since 1.15 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.compute;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.compute; import com.google.api.client.auth.oauth2.BearerToken; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.auth.oauth2.CredentialRefreshListener; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.util.Collection; /** * {@link Beta} <br/> * Google Compute Engine service accounts OAuth 2.0 credential based on <a * href="https://developers.google.com/compute/docs/authentication">Authenticating from Google * Compute Engine</a>. * * <p> * Sample usage: * </p> * * <pre> public static HttpRequestFactory createRequestFactory( HttpTransport transport, JsonFactory jsonFactory) { return transport.createRequestFactory(new GoogleComputeCredential(transport, jsonFactory)); } * </pre> * * <p> * Implementation is immutable and thread-safe. * </p> * * @since 1.15 * @author Yaniv Inbar */ @Beta public class ComputeCredential extends Credential { /** Metadata Service Account token server encoded URL. */ public static final String TOKEN_SERVER_ENCODED_URL = "http://metadata/computeMetadata/v1/instance/service-accounts/default/token"; /** * @param transport HTTP transport * @param jsonFactory JSON factory */ public ComputeCredential(HttpTransport transport, JsonFactory jsonFactory) { this(new Builder(transport, jsonFactory)); } /** * @param builder builder */ protected ComputeCredential(Builder builder) { super(builder); } @Override protected TokenResponse executeRefreshToken() throws IOException { GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl()); HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl); request.setParser(new JsonObjectParser(getJsonFactory())); request.getHeaders().set("X-Google-Metadata-Request", true); return request.execute().parseAs(TokenResponse.class); } /** * {@link Beta} <br/> * Google Compute Engine credential builder. * * <p> * Implementation is not thread-safe. * </p> */ @Beta public static class Builder extends Credential.Builder { /** * @param transport HTTP transport * @param jsonFactory JSON factory */ public Builder(HttpTransport transport, JsonFactory jsonFactory) { super(BearerToken.authorizationHeaderAccessMethod()); setTransport(transport); setJsonFactory(jsonFactory); setTokenServerEncodedUrl(TOKEN_SERVER_ENCODED_URL); } @Override public ComputeCredential build() { return new ComputeCredential(this); } @Override public Builder setTransport(HttpTransport transport) { return (Builder) super.setTransport(Preconditions.checkNotNull(transport)); } @Override public Builder setClock(Clock clock) { return (Builder) super.setClock(clock); } @Override public Builder setJsonFactory(JsonFactory jsonFactory) { return (Builder) super.setJsonFactory(Preconditions.checkNotNull(jsonFactory)); } @Override public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { return (Builder) super.setTokenServerUrl(Preconditions.checkNotNull(tokenServerUrl)); } @Override public Builder setTokenServerEncodedUrl(String tokenServerEncodedUrl) { return (Builder) super.setTokenServerEncodedUrl( Preconditions.checkNotNull(tokenServerEncodedUrl)); } @Override public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { Preconditions.checkArgument(clientAuthentication == null); return this; } @Override public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { return (Builder) super.setRequestInitializer(requestInitializer); } @Override public Builder addRefreshListener(CredentialRefreshListener refreshListener) { return (Builder) super.addRefreshListener(refreshListener); } @Override public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) { return (Builder) super.setRefreshListeners(refreshListeners); } } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.Beta; import com.google.api.client.util.SecurityUtils; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; /** * Utility class for the Google API Client Library. * * @since 1.12 * @author rmistry@google.com (Ravi Mistry) */ public final class GoogleUtils { // NOTE: Integer instead of int so compiler thinks it isn't a constant, so it won't inline it /** * Major part of the current release version. * * @since 1.14 */ public static final Integer MAJOR_VERSION = 1; /** * Minor part of the current release version. * * @since 1.14 */ public static final Integer MINOR_VERSION = 19; /** * Bug fix part of the current release version. * * @since 1.14 */ public static final Integer BUGFIX_VERSION = 0; /** Current release version. */ // NOTE: toString() so compiler thinks it isn't a constant, so it won't inline it public static final String VERSION = (MAJOR_VERSION + "." + MINOR_VERSION + "." + BUGFIX_VERSION + "-rc-SNAPSHOT").toString(); /** Cached value for {@link #getCertificateTrustStore()}. */ static KeyStore certTrustStore; /** * Returns the key store for trusted root certificates to use for Google APIs. * * <p> * Value is cached, so subsequent access is fast. * </p> * * @since 1.14 */ public static synchronized KeyStore getCertificateTrustStore() throws IOException, GeneralSecurityException { if (certTrustStore == null) { certTrustStore = SecurityUtils.getJavaKeyStore(); InputStream keyStoreStream = GoogleUtils.class.getResourceAsStream("google.jks"); SecurityUtils.loadKeyStore(certTrustStore, keyStoreStream, "notasecret"); } return certTrustStore; } /** * {@link Beta} <br/> * Returns a cached default implementation of the JsonFactory interface. */ @Beta public static JsonFactory getDefaultJsonFactory() { return JsonFactoryInstanceHolder.INSTANCE; } @Beta private static class JsonFactoryInstanceHolder { // The jackson2.JacksonFactory was introduced as a product dependency in 1.19 to enable // other APIs to not require one of these for input. This was the most commonly used // implementation in public samples. This is a compile-time dependency to help detect the // dependency as early as possible. static final JsonFactory INSTANCE = new JacksonFactory(); } /** * {@link Beta} <br/> * Returns a cached default implementation of the HttpTransport interface. */ @Beta public static HttpTransport getDefaultTransport() { return TransportInstanceHolder.INSTANCE; } @Beta private static class TransportInstanceHolder { static final HttpTransport INSTANCE = new NetHttpTransport(); } private GoogleUtils() { } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * Contains the basis for the generated service-specific libraries. * * @since 1.6 * @author Ravi Mistry */ package com.google.api.client.googleapis.services;
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services; import com.google.api.client.googleapis.MethodOverride; import com.google.api.client.googleapis.batch.BatchCallback; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.media.MediaHttpDownloader; import com.google.api.client.googleapis.media.MediaHttpUploader; import com.google.api.client.http.AbstractInputStreamContent; import com.google.api.client.http.EmptyContent; import com.google.api.client.http.GZipEncoding; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpResponseInterceptor; import com.google.api.client.http.UriTemplate; import com.google.api.client.util.GenericData; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Abstract Google client request for a {@link AbstractGoogleClient}. * * <p> * Implementation is not thread-safe. * </p> * * @param <T> type of the response * * @since 1.12 * @author Yaniv Inbar */ public abstract class AbstractGoogleClientRequest<T> extends GenericData { /** Google client. */ private final AbstractGoogleClient abstractGoogleClient; /** HTTP method. */ private final String requestMethod; /** URI template for the path relative to the base URL. */ private final String uriTemplate; /** HTTP content or {@code null} for none. */ private final HttpContent httpContent; /** HTTP headers used for the Google client request. */ private HttpHeaders requestHeaders = new HttpHeaders(); /** HTTP headers of the last response or {@code null} before request has been executed. */ private HttpHeaders lastResponseHeaders; /** Status code of the last response or {@code -1} before request has been executed. */ private int lastStatusCode = -1; /** Status message of the last response or {@code null} before request has been executed. */ private String lastStatusMessage; /** Whether to disable GZip compression of HTTP content. */ private boolean disableGZipContent; /** Response class to parse into. */ private Class<T> responseClass; /** Media HTTP uploader or {@code null} for none. */ private MediaHttpUploader uploader; /** Media HTTP downloader or {@code null} for none. */ private MediaHttpDownloader downloader; /** * @param abstractGoogleClient Google client * @param requestMethod HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param httpContent HTTP content or {@code null} for none * @param responseClass response class to parse into */ protected AbstractGoogleClientRequest(AbstractGoogleClient abstractGoogleClient, String requestMethod, String uriTemplate, HttpContent httpContent, Class<T> responseClass) { this.responseClass = Preconditions.checkNotNull(responseClass); this.abstractGoogleClient = Preconditions.checkNotNull(abstractGoogleClient); this.requestMethod = Preconditions.checkNotNull(requestMethod); this.uriTemplate = Preconditions.checkNotNull(uriTemplate); this.httpContent = httpContent; // application name String applicationName = abstractGoogleClient.getApplicationName(); if (applicationName != null) { requestHeaders.setUserAgent(applicationName); } } /** Returns whether to disable GZip compression of HTTP content. */ public final boolean getDisableGZipContent() { return disableGZipContent; } /** * Sets whether to disable GZip compression of HTTP content. * * <p> * By default it is {@code false}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractGoogleClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { this.disableGZipContent = disableGZipContent; return this; } /** Returns the HTTP method. */ public final String getRequestMethod() { return requestMethod; } /** Returns the URI template for the path relative to the base URL. */ public final String getUriTemplate() { return uriTemplate; } /** Returns the HTTP content or {@code null} for none. */ public final HttpContent getHttpContent() { return httpContent; } /** * Returns the Google client. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractGoogleClient getAbstractGoogleClient() { return abstractGoogleClient; } /** Returns the HTTP headers used for the Google client request. */ public final HttpHeaders getRequestHeaders() { return requestHeaders; } /** * Sets the HTTP headers used for the Google client request. * * <p> * These headers are set on the request after {@link #buildHttpRequest} is called, this means that * {@link HttpRequestInitializer#initialize} is called first. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractGoogleClientRequest<T> setRequestHeaders(HttpHeaders headers) { this.requestHeaders = headers; return this; } /** * Returns the HTTP headers of the last response or {@code null} before request has been executed. */ public final HttpHeaders getLastResponseHeaders() { return lastResponseHeaders; } /** * Returns the status code of the last response or {@code -1} before request has been executed. */ public final int getLastStatusCode() { return lastStatusCode; } /** * Returns the status message of the last response or {@code null} before request has been * executed. */ public final String getLastStatusMessage() { return lastStatusMessage; } /** Returns the response class to parse into. */ public final Class<T> getResponseClass() { return responseClass; } /** Returns the media HTTP Uploader or {@code null} for none. */ public final MediaHttpUploader getMediaHttpUploader() { return uploader; } /** * Initializes the media HTTP uploader based on the media content. * * @param mediaContent media content */ protected final void initializeMediaUpload(AbstractInputStreamContent mediaContent) { HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory(); this.uploader = new MediaHttpUploader( mediaContent, requestFactory.getTransport(), requestFactory.getInitializer()); this.uploader.setInitiationRequestMethod(requestMethod); if (httpContent != null) { this.uploader.setMetadata(httpContent); } } /** Returns the media HTTP downloader or {@code null} for none. */ public final MediaHttpDownloader getMediaHttpDownloader() { return downloader; } /** Initializes the media HTTP downloader. */ protected final void initializeMediaDownload() { HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory(); this.downloader = new MediaHttpDownloader(requestFactory.getTransport(), requestFactory.getInitializer()); } /** * Creates a new instance of {@link GenericUrl} suitable for use against this service. * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return newly created {@link GenericUrl} */ public GenericUrl buildHttpRequestUrl() { return new GenericUrl( UriTemplate.expand(abstractGoogleClient.getBaseUrl(), uriTemplate, this, true)); } /** * Create a request suitable for use against this service. * * <p> * Subclasses may override by calling the super implementation. * </p> */ public HttpRequest buildHttpRequest() throws IOException { return buildHttpRequest(false); } /** * Create a request suitable for use against this service, but using HEAD instead of GET. * * <p> * Only supported when the original request method is GET. * </p> * * <p> * Subclasses may override by calling the super implementation. * </p> */ protected HttpRequest buildHttpRequestUsingHead() throws IOException { return buildHttpRequest(true); } /** Create a request suitable for use against this service. */ private HttpRequest buildHttpRequest(boolean usingHead) throws IOException { Preconditions.checkArgument(uploader == null); Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET)); String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod; final HttpRequest httpRequest = getAbstractGoogleClient() .getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent); new MethodOverride().intercept(httpRequest); httpRequest.setParser(getAbstractGoogleClient().getObjectParser()); // custom methods may use POST with no content but require a Content-Length header if (httpContent == null && (requestMethod.equals(HttpMethods.POST) || requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) { httpRequest.setContent(new EmptyContent()); } httpRequest.getHeaders().putAll(requestHeaders); if (!disableGZipContent) { httpRequest.setEncoding(new GZipEncoding()); } final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor(); httpRequest.setResponseInterceptor(new HttpResponseInterceptor() { public void interceptResponse(HttpResponse response) throws IOException { if (responseInterceptor != null) { responseInterceptor.interceptResponse(response); } if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) { throw newExceptionOnError(response); } } }); return httpRequest; } /** * Sends the metadata request to the server and returns the raw metadata {@link HttpResponse}. * * <p> * Callers are responsible for disconnecting the HTTP response by calling * {@link HttpResponse#disconnect}. Example usage: * </p> * * <pre> HttpResponse response = request.executeUnparsed(); try { // process response.. } finally { response.disconnect(); } * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return the {@link HttpResponse} */ public HttpResponse executeUnparsed() throws IOException { return executeUnparsed(false); } /** * Sends the media request to the server and returns the raw media {@link HttpResponse}. * * <p> * Callers are responsible for disconnecting the HTTP response by calling * {@link HttpResponse#disconnect}. Example usage: * </p> * * <pre> HttpResponse response = request.executeMedia(); try { // process response.. } finally { response.disconnect(); } * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return the {@link HttpResponse} */ protected HttpResponse executeMedia() throws IOException { set("alt", "media"); return executeUnparsed(); } /** * Sends the metadata request using HEAD to the server and returns the raw metadata * {@link HttpResponse} for the response headers. * * <p> * Only supported when the original request method is GET. The response content is assumed to be * empty and ignored. Calls {@link HttpResponse#ignore()} so there is no need to disconnect the * response. Example usage: * </p> * * <pre> HttpResponse response = request.executeUsingHead(); // look at response.getHeaders() * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return the {@link HttpResponse} */ protected HttpResponse executeUsingHead() throws IOException { Preconditions.checkArgument(uploader == null); HttpResponse response = executeUnparsed(true); response.ignore(); return response; } /** * Sends the metadata request using the given request method to the server and returns the raw * metadata {@link HttpResponse}. */ private HttpResponse executeUnparsed(boolean usingHead) throws IOException { HttpResponse response; if (uploader == null) { // normal request (not upload) response = buildHttpRequest(usingHead).execute(); } else { // upload request GenericUrl httpRequestUrl = buildHttpRequestUrl(); HttpRequest httpRequest = getAbstractGoogleClient() .getRequestFactory().buildRequest(requestMethod, httpRequestUrl, httpContent); boolean throwExceptionOnExecuteError = httpRequest.getThrowExceptionOnExecuteError(); response = uploader.setInitiationHeaders(requestHeaders) .setDisableGZipContent(disableGZipContent).upload(httpRequestUrl); response.getRequest().setParser(getAbstractGoogleClient().getObjectParser()); // process any error if (throwExceptionOnExecuteError && !response.isSuccessStatusCode()) { throw newExceptionOnError(response); } } // process response lastResponseHeaders = response.getHeaders(); lastStatusCode = response.getStatusCode(); lastStatusMessage = response.getStatusMessage(); return response; } /** * Returns the exception to throw on an HTTP error response as defined by * {@link HttpResponse#isSuccessStatusCode()}. * * <p> * It is guaranteed that {@link HttpResponse#isSuccessStatusCode()} is {@code false}. Default * implementation is to call {@link HttpResponseException#HttpResponseException(HttpResponse)}, * but subclasses may override. * </p> * * @param response HTTP response * @return exception to throw */ protected IOException newExceptionOnError(HttpResponse response) { return new HttpResponseException(response); } /** * Sends the metadata request to the server and returns the parsed metadata response. * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return parsed HTTP response */ public T execute() throws IOException { return executeUnparsed().parseAs(responseClass); } /** * Sends the metadata request to the server and returns the metadata content input stream of * {@link HttpResponse}. * * <p> * Callers are responsible for closing the input stream after it is processed. Example sample: * </p> * * <pre> InputStream is = request.executeAsInputStream(); try { // Process input stream.. } finally { is.close(); } * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return input stream of the response content */ public InputStream executeAsInputStream() throws IOException { return executeUnparsed().getContent(); } /** * Sends the media request to the server and returns the media content input stream of * {@link HttpResponse}. * * <p> * Callers are responsible for closing the input stream after it is processed. Example sample: * </p> * * <pre> InputStream is = request.executeMediaAsInputStream(); try { // Process input stream.. } finally { is.close(); } * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return input stream of the response content */ protected InputStream executeMediaAsInputStream() throws IOException { return executeMedia().getContent(); } /** * Sends the metadata request to the server and writes the metadata content input stream of * {@link HttpResponse} into the given destination output stream. * * <p> * This method closes the content of the HTTP response from {@link HttpResponse#getContent()}. * </p> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @param outputStream destination output stream */ public void executeAndDownloadTo(OutputStream outputStream) throws IOException { executeUnparsed().download(outputStream); } /** * Sends the media request to the server and writes the media content input stream of * {@link HttpResponse} into the given destination output stream. * * <p> * This method closes the content of the HTTP response from {@link HttpResponse#getContent()}. * </p> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @param outputStream destination output stream */ protected void executeMediaAndDownloadTo(OutputStream outputStream) throws IOException { if (downloader == null) { executeMedia().download(outputStream); } else { downloader.download(buildHttpRequestUrl(), requestHeaders, outputStream); } } /** * Queues the request into the specified batch request container using the specified error class. * * <p> * Batched requests are then executed when {@link BatchRequest#execute()} is called. * </p> * * @param batchRequest batch request container * @param errorClass data class the unsuccessful response will be parsed into or * {@code Void.class} to ignore the content * @param callback batch callback */ public final <E> void queue( BatchRequest batchRequest, Class<E> errorClass, BatchCallback<T, E> callback) throws IOException { Preconditions.checkArgument(uploader == null, "Batching media requests is not supported"); batchRequest.queue(buildHttpRequest(), getResponseClass(), errorClass, callback); } // @SuppressWarnings was added here because this is generic class. // see: http://stackoverflow.com/questions/4169806/java-casting-object-to-a-generic-type and // http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#Type%20Erasure // for more details @SuppressWarnings("unchecked") @Override public AbstractGoogleClientRequest<T> set(String fieldName, Object value) { return (AbstractGoogleClientRequest<T>) super.set(fieldName, value); } /** * Ensures that the specified required parameter is not null or * {@link AbstractGoogleClient#getSuppressRequiredParameterChecks()} is true. * * @param value the value of the required parameter * @param name the name of the required parameter * @throws IllegalArgumentException if the specified required parameter is null and * {@link AbstractGoogleClient#getSuppressRequiredParameterChecks()} is false * @since 1.14 */ protected final void checkRequiredParameter(Object value, String name) { Preconditions.checkArgument( abstractGoogleClient.getSuppressRequiredParameterChecks() || value != null, "Required parameter %s must be specified", name); } }
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services; import java.io.IOException; /** * Google common client request initializer implementation for setting properties like key and * userIp. * * <p> * The simplest usage is to use it to set the key parameter: * </p> * * <pre> public static final GoogleClientRequestInitializer KEY_INITIALIZER = new CommonGoogleClientRequestInitializer(KEY); * </pre> * * <p> * There is also a constructor to set both the key and userIp parameters: * </p> * * <pre> public static final GoogleClientRequestInitializer INITIALIZER = new CommonGoogleClientRequestInitializer(KEY, USER_IP); * </pre> * * <p> * If you want to implement custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer extends CommonGoogleClientRequestInitializer { {@literal @}Override public void initialize(AbstractGoogleClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer2 extends CommonGoogleClientRequestInitializer { public MyRequestInitializer2() { super(KEY, USER_IP); } {@literal @}Override public void initialize(AbstractGoogleClientRequest{@literal <}?{@literal >} request) throws IOException { super.initialize(request); // must be called to set the key and userIp parameters // insert some additional logic } } * </pre> * * <p> * Subclasses should be thread-safe. * </p> * * @since 1.12 * @author Yaniv Inbar */ public class CommonGoogleClientRequestInitializer implements GoogleClientRequestInitializer { /** API key or {@code null} to leave it unchanged. */ private final String key; /** User IP or {@code null} to leave it unchanged. */ private final String userIp; public CommonGoogleClientRequestInitializer() { this(null); } /** * @param key API key or {@code null} to leave it unchanged */ public CommonGoogleClientRequestInitializer(String key) { this(key, null); } /** * @param key API key or {@code null} to leave it unchanged * @param userIp user IP or {@code null} to leave it unchanged */ public CommonGoogleClientRequestInitializer(String key, String userIp) { this.key = key; this.userIp = userIp; } /** * Subclasses should call super implementation in order to set the key and userIp. * * @throws IOException I/O exception */ public void initialize(AbstractGoogleClientRequest<?> request) throws IOException { if (key != null) { request.put("key", key); } if (userIp != null) { request.put("userIp", userIp); } } /** Returns the API key or {@code null} to leave it unchanged. */ public final String getKey() { return key; } /** Returns the user IP or {@code null} to leave it unchanged. */ public final String getUserIp() { return userIp; } }
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services; import java.io.IOException; /** * Google client request initializer. * * <p> * For example, this might be used to set a key URL query parameter on all requests: * </p> * * <pre> public class KeyRequestInitializer implements GoogleClientRequestInitializer { public void initialize(GoogleClientRequest<?> request) { request.put("key", KEY); } } * </pre> * * <p> * Implementations should be thread-safe. * </p> * * @since 1.12 * @author Yaniv Inbar */ public interface GoogleClientRequestInitializer { /** Initializes a Google client request. */ void initialize(AbstractGoogleClientRequest<?> request) throws IOException; }
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.ObjectParser; import com.google.api.client.util.Preconditions; import com.google.api.client.util.Strings; import java.io.IOException; import java.util.logging.Logger; /** * Abstract thread-safe Google client. * * @since 1.12 * @author Yaniv Inbar */ public abstract class AbstractGoogleClient { static final Logger LOGGER = Logger.getLogger(AbstractGoogleClient.class.getName()); /** The request factory for connections to the server. */ private final HttpRequestFactory requestFactory; /** * Initializer to use when creating an {@link AbstractGoogleClientRequest} or {@code null} for * none. */ private final GoogleClientRequestInitializer googleClientRequestInitializer; /** * Root URL of the service, for example {@code "https://www.googleapis.com/"}. Must be URL-encoded * and must end with a "/". */ private final String rootUrl; /** * Service path, for example {@code "tasks/v1/"}. Must be URL-encoded and must end with a "/". */ private final String servicePath; /** * Application name to be sent in the User-Agent header of each request or {@code null} for none. */ private final String applicationName; /** Object parser or {@code null} for none. */ private final ObjectParser objectParser; /** Whether discovery pattern checks should be suppressed on required parameters. */ private boolean suppressPatternChecks; /** Whether discovery required parameter checks should be suppressed. */ private boolean suppressRequiredParameterChecks; /** * @param builder builder * * @since 1.14 */ protected AbstractGoogleClient(Builder builder) { googleClientRequestInitializer = builder.googleClientRequestInitializer; rootUrl = normalizeRootUrl(builder.rootUrl); servicePath = normalizeServicePath(builder.servicePath); if (Strings.isNullOrEmpty(builder.applicationName)) { LOGGER.warning("Application name is not set. Call Builder#setApplicationName."); } applicationName = builder.applicationName; requestFactory = builder.httpRequestInitializer == null ? builder.transport.createRequestFactory() : builder.transport.createRequestFactory(builder.httpRequestInitializer); objectParser = builder.objectParser; suppressPatternChecks = builder.suppressPatternChecks; suppressRequiredParameterChecks = builder.suppressRequiredParameterChecks; } /** * Returns the URL-encoded root URL of the service, for example * {@code "https://www.googleapis.com/"}. * * <p> * Must end with a "/". * </p> */ public final String getRootUrl() { return rootUrl; } /** * Returns the URL-encoded service path of the service, for example {@code "tasks/v1/"}. * * <p> * Must end with a "/" and not begin with a "/". It is allowed to be an empty string {@code ""} or * a forward slash {@code "/"}, if it is a forward slash then it is treated as an empty string * </p> */ public final String getServicePath() { return servicePath; } /** * Returns the URL-encoded base URL of the service, for example * {@code "https://www.googleapis.com/tasks/v1/"}. * * <p> * Must end with a "/". It is guaranteed to be equal to {@code getRootUrl() + getServicePath()}. * </p> */ public final String getBaseUrl() { return rootUrl + servicePath; } /** * Returns the application name to be sent in the User-Agent header of each request or * {@code null} for none. */ public final String getApplicationName() { return applicationName; } /** Returns the HTTP request factory. */ public final HttpRequestFactory getRequestFactory() { return requestFactory; } /** Returns the Google client request initializer or {@code null} for none. */ public final GoogleClientRequestInitializer getGoogleClientRequestInitializer() { return googleClientRequestInitializer; } /** * Returns the object parser or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public ObjectParser getObjectParser() { return objectParser; } /** * Initializes a {@link AbstractGoogleClientRequest} using a * {@link GoogleClientRequestInitializer}. * * <p> * Must be called before the Google client request is executed, preferably right after the request * is instantiated. Sample usage: * </p> * * <pre> public class Get extends HttpClientRequest { ... } public Get get(String userId) throws IOException { Get result = new Get(userId); initialize(result); return result; } * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @param httpClientRequest Google client request type */ protected void initialize(AbstractGoogleClientRequest<?> httpClientRequest) throws IOException { if (getGoogleClientRequestInitializer() != null) { getGoogleClientRequestInitializer().initialize(httpClientRequest); } } /** * Create an {@link BatchRequest} object from this Google API client instance. * * <p> * Sample usage: * </p> * * <pre> client.batch() .queue(...) .queue(...) .execute(); * </pre> * * @return newly created Batch request */ public final BatchRequest batch() { return batch(null); } /** * Create an {@link BatchRequest} object from this Google API client instance. * * <p> * Sample usage: * </p> * * <pre> client.batch(httpRequestInitializer) .queue(...) .queue(...) .execute(); * </pre> * * @param httpRequestInitializer The initializer to use when creating the top-level batch HTTP * request or {@code null} for none * @return newly created Batch request */ public final BatchRequest batch(HttpRequestInitializer httpRequestInitializer) { BatchRequest batch = new BatchRequest(getRequestFactory().getTransport(), httpRequestInitializer); batch.setBatchUrl(new GenericUrl(getRootUrl() + "batch")); return batch; } /** Returns whether discovery pattern checks should be suppressed on required parameters. */ public final boolean getSuppressPatternChecks() { return suppressPatternChecks; } /** * Returns whether discovery required parameter checks should be suppressed. * * @since 1.14 */ public final boolean getSuppressRequiredParameterChecks() { return suppressRequiredParameterChecks; } /** If the specified root URL does not end with a "/" then a "/" is added to the end. */ static String normalizeRootUrl(String rootUrl) { Preconditions.checkNotNull(rootUrl, "root URL cannot be null."); if (!rootUrl.endsWith("/")) { rootUrl += "/"; } return rootUrl; } /** * If the specified service path does not end with a "/" then a "/" is added to the end. If the * specified service path begins with a "/" then the "/" is removed. */ static String normalizeServicePath(String servicePath) { Preconditions.checkNotNull(servicePath, "service path cannot be null"); if (servicePath.length() == 1) { Preconditions.checkArgument( "/".equals(servicePath), "service path must equal \"/\" if it is of length 1."); servicePath = ""; } else if (servicePath.length() > 0) { if (!servicePath.endsWith("/")) { servicePath += "/"; } if (servicePath.startsWith("/")) { servicePath = servicePath.substring(1); } } return servicePath; } /** * Builder for {@link AbstractGoogleClient}. * * <p> * Implementation is not thread-safe. * </p> */ public abstract static class Builder { /** HTTP transport. */ final HttpTransport transport; /** * Initializer to use when creating an {@link AbstractGoogleClientRequest} or {@code null} for * none. */ GoogleClientRequestInitializer googleClientRequestInitializer; /** HTTP request initializer or {@code null} for none. */ HttpRequestInitializer httpRequestInitializer; /** Object parser to use for parsing responses. */ final ObjectParser objectParser; /** The root URL of the service, for example {@code "https://www.googleapis.com/"}. */ String rootUrl; /** The service path of the service, for example {@code "tasks/v1/"}. */ String servicePath; /** * Application name to be sent in the User-Agent header of each request or {@code null} for * none. */ String applicationName; /** Whether discovery pattern checks should be suppressed on required parameters. */ boolean suppressPatternChecks; /** Whether discovery required parameter checks should be suppressed. */ boolean suppressRequiredParameterChecks; /** * Returns an instance of a new builder. * * @param transport The transport to use for requests * @param rootUrl root URL of the service. Must end with a "/" * @param servicePath service path * @param objectParser object parser or {@code null} for none * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ protected Builder(HttpTransport transport, String rootUrl, String servicePath, ObjectParser objectParser, HttpRequestInitializer httpRequestInitializer) { this.transport = Preconditions.checkNotNull(transport); this.objectParser = objectParser; setRootUrl(rootUrl); setServicePath(servicePath); this.httpRequestInitializer = httpRequestInitializer; } /** Builds a new instance of {@link AbstractGoogleClient}. */ public abstract AbstractGoogleClient build(); /** Returns the HTTP transport. */ public final HttpTransport getTransport() { return transport; } /** * Returns the object parser or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public ObjectParser getObjectParser() { return objectParser; } /** * Returns the URL-encoded root URL of the service, for example * {@code https://www.googleapis.com/}. * * <p> * Must be URL-encoded and must end with a "/". * </p> */ public final String getRootUrl() { return rootUrl; } /** * Sets the URL-encoded root URL of the service, for example {@code https://www.googleapis.com/} * . * <p> * If the specified root URL does not end with a "/" then a "/" is added to the end. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setRootUrl(String rootUrl) { this.rootUrl = normalizeRootUrl(rootUrl); return this; } /** * Returns the URL-encoded service path of the service, for example {@code "tasks/v1/"}. * * <p> * Must be URL-encoded and must end with a "/" and not begin with a "/". It is allowed to be an * empty string {@code ""}. * </p> */ public final String getServicePath() { return servicePath; } /** * Sets the URL-encoded service path of the service, for example {@code "tasks/v1/"}. * * <p> * It is allowed to be an empty string {@code ""} or a forward slash {@code "/"}, if it is a * forward slash then it is treated as an empty string. This is determined when the library is * generated and normally should not be changed. * </p> * * <p> * If the specified service path does not end with a "/" then a "/" is added to the end. If the * specified service path begins with a "/" then the "/" is removed. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setServicePath(String servicePath) { this.servicePath = normalizeServicePath(servicePath); return this; } /** Returns the Google client request initializer or {@code null} for none. */ public final GoogleClientRequestInitializer getGoogleClientRequestInitializer() { return googleClientRequestInitializer; } /** * Sets the Google client request initializer or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { this.googleClientRequestInitializer = googleClientRequestInitializer; return this; } /** Returns the HTTP request initializer or {@code null} for none. */ public final HttpRequestInitializer getHttpRequestInitializer() { return httpRequestInitializer; } /** * Sets the HTTP request initializer or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { this.httpRequestInitializer = httpRequestInitializer; return this; } /** * Returns the application name to be used in the UserAgent header of each request or * {@code null} for none. */ public final String getApplicationName() { return applicationName; } /** * Sets the application name to be used in the UserAgent header of each request or {@code null} * for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setApplicationName(String applicationName) { this.applicationName = applicationName; return this; } /** Returns whether discovery pattern checks should be suppressed on required parameters. */ public final boolean getSuppressPatternChecks() { return suppressPatternChecks; } /** * Sets whether discovery pattern checks should be suppressed on required parameters. * * <p> * Default value is {@code false}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { this.suppressPatternChecks = suppressPatternChecks; return this; } /** * Returns whether discovery required parameter checks should be suppressed. * * @since 1.14 */ public final boolean getSuppressRequiredParameterChecks() { return suppressRequiredParameterChecks; } /** * Sets whether discovery required parameter checks should be suppressed. * * <p> * Default value is {@code false}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.14 */ public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { this.suppressRequiredParameterChecks = suppressRequiredParameterChecks; return this; } /** * Suppresses all discovery pattern and required parameter checks. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.14 */ public Builder setSuppressAllChecks(boolean suppressAllChecks) { return setSuppressPatternChecks(true).setSuppressRequiredParameterChecks(true); } } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services.json; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; import com.google.api.client.googleapis.json.GoogleJsonErrorContainer; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.UriTemplate; import com.google.api.client.http.json.JsonHttpContent; import java.io.IOException; /** * Google JSON request for a {@link AbstractGoogleJsonClient}. * * <p> * Implementation is not thread-safe. * </p> * * @param <T> type of the response * @since 1.12 * @author Yaniv Inbar */ public abstract class AbstractGoogleJsonClientRequest<T> extends AbstractGoogleClientRequest<T> { /** POJO that can be serialized into JSON content or {@code null} for none. */ private final Object jsonContent; /** * @param abstractGoogleJsonClient Google JSON client * @param requestMethod HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param jsonContent POJO that can be serialized into JSON content or {@code null} for none * @param responseClass response class to parse into */ protected AbstractGoogleJsonClientRequest(AbstractGoogleJsonClient abstractGoogleJsonClient, String requestMethod, String uriTemplate, Object jsonContent, Class<T> responseClass) { super(abstractGoogleJsonClient, requestMethod, uriTemplate, jsonContent == null ? null : new JsonHttpContent(abstractGoogleJsonClient.getJsonFactory(), jsonContent) .setWrapperKey(abstractGoogleJsonClient.getObjectParser().getWrapperKeys().isEmpty() ? null : "data"), responseClass); this.jsonContent = jsonContent; } @Override public AbstractGoogleJsonClient getAbstractGoogleClient() { return (AbstractGoogleJsonClient) super.getAbstractGoogleClient(); } @Override public AbstractGoogleJsonClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (AbstractGoogleJsonClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public AbstractGoogleJsonClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (AbstractGoogleJsonClientRequest<T>) super.setRequestHeaders(headers); } /** * Queues the request into the specified batch request container. * * <p> * Batched requests are then executed when {@link BatchRequest#execute()} is called. * </p> * <p> * Example usage: * </p> * * <pre> request.queue(batchRequest, new JsonBatchCallback&lt;SomeResponseType&gt;() { public void onSuccess(SomeResponseType content, HttpHeaders responseHeaders) { log("Success"); } public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) { log(e.getMessage()); } }); * </pre> * * * @param batchRequest batch request container * @param callback batch callback */ public final void queue(BatchRequest batchRequest, JsonBatchCallback<T> callback) throws IOException { super.queue(batchRequest, GoogleJsonErrorContainer.class, callback); } @Override protected GoogleJsonResponseException newExceptionOnError(HttpResponse response) { return GoogleJsonResponseException.from(getAbstractGoogleClient().getJsonFactory(), response); } /** Returns POJO that can be serialized into JSON content or {@code null} for none. */ public Object getJsonContent() { return jsonContent; } @Override public AbstractGoogleJsonClientRequest<T> set(String fieldName, Object value) { return (AbstractGoogleJsonClientRequest<T>) super.set(fieldName, value); } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * Contains the basis for the generated service-specific libraries based on the JSON format. * * @since 1.12 * @author Yaniv Inbar */ package com.google.api.client.googleapis.services.json;
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services.json; import com.google.api.client.googleapis.services.AbstractGoogleClient; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import java.util.Arrays; import java.util.Collections; /** * Thread-safe Google JSON client. * * @since 1.12 * @author Yaniv Inbar */ public abstract class AbstractGoogleJsonClient extends AbstractGoogleClient { /** * @param builder builder * * @since 1.14 */ protected AbstractGoogleJsonClient(Builder builder) { super(builder); } @Override public JsonObjectParser getObjectParser() { return (JsonObjectParser) super.getObjectParser(); } /** Returns the JSON Factory. */ public final JsonFactory getJsonFactory() { return getObjectParser().getJsonFactory(); } /** * Builder for {@link AbstractGoogleJsonClient}. * * <p> * Implementation is not thread-safe. * </p> */ public abstract static class Builder extends AbstractGoogleClient.Builder { /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @param legacyDataWrapper whether using the legacy data wrapper in responses */ protected Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer, boolean legacyDataWrapper) { super(transport, rootUrl, servicePath, new JsonObjectParser.Builder( jsonFactory).setWrapperKeys( legacyDataWrapper ? Arrays.asList("data", "error") : Collections.<String>emptySet()) .build(), httpRequestInitializer); } @Override public final JsonObjectParser getObjectParser() { return (JsonObjectParser) super.getObjectParser(); } /** Returns the JSON Factory. */ public final JsonFactory getJsonFactory() { return getObjectParser().getJsonFactory(); } @Override public abstract AbstractGoogleJsonClient build(); @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services.json; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import java.io.IOException; /** * Google JSON client request initializer implementation for setting properties like key and userIp. * * <p> * The simplest usage is to use it to set the key parameter: * </p> * * <pre> public static final GoogleClientRequestInitializer KEY_INITIALIZER = new CommonGoogleJsonClientRequestInitializer(KEY); * </pre> * * <p> * There is also a constructor to set both the key and userIp parameters: * </p> * * <pre> public static final GoogleClientRequestInitializer INITIALIZER = new CommonGoogleJsonClientRequestInitializer(KEY, USER_IP); * </pre> * * <p> * If you want to implement custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer extends CommonGoogleJsonClientRequestInitializer { {@literal @}Override public void initialize(AbstractGoogleJsonClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: * </p> * * <pre> public static class MyKeyRequestInitializer extends CommonGoogleJsonClientRequestInitializer { public MyKeyRequestInitializer() { super(KEY, USER_IP); } {@literal @}Override public void initializeJsonRequest( AbstractGoogleJsonClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Subclasses should be thread-safe. * </p> * * @since 1.12 * @author Yaniv Inbar */ public class CommonGoogleJsonClientRequestInitializer extends CommonGoogleClientRequestInitializer { public CommonGoogleJsonClientRequestInitializer() { super(); } /** * @param key API key or {@code null} to leave it unchanged */ public CommonGoogleJsonClientRequestInitializer(String key) { super(key); } /** * @param key API key or {@code null} to leave it unchanged * @param userIp user IP or {@code null} to leave it unchanged */ public CommonGoogleJsonClientRequestInitializer(String key, String userIp) { super(key, userIp); } @Override public final void initialize(AbstractGoogleClientRequest<?> request) throws IOException { super.initialize(request); initializeJsonRequest((AbstractGoogleJsonClientRequest<?>) request); } /** * Initializes a Google JSON client request. * * <p> * Default implementation does nothing. Called from * {@link #initialize(AbstractGoogleClientRequest)}. * </p> * * @throws IOException I/O exception */ protected void initializeJsonRequest(AbstractGoogleJsonClientRequest<?> request) throws IOException { } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Notification channel handling based on the <a * href="http://wiki.fasterxml.com/JacksonRelease20">Jackson 2</a> JSON library. * * @author Yaniv Inbar * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.notifications.json.jackson2;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications.json.jackson2; import com.google.api.client.googleapis.notifications.TypedNotificationCallback; import com.google.api.client.googleapis.notifications.json.JsonNotificationCallback; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * A {@link TypedNotificationCallback} which uses an JSON content encoding with * {@link JacksonFactory#getDefaultInstance()}. * * <p> * Must NOT be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Implementation should be thread-safe. * </p> * * <b>Example usage:</b> * * <pre> static class MyNotificationCallback extends GsonNotificationCallback{@literal <}ListResponse{@literal >} { private static final long serialVersionUID = 1L; {@literal @}Override protected void onNotification( StoredChannel channel, TypedNotification{@literal <}ListResponse{@literal >} notification) { ListResponse content = notification.getContent(); switch (notification.getResourceState()) { case ResourceStates.SYNC: break; case ResourceStates.EXISTS: break; case ResourceStates.NOT_EXISTS: break; } } {@literal @}Override protected Class{@literal <}ListResponse{@literal >} getDataClass() throws IOException { return ListResponse.class; } } * </pre> * * @param <T> Type of the data contained within a notification * @author Yaniv Inbar * @since 1.16 */ @Beta public abstract class JacksonNotificationCallback<T> extends JsonNotificationCallback<T> { private static final long serialVersionUID = 1L; @Override protected JsonFactory getJsonFactory() { return JacksonFactory.getDefaultInstance(); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Notification channel handling based on the <a * href="http://code.google.com/p/google-gson/">GSON</a> JSON library. * * @author Yaniv Inbar * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.notifications.json.gson;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications.json.gson; import com.google.api.client.googleapis.notifications.TypedNotificationCallback; import com.google.api.client.googleapis.notifications.json.JsonNotificationCallback; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * A {@link TypedNotificationCallback} which uses an JSON content encoding with * {@link GsonFactory#getDefaultInstance()}. * * <p> * Must NOT be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Implementation should be thread-safe. * </p> * * <b>Example usage:</b> * * <pre> static class MyNotificationCallback extends GsonNotificationCallback{@literal <}ListResponse{@literal >} { private static final long serialVersionUID = 1L; {@literal @}Override protected void onNotification( StoredChannel channel, TypedNotification{@literal <}ListResponse{@literal >} notification) { ListResponse content = notification.getContent(); switch (notification.getResourceState()) { case ResourceStates.SYNC: break; case ResourceStates.EXISTS: break; case ResourceStates.NOT_EXISTS: break; } } {@literal @}Override protected Class{@literal <}ListResponse{@literal >} getDataClass() throws IOException { return ListResponse.class; } } * </pre> * * @param <T> Type of the data contained within a notification * @author Yaniv Inbar * @since 1.16 */ @Beta public abstract class GsonNotificationCallback<T> extends JsonNotificationCallback<T> { private static final long serialVersionUID = 1L; @Override protected JsonFactory getJsonFactory() { return GsonFactory.getDefaultInstance(); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for subscribing to topics and receiving notifications on servlet-based platforms. * * @author Yaniv Inbar * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.servlet.notifications;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.extensions.servlet.notifications; import com.google.api.client.googleapis.notifications.StoredChannel; import com.google.api.client.googleapis.notifications.UnparsedNotification; import com.google.api.client.googleapis.notifications.UnparsedNotificationCallback; import com.google.api.client.util.Beta; import com.google.api.client.util.LoggingInputStream; import com.google.api.client.util.Preconditions; import com.google.api.client.util.StringUtils; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link Beta} <br/> * Utilities for Webhook notifications. * * @author Yaniv Inbar * @since 1.16 */ @Beta public final class WebhookUtils { static final Logger LOGGER = Logger.getLogger(WebhookUtils.class.getName()); /** Webhook notification channel type to use in the watch request. */ public static final String TYPE = "web_hook"; /** * Utility method to process the webhook notification from {@link HttpServlet#doPost} by finding * the notification channel in the given data store factory. * * <p> * It is a wrapper around * {@link #processWebhookNotification(HttpServletRequest, HttpServletResponse, DataStore)} that * uses the data store from {@link StoredChannel#getDefaultDataStore(DataStoreFactory)}. * </p> * * @param req an {@link HttpServletRequest} object that contains the request the client has made * of the servlet * @param resp an {@link HttpServletResponse} object that contains the response the servlet sends * to the client * @param dataStoreFactory data store factory * @exception IOException if an input or output error is detected when the servlet handles the * request * @exception ServletException if the request for the POST could not be handled */ public static void processWebhookNotification( HttpServletRequest req, HttpServletResponse resp, DataStoreFactory dataStoreFactory) throws ServletException, IOException { processWebhookNotification(req, resp, StoredChannel.getDefaultDataStore(dataStoreFactory)); } /** * Utility method to process the webhook notification from {@link HttpServlet#doPost}. * * <p> * The {@link HttpServletRequest#getInputStream()} is closed in a finally block inside this * method. If it is not detected to be a webhook notification, an * {@link HttpServletResponse#SC_BAD_REQUEST} error will be displayed. If the notification channel * is found in the given notification channel data store, it will call * {@link UnparsedNotificationCallback#onNotification} for the registered notification callback * method. * </p> * * @param req an {@link HttpServletRequest} object that contains the request the client has made * of the servlet * @param resp an {@link HttpServletResponse} object that contains the response the servlet sends * to the client * @param channelDataStore notification channel data store * @exception IOException if an input or output error is detected when the servlet handles the * request * @exception ServletException if the request for the POST could not be handled */ public static void processWebhookNotification( HttpServletRequest req, HttpServletResponse resp, DataStore<StoredChannel> channelDataStore) throws ServletException, IOException { Preconditions.checkArgument("POST".equals(req.getMethod())); InputStream contentStream = req.getInputStream(); try { // log headers if (LOGGER.isLoggable(Level.CONFIG)) { StringBuilder builder = new StringBuilder(); Enumeration<?> e = req.getHeaderNames(); if (e != null) { while (e.hasMoreElements()) { Object nameObj = e.nextElement(); if (nameObj instanceof String) { String name = (String) nameObj; Enumeration<?> ev = req.getHeaders(name); if (ev != null) { while (ev.hasMoreElements()) { builder.append(name) .append(": ").append(ev.nextElement()).append(StringUtils.LINE_SEPARATOR); } } } } } LOGGER.config(builder.toString()); contentStream = new LoggingInputStream(contentStream, LOGGER, Level.CONFIG, 0x4000); // TODO(yanivi): allow to override logging content limit } // parse the relevant headers, and create a notification Long messageNumber; try { messageNumber = Long.valueOf(req.getHeader(WebhookHeaders.MESSAGE_NUMBER)); } catch (NumberFormatException e) { messageNumber = null; } String resourceState = req.getHeader(WebhookHeaders.RESOURCE_STATE); String resourceId = req.getHeader(WebhookHeaders.RESOURCE_ID); String resourceUri = req.getHeader(WebhookHeaders.RESOURCE_URI); String channelId = req.getHeader(WebhookHeaders.CHANNEL_ID); String channelExpiration = req.getHeader(WebhookHeaders.CHANNEL_EXPIRATION); String channelToken = req.getHeader(WebhookHeaders.CHANNEL_TOKEN); String changed = req.getHeader(WebhookHeaders.CHANGED); if (messageNumber == null || resourceState == null || resourceId == null || resourceUri == null || channelId == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Notification did not contain all required information."); return; } UnparsedNotification notification = new UnparsedNotification(messageNumber, resourceState, resourceId, resourceUri, channelId).setChannelExpiration(channelExpiration) .setChannelToken(channelToken) .setChanged(changed) .setContentType(req.getContentType()) .setContentStream(contentStream); // check if we know about the channel, hand over the notification to the notification callback StoredChannel storedChannel = channelDataStore.get(notification.getChannelId()); if (storedChannel != null) { storedChannel.getNotificationCallback().onNotification(storedChannel, notification); } } finally { contentStream.close(); } } private WebhookUtils() { } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.extensions.servlet.notifications; import com.google.api.client.googleapis.notifications.ResourceStates; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Headers for Webhook notifications. * * @author Yaniv Inbar * @since 1.16 */ @Beta public final class WebhookHeaders { /** Name of header for the message number (a monotonically increasing value starting with 1). */ public static final String MESSAGE_NUMBER = "X-Goog-Message-Number"; /** Name of header for the {@link ResourceStates resource state}. */ public static final String RESOURCE_STATE = "X-Goog-Resource-State"; /** * Name of header for the opaque ID for the watched resource that is stable across API versions. */ public static final String RESOURCE_ID = "X-Goog-Resource-ID"; /** * Name of header for the opaque ID (in the form of a canonicalized URI) for the watched resource * that is sensitive to the API version. */ public static final String RESOURCE_URI = "X-Goog-Resource-URI"; /** * Name of header for the notification channel UUID provided by the client in the watch request. */ public static final String CHANNEL_ID = "X-Goog-Channel-ID"; /** Name of header for the notification channel expiration time. */ public static final String CHANNEL_EXPIRATION = "X-Goog-Channel-Expiration"; /** * Name of header for the notification channel token (an opaque string) provided by the client in * the watch request. */ public static final String CHANNEL_TOKEN = "X-Goog-Channel-Token"; /** Name of header for the type of change performed on the resource. */ public static final String CHANGED = "X-Goog-Changed"; private WebhookHeaders() { } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.extensions.servlet.notifications; import com.google.api.client.googleapis.notifications.StoredChannel; import com.google.api.client.util.Beta; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import com.google.api.client.util.store.MemoryDataStoreFactory; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link Beta} <br/> * Thread-safe Webhook Servlet to receive notifications. * * <p> * In order to use this servlet you should create a class inheriting from * {@link NotificationServlet} and register the servlet in your web.xml. * </p> * * <p> * It is a simple wrapper around {@link WebhookUtils#processWebhookNotification}, so if you you may * alternatively call that method instead from your {@link HttpServlet#doPost} with no loss of * functionality. * </p> * * <b>Example usage:</b> * * <pre> public class MyNotificationServlet extends NotificationServlet { private static final long serialVersionUID = 1L; public MyNotificationServlet() throws IOException { super(new SomeDataStoreFactory()); } } * </pre> * * <b>Sample web.xml setup:</b> * * <pre> {@literal <}servlet{@literal >} {@literal <}servlet-name{@literal >}MyNotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}servlet-class{@literal >}com.mypackage.MyNotificationServlet{@literal <}/servlet-class{@literal >} {@literal <}/servlet{@literal >} {@literal <}servlet-mapping{@literal >} {@literal <}servlet-name{@literal >}MyNotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}url-pattern{@literal >}/notifications{@literal <}/url-pattern{@literal >} {@literal <}/servlet-mapping{@literal >} * </pre> * * <p> * WARNING: by default it uses {@link MemoryDataStoreFactory#getDefaultInstance()} which means it * will NOT persist the notification channels when the servlet process dies, so it is a BAD CHOICE * for a production application. But it is a convenient choice when testing locally, in which case * you don't need to override it, and can simply reference it directly in your web.xml file. For * example: * </p> * * <pre> {@literal <}servlet{@literal >} {@literal <}servlet-name{@literal >}NotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}servlet-class{@literal >}com.google.api.client.googleapis.extensions.servlet.notificationsNotificationServlet{@literal <}/servlet-class{@literal >} {@literal <}/servlet{@literal >} {@literal <}servlet-mapping{@literal >} {@literal <}servlet-name{@literal >}NotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}url-pattern{@literal >}/notifications{@literal <}/url-pattern{@literal >} {@literal <}/servlet-mapping{@literal >} * </pre> * * @author Yaniv Inbar * @since 1.16 */ @Beta public class NotificationServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** Notification channel data store. */ private final transient DataStore<StoredChannel> channelDataStore; /** * Constructor to be used for testing and demo purposes that uses * {@link MemoryDataStoreFactory#getDefaultInstance()} which means it will NOT persist the * notification channels when the servlet process dies, so it is a bad choice for a production * application. */ public NotificationServlet() throws IOException { this(MemoryDataStoreFactory.getDefaultInstance()); } /** * Constructor which uses {@link StoredChannel#getDefaultDataStore(DataStoreFactory)} on the given * data store factory, which is the normal use case. * * @param dataStoreFactory data store factory */ protected NotificationServlet(DataStoreFactory dataStoreFactory) throws IOException { this(StoredChannel.getDefaultDataStore(dataStoreFactory)); } /** * Constructor that allows a specific notification data store to be specified. * * @param channelDataStore notification channel data store */ protected NotificationServlet(DataStore<StoredChannel> channelDataStore) { this.channelDataStore = channelDataStore; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { WebhookUtils.processWebhookNotification(req, resp, channelDataStore); } }
Java
/** * Copyright (c) 2010 David Dearing */ package com.dpdearing.sandbox.gpsemulator.client; import com.dpdearing.sandbox.gpsemulator.common.LocationServiceAsync; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.maps.client.MapUIOptions; import com.google.gwt.maps.client.MapWidget; import com.google.gwt.maps.client.Maps; import com.google.gwt.maps.client.event.MapClickHandler; import com.google.gwt.maps.client.geom.LatLng; import com.google.gwt.maps.client.overlay.Marker; import com.google.gwt.maps.client.overlay.Overlay; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DockLayoutPanel; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootLayoutPanel; import com.google.gwt.user.client.ui.TextBox; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class GpsEmulator implements EntryPoint, MapClickHandler { /** * The default emulator port */ static private final int DEFAULT_PORT = 5554; static private final String SUCCESS_STYLE = "success"; static private final String ERROR_STYLE = "error"; /** * Create a remote service proxy to talk to the server-side Location service. */ private final LocationServiceAsync _service = LocationServiceAsync.Util.getInstance(); /** * The last marker placed on the map */ private Marker _lastMarker = null; /** * The textbox, button, and info label for configuring the port. */ private TextBox _text; private Button _button; private Label _info; /** * This is the entry point method. */ public void onModuleLoad() { /* * Asynchronously loads the Maps API. * * The first parameter should be a valid Maps API Key to deploy this * application on a public server, but a blank key will work for an * application served from localhost. */ Maps.loadMapsApi("", "2", false, new Runnable() { public void run() { // initialize the UI buildUi(); // initialize the default port new PortAsyncCallback(DEFAULT_PORT).execute(); } }); } /** * Initialize the UI */ private void buildUi() { // Create a textbox and set default port _text = new TextBox(); _text.setText(String.valueOf(DEFAULT_PORT)); // Create button to change default port _button = new Button("Change Emulator Port"); // Create the info/status label _info = new InlineLabel(); // register the button action _button.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { final int port = Integer.valueOf(_text.getText()); new PortAsyncCallback(port).execute(); } }); // Open a map centered on Cawker City, KS USA final LatLng cawkerCity = LatLng.newInstance(39.509, -98.434); final MapWidget map = new MapWidget(cawkerCity, 2); map.setSize("100%", "100%"); // Workaround for bug with click handler & setUItoDefaults() - see issue 260 final MapUIOptions opts = map.getDefaultUI(); opts.setDoubleClick(false); map.setUI(opts); // Register map click handler map.addMapClickHandler(this); // Create panel for textbox, button and info label final FlowPanel div = new FlowPanel(); div.add(_text); div.add(_button); div.add(_info); // Dock the map final DockLayoutPanel dock = new DockLayoutPanel(Unit.PX); dock.addNorth(map, 500); // Add the map dock to the div panel div.add(dock); RootLayoutPanel.get().add(div); } /** * Handle a map click event */ public void onClick(final MapClickEvent e) { final MapWidget sender = e.getSender(); final Overlay overlay = e.getOverlay(); final LatLng point = e.getLatLng(); if (overlay != null && overlay instanceof Marker) { // clear a marker that has been clicked on sender.removeOverlay(overlay); } else { // clear the last-placed marker ... if (_lastMarker != null && _lastMarker instanceof Marker) { sender.removeOverlay(_lastMarker); _lastMarker = null; } // ... and add the new marker final Marker mark = new Marker(point); _lastMarker = mark; sender.addOverlay(mark); // set the location new GeoFixAsyncCallback(point.getLatitude(), point.getLongitude()).execute(); } } /** * Asynchronous callback for setting the telnet port. */ private class PortAsyncCallback implements AsyncCallback<Void>, Command { private final int _port; /** * Constructor * * @param port the port */ public PortAsyncCallback(final int port) { _port = port; } /** * Success! * * @param result void */ public void onSuccess(final Void result) { _info.addStyleDependentName(SUCCESS_STYLE); _info.setText("Connected to port " + _port); } /** * Oh no! */ public void onFailure(final Throwable caught) { _info.addStyleDependentName(ERROR_STYLE); _info.setText("Error making connection on port " + _port + ": " + caught.getLocalizedMessage()); } /** * Execute service method */ public void execute() { // clear info message _info.setText(""); _info.removeStyleDependentName(ERROR_STYLE); _info.removeStyleDependentName(SUCCESS_STYLE); _service.setPort(_port, this); } } /** * Asynchronous callback for changing the emulator's location */ private class GeoFixAsyncCallback implements AsyncCallback<Void>, Command { private final double _latitude; private final double _longitude; /** * Constructor. * * @param latitude * latitude * @param longitude * longitude */ public GeoFixAsyncCallback(final double latitude, final double longitude) { _latitude = latitude; _longitude = longitude; } /** * Success! * * @param result void */ public void onSuccess(final Void result) { _info.addStyleDependentName(SUCCESS_STYLE); _info.setText("geo fix " + _longitude + " " + _latitude); } /** * Oh no! */ public void onFailure(final Throwable caught) { _info.addStyleDependentName(ERROR_STYLE); _info.setText("Error setting location: " + caught.getLocalizedMessage()); } /** * Execute service method */ public void execute() { // clear info message _info.setText(""); _info.removeStyleDependentName(ERROR_STYLE); _info.removeStyleDependentName(SUCCESS_STYLE); _service.setLocation(_latitude, _longitude, this); } } }
Java
/** * Copyright (c) 2010 David Dearing */ package com.dpdearing.sandbox.gpsemulator.server; import java.io.IOException; import com.dpdearing.sandbox.gpsemulator.common.LocationService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import de.mud.telnet.TelnetWrapper; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class LocationServiceImpl extends RemoteServiceServlet implements LocationService { /** * The telnet wrapper. */ private TelnetWrapper _telnet; /** * Constructor. */ public LocationServiceImpl() { _telnet = new TelnetWrapper(); } /** * {@inheritDoc} */ public void setPort(final int port) throws IOException { // disconnect from any previous connection _telnet.disconnect(); // reconnect to the new port _telnet.connect("localhost", port); } /** * {@inheritDoc} */ public void setLocation(final double latitude, final double longitude) throws IOException { // telnet the geo fix location: longitude first! _telnet.send("geo fix " + longitude + " " + latitude); } }
Java
/** * Copyright (c) 2010 David Dearing */ package com.dpdearing.sandbox.gpsemulator.common; import java.io.IOException; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * The client side stub for the RPC service. */ @RemoteServiceRelativePath("location") public interface LocationService extends RemoteService { /** * Set the Telnet port * * @param port * the port number * @throws IOException */ void setPort(int port) throws IOException; /** * Set the geospatial location * * @param latitude * latitude * @param longitude * longitude * @throws IOException */ void setLocation(double latitude, double longitude) throws IOException; }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package com.thimbleware.jmemcached.test; import java.io.IOException; import java.net.DatagramSocket; import java.net.ServerSocket; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeSet; /** * Finds currently available server ports. * * @author <a href="http://mina.apache.org">Apache MINA Project</a> * @see <a href="http://www.iana.org/assignments/port-numbers">IANA.org</a> */ public class AvailablePortFinder { /** * The minimum number of server port number. */ public static final int MIN_PORT_NUMBER = 1; /** * The maximum number of server port number. */ public static final int MAX_PORT_NUMBER = 49151; /** * Creates a new instance. */ private AvailablePortFinder() { // Do nothing } /** * Returns the {@link Set} of currently available port numbers * ({@link Integer}). This method is identical to * <code>getAvailablePorts(MIN_PORT_NUMBER, MAX_PORT_NUMBER)</code>. * * WARNING: this can take a very long time. */ public static Set<Integer> getAvailablePorts() { return getAvailablePorts(MIN_PORT_NUMBER, MAX_PORT_NUMBER); } /** * Gets the next available port starting at the lowest port number. * * @throws NoSuchElementException if there are no ports available */ public static int getNextAvailable() { return getNextAvailable(MIN_PORT_NUMBER); } /** * Gets the next available port starting at a port. * * @param fromPort the port to scan for availability * @throws NoSuchElementException if there are no ports available */ public static int getNextAvailable(int fromPort) { if (fromPort < MIN_PORT_NUMBER || fromPort > MAX_PORT_NUMBER) { throw new IllegalArgumentException("Invalid start port: " + fromPort); } for (int i = fromPort; i <= MAX_PORT_NUMBER; i++) { if (available(i)) { return i; } } throw new NoSuchElementException("Could not find an available port " + "above " + fromPort); } /** * Checks to see if a specific port is available. * * @param port the port to check for availability */ public static boolean available(int port) { if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) { throw new IllegalArgumentException("Invalid start port: " + port); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { // Do nothing } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false; } /** * Returns the {@link Set} of currently avaliable port numbers ({@link Integer}) * between the specified port range. * * @throws IllegalArgumentException if port range is not between * {@link #MIN_PORT_NUMBER} and {@link #MAX_PORT_NUMBER} or * <code>fromPort</code> if greater than <code>toPort</code>. */ public static Set<Integer> getAvailablePorts(int fromPort, int toPort) { if (fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER || fromPort > toPort) { throw new IllegalArgumentException("Invalid port range: " + fromPort + " ~ " + toPort); } Set<Integer> result = new TreeSet<Integer>(); for (int i = fromPort; i <= toPort; i++) { ServerSocket s = null; try { s = new ServerSocket(i); result.add(new Integer(i)); } catch (IOException e) { // Do nothing } finally { if (s != null) { try { s.close(); } catch (IOException e) { /* should not be thrown */ } } } } return result; } }
Java
/** * Taken and adapted from the Apache Wicket source. */ /* * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.thimbleware.jmemcached.util; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents an immutable byte count. These static factory methods allow easy * construction of value objects using either long values like bytes(2034) or * megabytes(3): * <p> * <ul> * <li>Bytes.bytes(long) * <li>Bytes.kilobytes(long) * <li>Bytes.megabytes(long) * <li>Bytes.gigabytes(long) * <li>Bytes.terabytes(long) * </ul> * <p> * or double precision floating point values like megabytes(3.2): * <p> * <ul> * <li>Bytes.bytes(double) * <li>Bytes.kilobytes(double) * <li>Bytes.megabytes(double) * <li>Bytes.gigabytes(double) * <li>Bytes.terabytes(double) * </ul> * <p> * In the case of bytes(double), the value will be rounded off to the nearest * integer byte count using Math.round(). * <p> * The precise number of bytes in a Bytes object can be retrieved by calling * bytes(). Approximate values for different units can be retrieved as double * precision values using these methods: * <p> * <ul> * <li>kilobytes() * <li>megabytes() * <li>gigabytes() * <li>terabytes() * </ul> * <p> * Also, value objects can be constructed from strings, optionally using a * Locale with valueOf(String) and valueOf(String,Locale). The string may * contain a decimal or floating point number followed by optional whitespace * followed by a unit (nothing for bytes, K for kilobyte, M for megabytes, G for * gigabytes or T for terabytes) optionally followed by a B (for bytes). Any of * these letters can be any case. So, examples of permissible string values are: * <p> * <ul> * <li>37 (37 bytes) * <li>2.3K (2.3 kilobytes) * <li>2.5 kb (2.5 kilobytes) * <li>4k (4 kilobytes) * <li>35.2GB (35.2 gigabytes) * <li>1024M (1024 megabytes) * </ul> * <p> * Note that if the Locale was not US, the values might substitute "," for "." * as that is the custom in Euroland. * <p> * The toString() methods is smart enough to convert a * given value object to the most appropriate units for the given value. * * @author Jonathan Locke */ public final class Bytes { /** Pattern for string parsing. */ private static final Pattern valuePattern = Pattern.compile( "([0-9]+([\\.,][0-9]+)?)\\s*(|K|M|G|T)B?", Pattern.CASE_INSENSITIVE); /** Maximum bytes value */ public static Bytes MAX = bytes(Long.MAX_VALUE); private long value; /** * Private constructor forces use of static factory methods. * * @param bytes * Number of bytes */ private Bytes(final long bytes) { this.value = bytes; } /** * Instantiate immutable Bytes value object.. * * @param bytes * Value to convert * @return Input as Bytes */ public static Bytes bytes(final long bytes) { return new Bytes(bytes); } /** * Instantiate immutable Bytes value object.. * * @param kilobytes * Value to convert * @return Input as Bytes */ public static Bytes kilobytes(final long kilobytes) { return bytes(kilobytes * 1024); } /** * Instantiate immutable Bytes value object.. * * @param megabytes * Value to convert * @return Input as Bytes */ public static Bytes megabytes(final long megabytes) { return kilobytes(megabytes * 1024); } /** * Instantiate immutable Bytes value object.. * * @param gigabytes * Value to convert * @return Input as Bytes */ public static Bytes gigabytes(final long gigabytes) { return megabytes(gigabytes * 1024); } /** * Instantiate immutable Bytes value object.. * * @param terabytes * Value to convert * @return Input as Bytes */ public static Bytes terabytes(final long terabytes) { return gigabytes(terabytes * 1024); } /** * Instantiate immutable Bytes value object.. * * @param bytes * Value to convert * @return Input as Bytes */ public static Bytes bytes(final double bytes) { return bytes(Math.round(bytes)); } /** * Instantiate immutable Bytes value object.. * * @param kilobytes * Value to convert * @return Input as Bytes */ public static Bytes kilobytes(final double kilobytes) { return bytes(kilobytes * 1024.0); } /** * Instantiate immutable Bytes value object.. * * @param megabytes * Value to convert * @return Input as Bytes */ public static Bytes megabytes(final double megabytes) { return kilobytes(megabytes * 1024.0); } /** * Instantiate immutable Bytes value object.. * * @param gigabytes * Value to convert * @return Input as Bytes */ public static Bytes gigabytes(final double gigabytes) { return megabytes(gigabytes * 1024.0); } /** * Instantiate immutable Bytes value object.. * * @param terabytes * Value to convert * @return Input as Bytes */ public static Bytes terabytes(final double terabytes) { return gigabytes(terabytes * 1024.0); } /** * Gets the byte count represented by this value object. * * @return Byte count */ public final long bytes() { return value; } /** * Gets the byte count in kilobytes. * * @return The value in kilobytes */ public final double kilobytes() { return value / 1024.0; } /** * Gets the byte count in megabytes. * * @return The value in megabytes */ public final double megabytes() { return kilobytes() / 1024.0; } /** * Gets the byte count in gigabytes. * * @return The value in gigabytes */ public final double gigabytes() { return megabytes() / 1024.0; } /** * Gets the byte count in terabytes. * * @return The value in terabytes */ public final double terabytes() { return gigabytes() / 1024.0; } /** * Converts a string to a number of bytes. Strings consist of a floating * point value followed by K, M, G or T for kilobytes, megabytes, gigabytes * or terabytes, respectively. The abbreviations KB, MB, GB and TB are also * accepted. Matching is case insensitive. * * @param string * The string to convert * @param locale * The Locale to be used for transformation * @return The Bytes value for the string * @throws NumberFormatException */ public static Bytes valueOf(final String string, final Locale locale) throws NumberFormatException { final Matcher matcher = valuePattern.matcher(string); // Valid input? if (matcher.matches()) { try { // Get double precision value final double value = NumberFormat.getNumberInstance(locale).parse(matcher.group(1)) .doubleValue(); // Get units specified final String units = matcher.group(3); if (units.equalsIgnoreCase("")) { return bytes(value); } else if (units.equalsIgnoreCase("K")) { return kilobytes(value); } else if (units.equalsIgnoreCase("M")) { return megabytes(value); } else if (units.equalsIgnoreCase("G")) { return gigabytes(value); } else if (units.equalsIgnoreCase("T")) { return terabytes(value); } else { throw new NumberFormatException("Units not recognized: " + string); } } catch (ParseException e) { throw new NumberFormatException("Unable to parse numeric part: " + string); } } else { throw new NumberFormatException("Unable to parse bytes: " + string); } } /** * Converts a string to a number of bytes. Strings consist of a floating * point value followed by K, M, G or T for kilobytes, megabytes, gigabytes * or terabytes, respectively. The abbreviations KB, MB, GB and TB are also * accepted. Matching is case insensitive. * * @param string * The string to convert * @return The Bytes value for the string * @throws NumberFormatException */ public static Bytes valueOf(final String string) throws NumberFormatException { return valueOf(string, Locale.getDefault()); } /** * Converts this byte count to a string using the given locale. * * @return The string for this byte count */ public String toString() { if (value >= 0) { if (terabytes() >= 1.0) { return unitString(gigabytes(), "T"); } if (gigabytes() >= 1.0) { return unitString(gigabytes(), "G"); } if (megabytes() >= 1.0) { return unitString(megabytes(), "M"); } if (kilobytes() >= 1.0) { return unitString(kilobytes(), "K"); } return Long.toString(value) + " bytes"; } else { return "N/A"; } } /** * Convert value to formatted floating point number and units. * * @param value * The value * @param units * The units * @return The formatted string */ private String unitString(final double value, final String units) { return "" + units; } }
Java
/** * Copyright 2008 ThimbleWare Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thimbleware.jmemcached; import com.thimbleware.jmemcached.storage.bytebuffer.BlockStorageCacheStorage; import com.thimbleware.jmemcached.storage.CacheStorage; import com.thimbleware.jmemcached.storage.bytebuffer.BlockStoreFactory; import com.thimbleware.jmemcached.storage.bytebuffer.ByteBufferBlockStore; import org.apache.commons.cli.*; import java.net.InetSocketAddress; import com.thimbleware.jmemcached.util.Bytes; import com.thimbleware.jmemcached.storage.hash.ConcurrentLinkedHashMap; import com.thimbleware.jmemcached.storage.mmap.MemoryMappedBlockStore; /** * Command line interface to the Java memcache daemon. * * Arguments in general parallel those of the C implementation. */ public class Main { public static void main(String[] args) throws Exception { // look for external log4j.properties // setup command line options Options options = new Options(); options.addOption("h", "help", false, "print this help screen"); options.addOption("bl", "block-store", false, "use external (from JVM) heap"); options.addOption("f", "mapped-file", false, "use external (from JVM) heap through a memory mapped file"); options.addOption("bs", "block-size", true, "block size (in bytes) for external memory mapped file allocator. default is 8 bytes"); options.addOption("i", "idle", true, "disconnect after idle <x> seconds"); options.addOption("p", "port", true, "port to listen on"); options.addOption("m", "memory", true, "max memory to use; in bytes, specify K, kb, M, GB for larger units"); options.addOption("c", "ceiling", true, "ceiling memory to use; in bytes, specify K, kb, M, GB for larger units"); options.addOption("l", "listen", true, "Address to listen on"); options.addOption("s", "size", true, "max items"); options.addOption("b", "binary", false, "binary protocol mode"); options.addOption("V", false, "Show version number"); options.addOption("v", false, "verbose (show commands)"); // read command line options CommandLineParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args); if (cmdline.hasOption("help") || cmdline.hasOption("h")) { System.out.println("Memcached Version " + MemCacheDaemon.memcachedVersion); System.out.println("http://thimbleware.com/projects/memcached\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar memcached.jar", options); return; } if (cmdline.hasOption("V")) { System.out.println("Memcached Version " + MemCacheDaemon.memcachedVersion); return; } int port = 11211; if (cmdline.hasOption("p")) { port = Integer.parseInt(cmdline.getOptionValue("p")); } else if (cmdline.hasOption("port")) { port = Integer.parseInt(cmdline.getOptionValue("port")); } InetSocketAddress addr = new InetSocketAddress(port); if (cmdline.hasOption("l")) { addr = new InetSocketAddress(cmdline.getOptionValue("l"), port); } else if (cmdline.hasOption("listen")) { addr = new InetSocketAddress(cmdline.getOptionValue("listen"), port); } int max_size = 1000000; if (cmdline.hasOption("s")) max_size = (int)Bytes.valueOf(cmdline.getOptionValue("s")).bytes(); else if (cmdline.hasOption("size")) max_size = (int)Bytes.valueOf(cmdline.getOptionValue("size")).bytes(); System.out.println("Setting max cache elements to " + String.valueOf(max_size)); int idle = -1; if (cmdline.hasOption("i")) { idle = Integer.parseInt(cmdline.getOptionValue("i")); } else if (cmdline.hasOption("idle")) { idle = Integer.parseInt(cmdline.getOptionValue("idle")); } boolean memoryMapped = false; if (cmdline.hasOption("f")) { memoryMapped = true; } else if (cmdline.hasOption("mapped-file")) { memoryMapped = true; } boolean blockStore = false; if (cmdline.hasOption("bl")) { blockStore = true; } else if (cmdline.hasOption("block-store")) { blockStore = true; } boolean verbose = false; if (cmdline.hasOption("v")) { verbose = true; } long ceiling; if (cmdline.hasOption("c")) { ceiling = Bytes.valueOf(cmdline.getOptionValue("c")).bytes(); System.out.println("Setting ceiling memory size to " + Bytes.bytes(ceiling).megabytes() + "M"); } else if (cmdline.hasOption("ceiling")) { ceiling = Bytes.valueOf(cmdline.getOptionValue("ceiling")).bytes(); System.out.println("Setting ceiling memory size to " + Bytes.bytes(ceiling).megabytes() + "M"); } else if (!memoryMapped ){ ceiling = 1024000; System.out.println("Setting ceiling memory size to default limit of " + Bytes.bytes(ceiling).megabytes() + "M"); } else { System.out.println("ERROR : ceiling memory size mandatory when external memory mapped file is specified"); return; } boolean binary = false; if (cmdline.hasOption("b")) { binary = true; } int blockSize = 8; if (!memoryMapped && (cmdline.hasOption("bs") || cmdline.hasOption("block-size"))) { System.out.println("WARN : block size option is only valid for memory mapped external heap storage; ignoring"); } else if (cmdline.hasOption("bs")) { blockSize = Integer.parseInt(cmdline.getOptionValue("bs")); } else if (cmdline.hasOption("block-size")) { blockSize = Integer.parseInt(cmdline.getOptionValue("block-size")); } long maxBytes; if (cmdline.hasOption("m")) { maxBytes = Bytes.valueOf(cmdline.getOptionValue("m")).bytes(); System.out.println("Setting max memory size to " + Bytes.bytes(maxBytes).gigabytes() + "GB"); } else if (cmdline.hasOption("memory")) { maxBytes = Bytes.valueOf(cmdline.getOptionValue("memory")).bytes(); System.out.println("Setting max memory size to " + Bytes.bytes(maxBytes).gigabytes() + "GB"); } else if (!memoryMapped) { maxBytes = Runtime.getRuntime().maxMemory(); System.out.println("Setting max memory size to JVM limit of " + Bytes.bytes(maxBytes).gigabytes() + "GB"); } else { System.out.println("ERROR : max memory size and ceiling size are mandatory when external memory mapped file is specified"); return; } if (!memoryMapped && !blockStore && maxBytes > Runtime.getRuntime().maxMemory()) { System.out.println("ERROR : JVM heap size is not big enough. use '-Xmx" + String.valueOf(maxBytes / 1024000) + "m' java argument before the '-jar' option."); return; } else if ((memoryMapped || !blockStore) && maxBytes > Integer.MAX_VALUE) { System.out.println("ERROR : when external memory mapped, memory size may not exceed the size of Integer.MAX_VALUE (" + Bytes.bytes(Integer.MAX_VALUE).gigabytes() + "GB"); return; } // create daemon and start it final MemCacheDaemon<LocalCacheElement> daemon = new MemCacheDaemon<LocalCacheElement>(); CacheStorage<Key, LocalCacheElement> storage; if (blockStore) { BlockStoreFactory blockStoreFactory = ByteBufferBlockStore.getFactory(); storage = new BlockStorageCacheStorage(8, (int)ceiling, blockSize, maxBytes, max_size, blockStoreFactory); } else if (memoryMapped) { BlockStoreFactory blockStoreFactory = MemoryMappedBlockStore.getFactory(); storage = new BlockStorageCacheStorage(8, (int)ceiling, blockSize, maxBytes, max_size, blockStoreFactory); } else { storage = ConcurrentLinkedHashMap.create(ConcurrentLinkedHashMap.EvictionPolicy.FIFO, max_size, maxBytes); } daemon.setCache(new CacheImpl(storage)); daemon.setBinary(binary); daemon.setAddr(addr); daemon.setIdleTime(idle); daemon.setVerbose(verbose); daemon.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { if (daemon.isRunning()) daemon.stop(); } })); } }
Java
package com.thimbleware.jmemcached; import org.jboss.netty.buffer.ChannelBuffer; import java.util.Arrays; /** * Represents a given key for lookup in the cache. * * Wraps a byte array with a precomputed hashCode. */ public class Key { public ChannelBuffer bytes; private int hashCode; public Key(ChannelBuffer bytes) { this.bytes = bytes.slice(); this.hashCode = this.bytes.hashCode(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Key key1 = (Key) o; bytes.readerIndex(0); key1.bytes.readerIndex(0); if (!bytes.equals(key1.bytes)) return false; return true; } @Override public int hashCode() { return hashCode; } }
Java
/** * Copyright 2008 ThimbleWare Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thimbleware.jmemcached.protocol; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** */ public enum Op { GET, GETS, APPEND, PREPEND, DELETE, DECR, INCR, REPLACE, ADD, SET, CAS, STATS, VERSION, QUIT, FLUSH_ALL, VERBOSITY; private static Map<ChannelBuffer, Op> opsbf = new HashMap<ChannelBuffer, Op>(); static { for (int x = 0 ; x < Op.values().length; x++) { byte[] bytes = Op.values()[x].toString().toLowerCase().getBytes(); opsbf.put(ChannelBuffers.wrappedBuffer(bytes), Op.values()[x]); } } public static Op FindOp(ChannelBuffer cmd) { cmd.readerIndex(0); return opsbf.get(cmd); } }
Java
package com.thimbleware.jmemcached.protocol.binary; import com.thimbleware.jmemcached.protocol.Op; import com.thimbleware.jmemcached.protocol.ResponseMessage; import com.thimbleware.jmemcached.protocol.exceptions.UnknownCommandException; import com.thimbleware.jmemcached.CacheElement; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteOrder; import java.util.Set; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * */ // TODO refactor so this can be unit tested separate from netty? scalacheck? @ChannelHandler.Sharable public class MemcachedBinaryResponseEncoder<CACHE_ELEMENT extends CacheElement> extends SimpleChannelUpstreamHandler { private ConcurrentHashMap<Integer, ChannelBuffer> corkedBuffers = new ConcurrentHashMap<Integer, ChannelBuffer>(); final Logger logger = LoggerFactory.getLogger(MemcachedBinaryResponseEncoder.class); public static enum ResponseCode { OK(0x0000), KEYNF(0x0001), KEYEXISTS(0x0002), TOOLARGE(0x0003), INVARG(0x0004), NOT_STORED(0x0005), UNKNOWN(0x0081), OOM(0x00082); public short code; ResponseCode(int code) { this.code = (short)code; } } public ResponseCode getStatusCode(ResponseMessage command) { Op cmd = command.cmd.op; if (cmd == Op.GET || cmd == Op.GETS) { return ResponseCode.OK; } else if (cmd == Op.SET || cmd == Op.CAS || cmd == Op.ADD || cmd == Op.REPLACE || cmd == Op.APPEND || cmd == Op.PREPEND) { switch (command.response) { case EXISTS: return ResponseCode.KEYEXISTS; case NOT_FOUND: return ResponseCode.KEYNF; case NOT_STORED: return ResponseCode.NOT_STORED; case STORED: return ResponseCode.OK; } } else if (cmd == Op.INCR || cmd == Op.DECR) { return command.incrDecrResponse == null ? ResponseCode.KEYNF : ResponseCode.OK; } else if (cmd == Op.DELETE) { switch (command.deleteResponse) { case DELETED: return ResponseCode.OK; case NOT_FOUND: return ResponseCode.KEYNF; } } else if (cmd == Op.STATS) { return ResponseCode.OK; } else if (cmd == Op.VERSION) { return ResponseCode.OK; } else if (cmd == Op.FLUSH_ALL) { return ResponseCode.OK; } return ResponseCode.UNKNOWN; } public ChannelBuffer constructHeader(MemcachedBinaryCommandDecoder.BinaryOp bcmd, ChannelBuffer extrasBuffer, ChannelBuffer keyBuffer, ChannelBuffer valueBuffer, short responseCode, int opaqueValue, long casUnique) { // take the ResponseMessage and turn it into a binary payload. ChannelBuffer header = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24); header.writeByte((byte)0x81); // magic header.writeByte(bcmd.code); // opcode short keyLength = (short) (keyBuffer != null ? keyBuffer.capacity() :0); header.writeShort(keyLength); int extrasLength = extrasBuffer != null ? extrasBuffer.capacity() : 0; header.writeByte((byte) extrasLength); // extra length = flags + expiry header.writeByte((byte)0); // data type unused header.writeShort(responseCode); // status code int dataLength = valueBuffer != null ? valueBuffer.capacity() : 0; header.writeInt(dataLength + keyLength + extrasLength); // data length header.writeInt(opaqueValue); // opaque header.writeLong(casUnique); return header; } /** * Handle exceptions in protocol processing. Exceptions are either client or internal errors. Report accordingly. * * @param ctx * @param e * @throws Exception */ @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { try { throw e.getCause(); } catch (UnknownCommandException unknownCommand) { if (ctx.getChannel().isOpen()) ctx.getChannel().write(constructHeader(MemcachedBinaryCommandDecoder.BinaryOp.Noop, null, null, null, (short)0x0081, 0, 0)); } catch (Throwable err) { logger.error("error", err); if (ctx.getChannel().isOpen()) ctx.getChannel().close(); } } @Override @SuppressWarnings("unchecked") public void messageReceived(ChannelHandlerContext channelHandlerContext, MessageEvent messageEvent) throws Exception { ResponseMessage<CACHE_ELEMENT> command = (ResponseMessage<CACHE_ELEMENT>) messageEvent.getMessage(); Object additional = messageEvent.getMessage(); MemcachedBinaryCommandDecoder.BinaryOp bcmd = MemcachedBinaryCommandDecoder.BinaryOp.forCommandMessage(command.cmd); // write extras == flags & expiry ChannelBuffer extrasBuffer = null; // write key if there is one ChannelBuffer keyBuffer = null; if (bcmd.addKeyToResponse && command.cmd.keys != null && command.cmd.keys.size() != 0) { keyBuffer = ChannelBuffers.wrappedBuffer(command.cmd.keys.get(0).bytes); } // write value if there is one ChannelBuffer valueBuffer = null; if (command.elements != null) { extrasBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 4); CacheElement element = command.elements[0]; extrasBuffer.writeShort((short) (element != null ? element.getExpire() : 0)); extrasBuffer.writeShort((short) (element != null ? element.getFlags() : 0)); if ((command.cmd.op == Op.GET || command.cmd.op == Op.GETS)) { if (element != null) { valueBuffer = ChannelBuffers.wrappedBuffer(element.getData()); } else { valueBuffer = ChannelBuffers.buffer(0); } } else if (command.cmd.op == Op.INCR || command.cmd.op == Op.DECR) { valueBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 8); valueBuffer.writeLong(command.incrDecrResponse); } } else if (command.cmd.op == Op.INCR || command.cmd.op == Op.DECR) { valueBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 8); valueBuffer.writeLong(command.incrDecrResponse); } long casUnique = 0; if (command.elements != null && command.elements.length != 0 && command.elements[0] != null) { casUnique = command.elements[0].getCasUnique(); } // stats is special -- with it, we write N times, one for each stat, then an empty payload if (command.cmd.op == Op.STATS) { // first uncork any corked buffers if (corkedBuffers.containsKey(command.cmd.opaque)) uncork(command.cmd.opaque, messageEvent.getChannel()); for (Map.Entry<String, Set<String>> statsEntries : command.stats.entrySet()) { for (String stat : statsEntries.getValue()) { keyBuffer = ChannelBuffers.wrappedBuffer(ByteOrder.BIG_ENDIAN, statsEntries.getKey().getBytes(MemcachedBinaryCommandDecoder.USASCII)); valueBuffer = ChannelBuffers.wrappedBuffer(ByteOrder.BIG_ENDIAN, stat.getBytes(MemcachedBinaryCommandDecoder.USASCII)); ChannelBuffer headerBuffer = constructHeader(bcmd, extrasBuffer, keyBuffer, valueBuffer, getStatusCode(command).code, command.cmd.opaque, casUnique); writePayload(messageEvent, extrasBuffer, keyBuffer, valueBuffer, headerBuffer); } } keyBuffer = null; valueBuffer = null; ChannelBuffer headerBuffer = constructHeader(bcmd, extrasBuffer, keyBuffer, valueBuffer, getStatusCode(command).code, command.cmd.opaque, casUnique); writePayload(messageEvent, extrasBuffer, keyBuffer, valueBuffer, headerBuffer); } else { ChannelBuffer headerBuffer = constructHeader(bcmd, extrasBuffer, keyBuffer, valueBuffer, getStatusCode(command).code, command.cmd.opaque, casUnique); // write everything // is the command 'quiet?' if so, then we append to our 'corked' buffer until a non-corked command comes along if (bcmd.noreply) { int totalCapacity = headerBuffer.capacity() + (extrasBuffer != null ? extrasBuffer.capacity() : 0) + (keyBuffer != null ? keyBuffer.capacity() : 0) + (valueBuffer != null ? valueBuffer.capacity() : 0); ChannelBuffer corkedResponse = cork(command.cmd.opaque, totalCapacity); corkedResponse.writeBytes(headerBuffer); if (extrasBuffer != null) corkedResponse.writeBytes(extrasBuffer); if (keyBuffer != null) corkedResponse.writeBytes(keyBuffer); if (valueBuffer != null) corkedResponse.writeBytes(valueBuffer); } else { // first write out any corked responses if (corkedBuffers.containsKey(command.cmd.opaque)) uncork(command.cmd.opaque, messageEvent.getChannel()); writePayload(messageEvent, extrasBuffer, keyBuffer, valueBuffer, headerBuffer); } } } private ChannelBuffer cork(int opaque, int totalCapacity) { if (corkedBuffers.containsKey(opaque)) { ChannelBuffer corkedResponse = corkedBuffers.get(opaque); ChannelBuffer oldBuffer = corkedResponse; corkedResponse = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, totalCapacity + corkedResponse.capacity()); corkedResponse.writeBytes(oldBuffer); oldBuffer.clear(); corkedBuffers.remove(opaque); corkedBuffers.put(opaque, corkedResponse); return corkedResponse; } else { ChannelBuffer buffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, totalCapacity); corkedBuffers.put(opaque, buffer); return buffer; } } private void uncork(int opaque, Channel channel) { ChannelBuffer corkedBuffer = corkedBuffers.get(opaque); assert corkedBuffer != null; channel.write(corkedBuffer); corkedBuffers.remove(opaque); } private void writePayload(MessageEvent messageEvent, ChannelBuffer extrasBuffer, ChannelBuffer keyBuffer, ChannelBuffer valueBuffer, ChannelBuffer headerBuffer) { if (messageEvent.getChannel().isOpen()) { messageEvent.getChannel().write(headerBuffer); if (extrasBuffer != null) messageEvent.getChannel().write(extrasBuffer); if (keyBuffer != null) messageEvent.getChannel().write(keyBuffer); if (valueBuffer != null) messageEvent.getChannel().write(valueBuffer); } } }
Java
package com.thimbleware.jmemcached.protocol.binary; import com.thimbleware.jmemcached.Cache; import com.thimbleware.jmemcached.protocol.MemcachedCommandHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.group.DefaultChannelGroup; public class MemcachedBinaryPipelineFactory implements ChannelPipelineFactory { private final MemcachedBinaryCommandDecoder decoder = new MemcachedBinaryCommandDecoder(); private final MemcachedCommandHandler memcachedCommandHandler; private final MemcachedBinaryResponseEncoder memcachedBinaryResponseEncoder = new MemcachedBinaryResponseEncoder(); public MemcachedBinaryPipelineFactory(Cache cache, String version, boolean verbose, int idleTime, DefaultChannelGroup channelGroup) { memcachedCommandHandler = new MemcachedCommandHandler(cache, version, verbose, idleTime, channelGroup); } public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline( decoder, memcachedCommandHandler, memcachedBinaryResponseEncoder ); } }
Java
package com.thimbleware.jmemcached.protocol.binary; import com.thimbleware.jmemcached.Key; import com.thimbleware.jmemcached.LocalCacheElement; import com.thimbleware.jmemcached.CacheElement; import com.thimbleware.jmemcached.protocol.Op; import com.thimbleware.jmemcached.protocol.CommandMessage; import com.thimbleware.jmemcached.protocol.exceptions.MalformedCommandException; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.frame.FrameDecoder; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.nio.ByteOrder; /** */ @ChannelHandler.Sharable public class MemcachedBinaryCommandDecoder extends FrameDecoder { public static final Charset USASCII = Charset.forName("US-ASCII"); public static enum BinaryOp { Get(0x00, Op.GET, false), Set(0x01, Op.SET, false), Add(0x02, Op.ADD, false), Replace(0x03, Op.REPLACE, false), Delete(0x04, Op.DELETE, false), Increment(0x05, Op.INCR, false), Decrement(0x06, Op.DECR, false), Quit(0x07, Op.QUIT, false), Flush(0x08, Op.FLUSH_ALL, false), GetQ(0x09, Op.GET, false), Noop(0x0A, null, false), Version(0x0B, Op.VERSION, false), GetK(0x0C, Op.GET, false, true), GetKQ(0x0D, Op.GET, true, true), Append(0x0E, Op.APPEND, false), Prepend(0x0F, Op.PREPEND, false), Stat(0x10, Op.STATS, false), SetQ(0x11, Op.SET, true), AddQ(0x12, Op.ADD, true), ReplaceQ(0x13, Op.REPLACE, true), DeleteQ(0x14, Op.DELETE, true), IncrementQ(0x15, Op.INCR, true), DecrementQ(0x16, Op.DECR, true), QuitQ(0x17, Op.QUIT, true), FlushQ(0x18, Op.FLUSH_ALL, true), AppendQ(0x19, Op.APPEND, true), PrependQ(0x1A, Op.PREPEND, true); public byte code; public Op correspondingOp; public boolean noreply; public boolean addKeyToResponse = false; BinaryOp(int code, Op correspondingOp, boolean noreply) { this.code = (byte)code; this.correspondingOp = correspondingOp; this.noreply = noreply; } BinaryOp(int code, Op correspondingOp, boolean noreply, boolean addKeyToResponse) { this.code = (byte)code; this.correspondingOp = correspondingOp; this.noreply = noreply; this.addKeyToResponse = addKeyToResponse; } public static BinaryOp forCommandMessage(CommandMessage msg) { for (BinaryOp binaryOp : values()) { if (binaryOp.correspondingOp == msg.op && binaryOp.noreply == msg.noreply && binaryOp.addKeyToResponse == msg.addKeyToResponse) { return binaryOp; } } return null; } } protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception { // need at least 24 bytes, to get header if (channelBuffer.readableBytes() < 24) return null; // get the header channelBuffer.markReaderIndex(); ChannelBuffer headerBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24); channelBuffer.readBytes(headerBuffer); short magic = headerBuffer.readUnsignedByte(); // magic should be 0x80 if (magic != 0x80) { headerBuffer.resetReaderIndex(); throw new MalformedCommandException("binary request payload is invalid, magic byte incorrect"); } short opcode = headerBuffer.readUnsignedByte(); short keyLength = headerBuffer.readShort(); short extraLength = headerBuffer.readUnsignedByte(); short dataType = headerBuffer.readUnsignedByte(); // unused short reserved = headerBuffer.readShort(); // unused int totalBodyLength = headerBuffer.readInt(); int opaque = headerBuffer.readInt(); long cas = headerBuffer.readLong(); // we want the whole of totalBodyLength; otherwise, keep waiting. if (channelBuffer.readableBytes() < totalBodyLength) { channelBuffer.resetReaderIndex(); return null; } // This assumes correct order in the enum. If that ever changes, we will have to scan for 'code' field. BinaryOp bcmd = BinaryOp.values()[opcode]; Op cmdType = bcmd.correspondingOp; CommandMessage cmdMessage = CommandMessage.command(cmdType); cmdMessage.noreply = bcmd.noreply; cmdMessage.cas_key = cas; cmdMessage.opaque = opaque; cmdMessage.addKeyToResponse = bcmd.addKeyToResponse; // get extras. could be empty. ChannelBuffer extrasBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, extraLength); channelBuffer.readBytes(extrasBuffer); // get the key if any if (keyLength != 0) { ChannelBuffer keyBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, keyLength); channelBuffer.readBytes(keyBuffer); ArrayList<Key> keys = new ArrayList<Key>(); keys.add(new Key(keyBuffer.copy())); cmdMessage.keys = keys; if (cmdType == Op.ADD || cmdType == Op.SET || cmdType == Op.REPLACE || cmdType == Op.APPEND || cmdType == Op.PREPEND) { // TODO these are backwards from the spec, but seem to be what spymemcached demands -- which has the mistake?! long expire = ((short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0)) * 1000; short flags = (short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0); // the remainder of the message -- that is, totalLength - (keyLength + extraLength) should be the payload int size = totalBodyLength - keyLength - extraLength; cmdMessage.element = new LocalCacheElement(new Key(keyBuffer.slice()), flags, expire != 0 && expire < CacheElement.THIRTY_DAYS ? LocalCacheElement.Now() + expire : expire, 0L); ChannelBuffer data = ChannelBuffers.buffer(size); channelBuffer.readBytes(data); cmdMessage.element.setData(data); } else if (cmdType == Op.INCR || cmdType == Op.DECR) { long initialValue = extrasBuffer.readUnsignedInt(); long amount = extrasBuffer.readUnsignedInt(); long expiration = extrasBuffer.readUnsignedInt(); cmdMessage.incrAmount = (int) amount; cmdMessage.incrExpiry = (int) expiration; } } return cmdMessage; } }
Java
package com.thimbleware.jmemcached.protocol; import com.thimbleware.jmemcached.Cache; import com.thimbleware.jmemcached.CacheElement; import java.io.Serializable; import java.util.Set; import java.util.Map; /** * Represents the response to a command. */ public final class ResponseMessage<CACHE_ELEMENT extends CacheElement> implements Serializable { public ResponseMessage(CommandMessage cmd) { this.cmd = cmd; } public CommandMessage<CACHE_ELEMENT> cmd; public CACHE_ELEMENT[] elements; public Cache.StoreResponse response; public Map<String, Set<String>> stats; public String version; public Cache.DeleteResponse deleteResponse; public Integer incrDecrResponse; public boolean flushSuccess; public ResponseMessage<CACHE_ELEMENT> withElements(CACHE_ELEMENT[] elements) { this.elements = elements; return this; } public ResponseMessage<CACHE_ELEMENT> withResponse(Cache.StoreResponse response) { this.response = response; return this; } public ResponseMessage<CACHE_ELEMENT> withDeleteResponse(Cache.DeleteResponse deleteResponse) { this.deleteResponse = deleteResponse; return this; } public ResponseMessage<CACHE_ELEMENT> withIncrDecrResponse(Integer incrDecrResp) { this.incrDecrResponse = incrDecrResp; return this; } public ResponseMessage<CACHE_ELEMENT> withStatResponse(Map<String, Set<String>> stats) { this.stats = stats; return this; } public ResponseMessage<CACHE_ELEMENT> withFlushResponse(boolean success) { this.flushSuccess = success; return this; } }
Java
/** * Copyright 2008 ThimbleWare Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thimbleware.jmemcached.protocol; import com.thimbleware.jmemcached.CacheElement; import com.thimbleware.jmemcached.Key; import org.jboss.netty.buffer.ChannelBuffer; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * The payload object holding the parsed message. */ public final class CommandMessage<CACHE_ELEMENT extends CacheElement> implements Serializable { public Op op; public CACHE_ELEMENT element; public List<Key> keys; public boolean noreply; public long cas_key; public int time = 0; public int opaque; public boolean addKeyToResponse = false; public int incrExpiry; public int incrAmount; private CommandMessage(Op op) { this.op = op; element = null; } public void setKey(ChannelBuffer key) { this.keys = new ArrayList<Key>(); this.keys.add(new Key(key)); } public void setKeys(List<ChannelBuffer> keys) { this.keys = new ArrayList<Key>(keys.size()); for (ChannelBuffer key : keys) { this.keys.add(new Key(key)); } } public static CommandMessage command(Op operation) { return new CommandMessage(operation); } }
Java
package com.thimbleware.jmemcached.protocol.exceptions; /** */ public class ClientException extends Exception { public ClientException() { } public ClientException(String s) { super(s); } public ClientException(String s, Throwable throwable) { super(s, throwable); } public ClientException(Throwable throwable) { super(throwable); } }
Java
package com.thimbleware.jmemcached.protocol.exceptions; /** */ public class InvalidProtocolStateException extends Exception { public InvalidProtocolStateException() { } public InvalidProtocolStateException(String s) { super(s); } public InvalidProtocolStateException(String s, Throwable throwable) { super(s, throwable); } public InvalidProtocolStateException(Throwable throwable) { super(throwable); } }
Java
package com.thimbleware.jmemcached.protocol.exceptions; /** */ public class UnknownCommandException extends ClientException { public UnknownCommandException() { } public UnknownCommandException(String s) { super(s); } public UnknownCommandException(String s, Throwable throwable) { super(s, throwable); } public UnknownCommandException(Throwable throwable) { super(throwable); } }
Java
package com.thimbleware.jmemcached.protocol.exceptions; /** */ public class IncorrectlyTerminatedPayloadException extends ClientException { public IncorrectlyTerminatedPayloadException() { } public IncorrectlyTerminatedPayloadException(String s) { super(s); } public IncorrectlyTerminatedPayloadException(String s, Throwable throwable) { super(s, throwable); } public IncorrectlyTerminatedPayloadException(Throwable throwable) { super(throwable); } }
Java
package com.thimbleware.jmemcached.protocol.exceptions; /** */ public class MalformedCommandException extends ClientException { public MalformedCommandException() { } public MalformedCommandException(String s) { super(s); } public MalformedCommandException(String s, Throwable throwable) { super(s, throwable); } public MalformedCommandException(Throwable throwable) { super(throwable); } }
Java
package com.thimbleware.jmemcached.protocol; import java.io.Serializable; /** * Class for holding the current session status. */ public final class SessionStatus implements Serializable { /** * Possible states that the current session is in. */ public static enum State { WAITING_FOR_DATA, READY, PROCESSING_MULTILINE, } // the state the session is in public State state; // if we are waiting for more data, how much? public int bytesNeeded; // the current working command public CommandMessage cmd; public SessionStatus() { ready(); } public SessionStatus ready() { this.cmd = null; this.bytesNeeded = -1; this.state = State.READY; return this; } public SessionStatus processingMultiline() { this.state = State.PROCESSING_MULTILINE; return this; } public SessionStatus needMore(int size, CommandMessage cmd) { this.cmd = cmd; this.bytesNeeded = size; this.state = State.WAITING_FOR_DATA; return this; } }
Java
package com.thimbleware.jmemcached.protocol.text; import com.thimbleware.jmemcached.CacheElement; import com.thimbleware.jmemcached.Key; import com.thimbleware.jmemcached.LocalCacheElement; import com.thimbleware.jmemcached.protocol.CommandMessage; import com.thimbleware.jmemcached.protocol.Op; import com.thimbleware.jmemcached.protocol.SessionStatus; import com.thimbleware.jmemcached.protocol.exceptions.IncorrectlyTerminatedPayloadException; import com.thimbleware.jmemcached.protocol.exceptions.InvalidProtocolStateException; import com.thimbleware.jmemcached.protocol.exceptions.MalformedCommandException; import com.thimbleware.jmemcached.protocol.exceptions.UnknownCommandException; import com.thimbleware.jmemcached.util.BufferUtils; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferIndexFinder; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.frame.FrameDecoder; import java.util.ArrayList; import java.util.List; /** * The MemcachedCommandDecoder is responsible for taking lines from the MemcachedFrameDecoder and parsing them * into CommandMessage instances for handling by the MemcachedCommandHandler * <p/> * Protocol status is held in the SessionStatus instance which is shared between each of the decoders in the pipeline. */ public final class MemcachedCommandDecoder extends FrameDecoder { private static final int MIN_BYTES_LINE = 2; private SessionStatus status; private static final ChannelBuffer NOREPLY = ChannelBuffers.wrappedBuffer("noreply".getBytes()); public MemcachedCommandDecoder(SessionStatus status) { this.status = status; } /** * Index finder which locates a byte which is neither a {@code CR ('\r')} * nor a {@code LF ('\n')}. */ static ChannelBufferIndexFinder CRLF_OR_WS = new ChannelBufferIndexFinder() { public final boolean find(ChannelBuffer buffer, int guessedIndex) { byte b = buffer.getByte(guessedIndex); return b == ' ' || b == '\r' || b == '\n'; } }; static boolean eol(int pos, ChannelBuffer buffer) { return buffer.readableBytes() >= MIN_BYTES_LINE && buffer.getByte(buffer.readerIndex() + pos) == '\r' && buffer.getByte(buffer.readerIndex() + pos+1) == '\n'; } @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (status.state == SessionStatus.State.READY) { ChannelBuffer in = buffer.slice(); // split into pieces List<ChannelBuffer> pieces = new ArrayList<ChannelBuffer>(6); if (in.readableBytes() < MIN_BYTES_LINE) return null; int pos = in.bytesBefore(CRLF_OR_WS); boolean eol = false; do { if (pos != -1) { eol = eol(pos, in); int skip = eol ? MIN_BYTES_LINE : 1; ChannelBuffer slice = in.readSlice(pos); slice.readerIndex(0); pieces.add(slice); in.skipBytes(skip); if (eol) break; } } while ((pos = in.bytesBefore(CRLF_OR_WS)) != -1); if (eol) { buffer.skipBytes(in.readerIndex()); return processLine(pieces, channel, ctx); } if (status.state != SessionStatus.State.WAITING_FOR_DATA) status.ready(); } else if (status.state == SessionStatus.State.WAITING_FOR_DATA) { if (buffer.readableBytes() >= status.bytesNeeded + MemcachedResponseEncoder.CRLF.capacity()) { // verify delimiter matches at the right location ChannelBuffer dest = buffer.slice(buffer.readerIndex() + status.bytesNeeded, MIN_BYTES_LINE); if (!dest.equals(MemcachedResponseEncoder.CRLF)) { // before we throw error... we're ready for the next command status.ready(); // error, no delimiter at end of payload throw new IncorrectlyTerminatedPayloadException("payload not terminated correctly"); } else { status.processingMultiline(); // There's enough bytes in the buffer and the delimiter is at the end. Read it. ChannelBuffer result = buffer.slice(buffer.readerIndex(), status.bytesNeeded); buffer.skipBytes(status.bytesNeeded + MemcachedResponseEncoder.CRLF.capacity()); CommandMessage commandMessage = continueSet(channel, status, result, ctx); if (status.state != SessionStatus.State.WAITING_FOR_DATA) status.ready(); return commandMessage; } } } else { throw new InvalidProtocolStateException("invalid protocol state"); } return null; } /** * Process an individual complete protocol line and either passes the command for processing by the * session handler, or (in the case of SET-type commands) partially parses the command and sets the session into * a state to wait for additional data. * * @param parts the (originally space separated) parts of the command * @param channel the netty channel to operate on * @param channelHandlerContext the netty channel handler context * @throws com.thimbleware.jmemcached.protocol.exceptions.MalformedCommandException * @throws com.thimbleware.jmemcached.protocol.exceptions.UnknownCommandException */ private Object processLine(List<ChannelBuffer> parts, Channel channel, ChannelHandlerContext channelHandlerContext) throws UnknownCommandException, MalformedCommandException { final int numParts = parts.size(); // Turn the command into an enum for matching on Op op; try { op = Op.FindOp(parts.get(0)); if (op == null) throw new IllegalArgumentException("unknown operation: " + parts.get(0).toString()); } catch (IllegalArgumentException e) { throw new UnknownCommandException("unknown operation: " + parts.get(0).toString()); } // Produce the initial command message, for filling in later CommandMessage cmd = CommandMessage.command(op); switch (op) { case DELETE: cmd.setKey(parts.get(1)); if (numParts >= MIN_BYTES_LINE) { if (parts.get(numParts - 1).equals(NOREPLY)) { cmd.noreply = true; if (numParts == 4) cmd.time = BufferUtils.atoi(parts.get(MIN_BYTES_LINE)); } else if (numParts == 3) cmd.time = BufferUtils.atoi(parts.get(MIN_BYTES_LINE)); } return cmd; case DECR: case INCR: // Malformed if (numParts < MIN_BYTES_LINE || numParts > 3) throw new MalformedCommandException("invalid increment command"); cmd.setKey(parts.get(1)); cmd.incrAmount = BufferUtils.atoi(parts.get(MIN_BYTES_LINE)); if (numParts == 3 && parts.get(MIN_BYTES_LINE).equals(NOREPLY)) { cmd.noreply = true; } return cmd; case FLUSH_ALL: if (numParts >= 1) { if (parts.get(numParts - 1).equals(NOREPLY)) { cmd.noreply = true; if (numParts == 3) cmd.time = BufferUtils.atoi((parts.get(1))); } else if (numParts == MIN_BYTES_LINE) cmd.time = BufferUtils.atoi((parts.get(1))); } return cmd; case VERBOSITY: // verbosity <time> [noreply]\r\n // Malformed if (numParts < MIN_BYTES_LINE || numParts > 3) throw new MalformedCommandException("invalid verbosity command"); cmd.time = BufferUtils.atoi((parts.get(1))); // verbose level if (numParts > 1 && parts.get(MIN_BYTES_LINE).equals(NOREPLY)) cmd.noreply = true; return cmd; case APPEND: case PREPEND: case REPLACE: case ADD: case SET: case CAS: // if we don't have all the parts, it's malformed if (numParts < 5) { throw new MalformedCommandException("invalid command length"); } // Fill in all the elements of the command int size = BufferUtils.atoi(parts.get(4)); long expire = BufferUtils.atoi(parts.get(3)) * 1000; int flags = BufferUtils.atoi(parts.get(MIN_BYTES_LINE)); cmd.element = new LocalCacheElement(new Key(parts.get(1).slice()), flags, expire != 0 && expire < CacheElement.THIRTY_DAYS ? LocalCacheElement.Now() + expire : expire, 0L); // look for cas and "noreply" elements if (numParts > 5) { int noreply = op == Op.CAS ? 6 : 5; if (op == Op.CAS) { cmd.cas_key = BufferUtils.atol(parts.get(5)); } if (numParts == noreply + 1 && parts.get(noreply).equals(NOREPLY)) cmd.noreply = true; } // Now indicate that we need more for this command by changing the session status's state. // This instructs the frame decoder to start collecting data for us. status.needMore(size, cmd); break; // case GET: case GETS: case STATS: case VERSION: case QUIT: // Get all the keys cmd.setKeys(parts.subList(1, numParts)); // Pass it on. return cmd; default: throw new UnknownCommandException("unknown command: " + op); } return null; } /** * Handles the continuation of a SET/ADD/REPLACE command with the data it was waiting for. * * @param channel netty channel * @param state the current session status (unused) * @param remainder the bytes picked up * @param channelHandlerContext netty channel handler context */ private CommandMessage continueSet(Channel channel, SessionStatus state, ChannelBuffer remainder, ChannelHandlerContext channelHandlerContext) { state.cmd.element.setData(remainder); return state.cmd; } }
Java
package com.thimbleware.jmemcached.protocol.text; import com.thimbleware.jmemcached.Cache; import com.thimbleware.jmemcached.protocol.MemcachedCommandHandler; import com.thimbleware.jmemcached.protocol.SessionStatus; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.group.DefaultChannelGroup; import java.nio.charset.Charset; /** */ public final class MemcachedPipelineFactory implements ChannelPipelineFactory { public static final Charset USASCII = Charset.forName("US-ASCII"); private Cache cache; private String version; private boolean verbose; private int idleTime; private int frameSize; private DefaultChannelGroup channelGroup; private final MemcachedResponseEncoder memcachedResponseEncoder = new MemcachedResponseEncoder(); private final MemcachedCommandHandler memcachedCommandHandler; public MemcachedPipelineFactory(Cache cache, String version, boolean verbose, int idleTime, int frameSize, DefaultChannelGroup channelGroup) { this.cache = cache; this.version = version; this.verbose = verbose; this.idleTime = idleTime; this.frameSize = frameSize; this.channelGroup = channelGroup; memcachedCommandHandler = new MemcachedCommandHandler(this.cache, this.version, this.verbose, this.idleTime, this.channelGroup); } public final ChannelPipeline getPipeline() throws Exception { SessionStatus status = new SessionStatus().ready(); return Channels.pipeline( new MemcachedCommandDecoder(status), memcachedCommandHandler, memcachedResponseEncoder); } }
Java
package com.thimbleware.jmemcached.protocol.text; import com.thimbleware.jmemcached.Cache; import com.thimbleware.jmemcached.CacheElement; import com.thimbleware.jmemcached.protocol.Op; import com.thimbleware.jmemcached.protocol.ResponseMessage; import com.thimbleware.jmemcached.protocol.exceptions.ClientException; import com.thimbleware.jmemcached.util.BufferUtils; import org.jboss.netty.channel.*; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.buffer.ChannelBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.thimbleware.jmemcached.protocol.text.MemcachedPipelineFactory.*; import static java.lang.String.valueOf; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.Map; /** * Response encoder for the memcached text protocol. Produces strings destined for the StringEncoder */ public final class MemcachedResponseEncoder<CACHE_ELEMENT extends CacheElement> extends SimpleChannelUpstreamHandler { final Logger logger = LoggerFactory.getLogger(MemcachedResponseEncoder.class); public static final ChannelBuffer CRLF = ChannelBuffers.copiedBuffer("\r\n", USASCII); private static final ChannelBuffer SPACE = ChannelBuffers.copiedBuffer(" ", USASCII); private static final ChannelBuffer VALUE = ChannelBuffers.copiedBuffer("VALUE ", USASCII); private static final ChannelBuffer EXISTS = ChannelBuffers.copiedBuffer("EXISTS\r\n", USASCII); private static final ChannelBuffer NOT_FOUND = ChannelBuffers.copiedBuffer("NOT_FOUND\r\n", USASCII); private static final ChannelBuffer NOT_STORED = ChannelBuffers.copiedBuffer("NOT_STORED\r\n", USASCII); private static final ChannelBuffer STORED = ChannelBuffers.copiedBuffer("STORED\r\n", USASCII); private static final ChannelBuffer DELETED = ChannelBuffers.copiedBuffer("DELETED\r\n", USASCII); private static final ChannelBuffer END = ChannelBuffers.copiedBuffer("END\r\n", USASCII); private static final ChannelBuffer OK = ChannelBuffers.copiedBuffer("OK\r\n", USASCII); private static final ChannelBuffer ERROR = ChannelBuffers.copiedBuffer("ERROR\r\n", USASCII); private static final ChannelBuffer CLIENT_ERROR = ChannelBuffers.copiedBuffer("CLIENT_ERROR\r\n", USASCII); /** * Handle exceptions in protocol processing. Exceptions are either client or internal errors. Report accordingly. * * @param ctx * @param e * @throws Exception */ @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { try { throw e.getCause(); } catch (ClientException ce) { if (ctx.getChannel().isOpen()) ctx.getChannel().write(CLIENT_ERROR); } catch (Throwable tr) { logger.error("error", tr); if (ctx.getChannel().isOpen()) ctx.getChannel().write(ERROR); } } @Override public void messageReceived(ChannelHandlerContext channelHandlerContext, MessageEvent messageEvent) throws Exception { ResponseMessage<CACHE_ELEMENT> command = (ResponseMessage<CACHE_ELEMENT>) messageEvent.getMessage(); Op cmd = command.cmd.op; Channel channel = messageEvent.getChannel(); switch (cmd) { case GET: case GETS: CacheElement[] results = command.elements; ChannelBuffer[] buffers = new ChannelBuffer[results.length * (9 + (cmd == Op.GETS ? 2 : 0)) + 1]; int i = 0; for (CacheElement result : results) { if (result != null) { buffers[i++] = VALUE; buffers[i++] = result.getKey().bytes; buffers[i++] = SPACE; buffers[i++] = BufferUtils.itoa(result.getFlags()); buffers[i++] = SPACE; buffers[i++] = BufferUtils.itoa(result.size()); if (cmd == Op.GETS) { buffers[i++] = SPACE; buffers[i++] = BufferUtils.ltoa(result.getCasUnique()); } buffers[i++] = CRLF; buffers[i++] = result.getData(); buffers[i++] = CRLF; } } buffers[i] = END; Channels.write(channel, ChannelBuffers.wrappedBuffer(buffers)); break; case APPEND: case PREPEND: case ADD: case SET: case REPLACE: case CAS: if (!command.cmd.noreply) Channels.write(channel, storeResponse(command.response)); break; case DELETE: if (!command.cmd.noreply) Channels.write(channel, deleteResponseString(command.deleteResponse)); break; case DECR: case INCR: if (!command.cmd.noreply) Channels.write(channel, incrDecrResponseString(command.incrDecrResponse)); break; case STATS: for (Map.Entry<String, Set<String>> stat : command.stats.entrySet()) { for (String statVal : stat.getValue()) { StringBuilder builder = new StringBuilder(); builder.append("STAT "); builder.append(stat.getKey()); builder.append(" "); builder.append(String.valueOf(statVal)); builder.append("\r\n"); Channels.write(channel, ChannelBuffers.copiedBuffer(builder.toString(), USASCII)); } } Channels.write(channel, END.duplicate()); break; case VERSION: Channels.write(channel, ChannelBuffers.copiedBuffer("VERSION " + command.version + "\r\n", USASCII)); break; case QUIT: Channels.disconnect(channel); break; case FLUSH_ALL: if (!command.cmd.noreply) { ChannelBuffer ret = command.flushSuccess ? OK.duplicate() : ERROR.duplicate(); Channels.write(channel, ret); } break; case VERBOSITY: break; default: Channels.write(channel, ERROR.duplicate()); logger.error("error; unrecognized command: " + cmd); } } private ChannelBuffer deleteResponseString(Cache.DeleteResponse deleteResponse) { if (deleteResponse == Cache.DeleteResponse.DELETED) return DELETED.duplicate(); else return NOT_FOUND.duplicate(); } private ChannelBuffer incrDecrResponseString(Integer ret) { if (ret == null) return NOT_FOUND.duplicate(); else return ChannelBuffers.copiedBuffer(valueOf(ret) + "\r\n", USASCII); } /** * Find the string response message which is equivalent to a response to a set/add/replace message * in the cache * * @param storeResponse the response code * @return the string to output on the network */ private ChannelBuffer storeResponse(Cache.StoreResponse storeResponse) { switch (storeResponse) { case EXISTS: return EXISTS.duplicate(); case NOT_FOUND: return NOT_FOUND.duplicate(); case NOT_STORED: return NOT_STORED.duplicate(); case STORED: return STORED.duplicate(); } throw new RuntimeException("unknown store response from cache: " + storeResponse); } }
Java
/** * Copyright 2008 ThimbleWare Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thimbleware.jmemcached.protocol; import com.thimbleware.jmemcached.Cache; import com.thimbleware.jmemcached.CacheElement; import com.thimbleware.jmemcached.Key; import com.thimbleware.jmemcached.protocol.exceptions.UnknownCommandException; import org.jboss.netty.channel.*; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicInteger; // TODO implement flush_all delay /** * The actual command handler, which is responsible for processing the CommandMessage instances * that are inbound from the protocol decoders. * <p/> * One instance is shared among the entire pipeline, since this handler is stateless, apart from some globals * for the entire daemon. * <p/> * The command handler produces ResponseMessages which are destined for the response encoder. */ @ChannelHandler.Sharable public final class MemcachedCommandHandler<CACHE_ELEMENT extends CacheElement> extends SimpleChannelUpstreamHandler { final Logger logger = LoggerFactory.getLogger(MemcachedCommandHandler.class); public final AtomicInteger curr_conns = new AtomicInteger(); public final AtomicInteger total_conns = new AtomicInteger(); /** * The following state variables are universal for the entire daemon. These are used for statistics gathering. * In order for these values to work properly, the handler _must_ be declared with a ChannelPipelineCoverage * of "all". */ public final String version; public final int idle_limit; public final boolean verbose; /** * The actual physical data storage. */ private final Cache<CACHE_ELEMENT> cache; /** * The channel group for the entire daemon, used for handling global cleanup on shutdown. */ private final DefaultChannelGroup channelGroup; /** * Construct the server session handler * * @param cache the cache to use * @param memcachedVersion the version string to return to clients * @param verbosity verbosity level for debugging * @param idle how long sessions can be idle for * @param channelGroup */ public MemcachedCommandHandler(Cache cache, String memcachedVersion, boolean verbosity, int idle, DefaultChannelGroup channelGroup) { this.cache = cache; version = memcachedVersion; verbose = verbosity; idle_limit = idle; this.channelGroup = channelGroup; } /** * On open we manage some statistics, and add this connection to the channel group. * * @param channelHandlerContext * @param channelStateEvent * @throws Exception */ @Override public void channelOpen(ChannelHandlerContext channelHandlerContext, ChannelStateEvent channelStateEvent) throws Exception { total_conns.incrementAndGet(); curr_conns.incrementAndGet(); channelGroup.add(channelHandlerContext.getChannel()); } /** * On close we manage some statistics, and remove this connection from the channel group. * * @param channelHandlerContext * @param channelStateEvent * @throws Exception */ @Override public void channelClosed(ChannelHandlerContext channelHandlerContext, ChannelStateEvent channelStateEvent) throws Exception { curr_conns.decrementAndGet(); channelGroup.remove(channelHandlerContext.getChannel()); } /** * The actual meat of the matter. Turn CommandMessages into executions against the physical cache, and then * pass on the downstream messages. * * @param channelHandlerContext * @param messageEvent * @throws Exception */ @Override @SuppressWarnings("unchecked") public void messageReceived(ChannelHandlerContext channelHandlerContext, MessageEvent messageEvent) throws Exception { if (!(messageEvent.getMessage() instanceof CommandMessage)) { // Ignore what this encoder can't encode. channelHandlerContext.sendUpstream(messageEvent); return; } CommandMessage<CACHE_ELEMENT> command = (CommandMessage<CACHE_ELEMENT>) messageEvent.getMessage(); Op cmd = command.op; int cmdKeysSize = command.keys == null ? 0 : command.keys.size(); // first process any messages in the delete queue cache.asyncEventPing(); // now do the real work if (this.verbose) { StringBuilder log = new StringBuilder(); log.append(cmd); if (command.element != null) { log.append(" ").append(command.element.getKey()); } for (int i = 0; i < cmdKeysSize; i++) { log.append(" ").append(command.keys.get(i)); } logger.info(log.toString()); } Channel channel = messageEvent.getChannel(); if (cmd == null) handleNoOp(channelHandlerContext, command); else switch (cmd) { case GET: case GETS: handleGets(channelHandlerContext, command, channel); break; case APPEND: handleAppend(channelHandlerContext, command, channel); break; case PREPEND: handlePrepend(channelHandlerContext, command, channel); break; case DELETE: handleDelete(channelHandlerContext, command, channel); break; case DECR: handleDecr(channelHandlerContext, command, channel); break; case INCR: handleIncr(channelHandlerContext, command, channel); break; case REPLACE: handleReplace(channelHandlerContext, command, channel); break; case ADD: handleAdd(channelHandlerContext, command, channel); break; case SET: handleSet(channelHandlerContext, command, channel); break; case CAS: handleCas(channelHandlerContext, command, channel); break; case STATS: handleStats(channelHandlerContext, command, cmdKeysSize, channel); break; case VERSION: handleVersion(channelHandlerContext, command, channel); break; case QUIT: handleQuit(channel); break; case FLUSH_ALL: handleFlush(channelHandlerContext, command, channel); break; case VERBOSITY: handleVerbosity(channelHandlerContext, command, channel); break; default: throw new UnknownCommandException("unknown command"); } } protected void handleNoOp(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command) { Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command)); } protected void handleFlush(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withFlushResponse(cache.flush_all(command.time)), channel.getRemoteAddress()); } protected void handleVerbosity(ChannelHandlerContext channelHandlerContext, CommandMessage command, Channel channel) { //TODO set verbosity mode Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command), channel.getRemoteAddress()); } protected void handleQuit(Channel channel) { channel.disconnect(); } protected void handleVersion(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { ResponseMessage responseMessage = new ResponseMessage(command); responseMessage.version = version; Channels.fireMessageReceived(channelHandlerContext, responseMessage, channel.getRemoteAddress()); } protected void handleStats(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, int cmdKeysSize, Channel channel) { String option = ""; if (cmdKeysSize > 0) { option = command.keys.get(0).bytes.toString(); } Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withStatResponse(cache.stat(option)), channel.getRemoteAddress()); } protected void handleDelete(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Cache.DeleteResponse dr = cache.delete(command.keys.get(0), command.time); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withDeleteResponse(dr), channel.getRemoteAddress()); } protected void handleDecr(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Integer incrDecrResp = cache.get_add(command.keys.get(0), -1 * command.incrAmount); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withIncrDecrResponse(incrDecrResp), channel.getRemoteAddress()); } protected void handleIncr(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Integer incrDecrResp = cache.get_add(command.keys.get(0), command.incrAmount); // TODO support default value and expiry!! Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withIncrDecrResponse(incrDecrResp), channel.getRemoteAddress()); } protected void handlePrepend(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Cache.StoreResponse ret; ret = cache.prepend(command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress()); } protected void handleAppend(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Cache.StoreResponse ret; ret = cache.append(command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress()); } protected void handleReplace(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Cache.StoreResponse ret; ret = cache.replace(command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress()); } protected void handleAdd(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Cache.StoreResponse ret; ret = cache.add(command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress()); } protected void handleCas(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Cache.StoreResponse ret; ret = cache.cas(command.cas_key, command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress()); } protected void handleSet(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Cache.StoreResponse ret; ret = cache.set(command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress()); } protected void handleGets(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) { Key[] keys = new Key[command.keys.size()]; keys = command.keys.toArray(keys); CACHE_ELEMENT[] results = get(keys); ResponseMessage<CACHE_ELEMENT> resp = new ResponseMessage<CACHE_ELEMENT>(command).withElements(results); Channels.fireMessageReceived(channelHandlerContext, resp, channel.getRemoteAddress()); } /** * Get an element from the cache * * @param keys the key for the element to lookup * @return the element, or 'null' in case of cache miss. */ private CACHE_ELEMENT[] get(Key... keys) { return cache.get(keys); } /** * @return the current time in seconds (from epoch), used for expiries, etc. */ private static int Now() { return (int) (System.currentTimeMillis() / 1000); } }
Java
package com.thimbleware.jmemcached; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.Set; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import static java.lang.String.*; /** * Abstract implementation of a cache handler for the memcache daemon; provides some convenience methods and * a general framework for implementation */ public abstract class AbstractCache<CACHE_ELEMENT extends CacheElement> implements Cache<CACHE_ELEMENT> { protected final AtomicLong started = new AtomicLong(); protected final AtomicInteger getCmds = new AtomicInteger(); protected final AtomicInteger setCmds = new AtomicInteger(); protected final AtomicInteger getHits = new AtomicInteger(); protected final AtomicInteger getMisses = new AtomicInteger(); protected final AtomicLong casCounter = new AtomicLong(1); public AbstractCache() { initStats(); } /** * @return the current time in seconds (from epoch), used for expiries, etc. */ public static int Now() { return (int) (System.currentTimeMillis()); } protected abstract Set<Key> keys(); public abstract long getCurrentItems(); public abstract long getLimitMaxBytes(); public abstract long getCurrentBytes(); public final int getGetCmds() { return getCmds.get(); } public final int getSetCmds() { return setCmds.get(); } public final int getGetHits() { return getHits.get(); } public final int getGetMisses() { return getMisses.get(); } /** * Return runtime statistics * * @param arg additional arguments to the stats command * @return the full command response */ public final Map<String, Set<String>> stat(String arg) { Map<String, Set<String>> result = new HashMap<String, Set<String>>(); // stats we know multiSet(result, "version", MemCacheDaemon.memcachedVersion); multiSet(result, "cmd_gets", valueOf(getGetCmds())); multiSet(result, "cmd_sets", valueOf(getSetCmds())); multiSet(result, "get_hits", valueOf(getGetHits())); multiSet(result, "get_misses", valueOf(getGetMisses())); multiSet(result, "time", valueOf(valueOf(Now()))); multiSet(result, "uptime", valueOf(Now() - this.started.longValue())); multiSet(result, "cur_items", valueOf(this.getCurrentItems())); multiSet(result, "limit_maxbytes", valueOf(this.getLimitMaxBytes())); multiSet(result, "current_bytes", valueOf(this.getCurrentBytes())); multiSet(result, "free_bytes", valueOf(Runtime.getRuntime().freeMemory())); // Not really the same thing precisely, but meaningful nonetheless. potentially this should be renamed multiSet(result, "pid", valueOf(Thread.currentThread().getId())); // stuff we know nothing about; gets faked only because some clients expect this multiSet(result, "rusage_user", "0:0"); multiSet(result, "rusage_system", "0:0"); multiSet(result, "connection_structures", "0"); // TODO we could collect these stats multiSet(result, "bytes_read", "0"); multiSet(result, "bytes_written", "0"); return result; } private void multiSet(Map<String, Set<String>> map, String key, String val) { Set<String> cur = map.get(key); if (cur == null) { cur = new HashSet<String>(); } cur.add(val); map.put(key, cur); } /** * Initialize all statistic counters */ protected void initStats() { started.set(System.currentTimeMillis()); // getCmds.set(0); // setCmds.set(0); // getHits.set(0); // getMisses.set(0); } public abstract void asyncEventPing(); }
Java
package com.thimbleware.jmemcached.util; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import java.nio.ByteBuffer; /** */ public class BufferUtils { final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE }; private static final ChannelBuffer LONG_MIN_VALUE_BYTES = ChannelBuffers.wrappedBuffer("-9223372036854775808".getBytes()); // Requires positive x static int stringSize(int x) { for (int i=0; ; i++) if (x <= sizeTable[i]) return i+1; } final static byte[] digits = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' }; final static byte [] DigitTens = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', } ; final static byte [] DigitOnes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', } ; public static int atoi(ChannelBuffer s) throws NumberFormatException { int result = 0; boolean negative = false; int i = 0, len = s.capacity(); int limit = -Integer.MAX_VALUE; int multmin; int digit; if (len > 0) { byte firstChar = s.getByte(0); if (firstChar < '0') { // Possible leading "-" if (firstChar == '-') { negative = true; limit = Integer.MIN_VALUE; } else throw new NumberFormatException(); if (len == 1) // Cannot have lone "-" throw new NumberFormatException(); i++; } multmin = limit / 10; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE digit = Character.digit(s.getByte(i++),10); if (digit < 0) { throw new NumberFormatException(); } if (result < multmin) { throw new NumberFormatException(); } result *= 10; if (result < limit + digit) { throw new NumberFormatException(); } result -= digit; } } else { throw new NumberFormatException(); } return negative ? result : -result; } public static long atol(ChannelBuffer s) throws NumberFormatException { long result = 0; boolean negative = false; int i = 0, len = s.capacity(); long limit = -Long.MAX_VALUE; long multmin; int digit; if (len > 0) { byte firstChar = s.getByte(0); if (firstChar < '0') { // Possible leading "-" if (firstChar == '-') { negative = true; limit = Long.MIN_VALUE; } else throw new NumberFormatException(); if (len == 1) // Cannot have lone "-" throw new NumberFormatException(); i++; } multmin = limit / 10; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE digit = Character.digit(s.getByte(i++),10); if (digit < 0) { throw new NumberFormatException(); } if (result < multmin) { throw new NumberFormatException(); } result *= 10; if (result < limit + digit) { throw new NumberFormatException(); } result -= digit; } } else { throw new NumberFormatException(); } return negative ? result : -result; } /** Blatant copy of Integer.toString, but returning a byte array instead of a String, as * string charset decoding/encoding was killing us on performance. * @param i integer to convert * @return byte[] array containing literal ASCII char representation */ public static ChannelBuffer itoa(int i) { int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); ChannelBuffer buf = ChannelBuffers.buffer(size); getChars(i, size, buf); return buf; } public static ChannelBuffer ltoa(long i) { if (i == Long.MIN_VALUE) return LONG_MIN_VALUE_BYTES; int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); ChannelBuffer buf = ChannelBuffers.buffer(size); getChars(i, size, buf); return buf; } /** * Places characters representing the integer i into the * character array buf. The characters are placed into * the buffer backwards starting with the least significant * digit at the specified index (exclusive), and working * backwards from there. * * Will fail if i == Long.MIN_VALUE */ static void getChars(long i, int index, ChannelBuffer buf) { long q; int r; int charPos = index; byte sign = 0; if (i < 0) { sign = '-'; i = -i; } // Get 2 digits/iteration using longs until quotient fits into an int while (i > Integer.MAX_VALUE) { q = i / 100; // really: r = i - (q * 100); r = (int)(i - ((q << 6) + (q << 5) + (q << 2))); i = q; buf.setByte(--charPos, DigitOnes[r]); buf.setByte(--charPos, DigitTens[r]); } // Get 2 digits/iteration using ints int q2; int i2 = (int)i; while (i2 >= 65536) { q2 = i2 / 100; // really: r = i2 - (q * 100); r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2)); i2 = q2; buf.setByte(--charPos, DigitOnes[r]); buf.setByte(--charPos, DigitTens[r]); } // Fall thru to fast mode for smaller numbers // assert(i2 <= 65536, i2); for (;;) { q2 = (i2 * 52429) >>> (16+3); r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ... buf.setByte(--charPos, digits[r]); i2 = q2; if (i2 == 0) break; } if (sign != 0) { buf.setByte(--charPos, sign); } buf.writerIndex(buf.capacity()); } static void getChars(int i, int index, ChannelBuffer buf) { int q, r; int charPos = index; byte sign = 0; if (i < 0) { sign = '-'; i = -i; } // Generate two digits per iteration while (i >= 65536) { q = i / 100; // really: r = i - (q * 100); r = i - ((q << 6) + (q << 5) + (q << 2)); i = q; buf.setByte(--charPos, DigitOnes[r]); buf.setByte(--charPos, DigitTens[r]); } // Fall thru to fast mode for smaller numbers // assert(i <= 65536, i); for (;;) { q = (i * 52429) >>> (16+3); r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... buf.setByte(--charPos, digits[r]); i = q; if (i == 0) break; } if (sign != 0) { buf.setByte(--charPos, sign); } buf.writerIndex(buf.capacity()); } // Requires positive x static int stringSize(long x) { long p = 10; for (int i=1; i<19; i++) { if (x < p) return i; p = 10*p; } return 19; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thimbleware.jmemcached.util; import java.util.Arrays; import java.io.Serializable; import java.util.BitSet; /** An "open" BitSet implementation that allows direct access to the array of words * storing the bits. * <p/> * Unlike java.util.bitset, the fact that bits are packed into an array of longs * is part of the interface. This allows efficient implementation of other algorithms * by someone other than the author. It also allows one to efficiently implement * alternate serialization or interchange formats. * <p/> * <code>OpenBitSet</code> is faster than <code>java.util.BitSet</code> in most operations * and *much* faster at calculating cardinality of sets and results of set operations. * It can also handle sets of larger cardinality (up to 64 * 2**32-1) * <p/> * The goals of <code>OpenBitSet</code> are the fastest implementation possible, and * maximum code reuse. Extra safety and encapsulation * may always be built on top, but if that's built in, the cost can never be removed (and * hence people re-implement their own version in order to get better performance). * If you want a "safe", totally encapsulated (and slower and limited) BitSet * class, use <code>java.util.BitSet</code>. * <p/> * <h3>Performance Results</h3> * Test system: Pentium 4, Sun Java 1.5_06 -server -Xbatch -Xmx64M <br/>BitSet size = 1,000,000 <br/>Results are java.util.BitSet time divided by OpenBitSet time. <table border="1"> <tr> <th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th> </tr> <tr> <th>50% full</th> <td>3.36</td> <td>3.96</td> <td>1.44</td> <td>1.46</td> <td>1.99</td> <td>1.58</td> </tr> <tr> <th>1% full</th> <td>3.31</td> <td>3.90</td> <td>&nbsp;</td> <td>1.04</td> <td>&nbsp;</td> <td>0.99</td> </tr> </table> <br/> Test system: AMD Opteron, 64 bit linux, Sun Java 1.5_06 -server -Xbatch -Xmx64M <br/>BitSet size = 1,000,000 <br/>Results are java.util.BitSet time divided by OpenBitSet time. <table border="1"> <tr> <th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th> </tr> <tr> <th>50% full</th> <td>2.50</td> <td>3.50</td> <td>1.00</td> <td>1.03</td> <td>1.12</td> <td>1.25</td> </tr> <tr> <th>1% full</th> <td>2.51</td> <td>3.49</td> <td>&nbsp;</td> <td>1.00</td> <td>&nbsp;</td> <td>1.02</td> </tr> </table> */ public class OpenBitSet implements Cloneable, Serializable { private static final int OFFSET = 6; private static final int ELM_SIZE = 1 << OFFSET; private final static long ALLSET = 0xFFFFFFFFFFFFFFFFL; private static final long[] TWO_N_ARRAY = new long[] { 0x1L, 0x2L, 0x4L, 0x8L, 0x10L, 0x20L, 0x40L, 0x80L, 0x100L, 0x200L, 0x400L, 0x800L, 0x1000L, 0x2000L, 0x4000L, 0x8000L, 0x10000L, 0x20000L, 0x40000L, 0x80000L, 0x100000L, 0x200000L, 0x400000L, 0x800000L, 0x1000000L, 0x2000000L, 0x4000000L, 0x8000000L, 0x10000000L, 0x20000000L, 0x40000000L, 0x80000000L, 0x100000000L, 0x200000000L, 0x400000000L, 0x800000000L, 0x1000000000L, 0x2000000000L, 0x4000000000L, 0x8000000000L, 0x10000000000L, 0x20000000000L, 0x40000000000L, 0x80000000000L, 0x100000000000L, 0x200000000000L, 0x400000000000L, 0x800000000000L, 0x1000000000000L, 0x2000000000000L, 0x4000000000000L, 0x8000000000000L, 0x10000000000000L, 0x20000000000000L, 0x40000000000000L, 0x80000000000000L, 0x100000000000000L, 0x200000000000000L, 0x400000000000000L, 0x800000000000000L, 0x1000000000000000L, 0x2000000000000000L, 0x4000000000000000L, 0x8000000000000000L }; protected long[] bits; protected int wlen; // number of words (elements) used in the array /** Constructs an OpenBitSet large enough to hold numBits. * * @param numBits */ public OpenBitSet(long numBits) { bits = new long[bits2words(numBits)]; wlen = bits.length; } public OpenBitSet() { this(64); } /** Constructs an OpenBitSet from an existing long[]. * <br/> * The first 64 bits are in long[0], * with bit index 0 at the least significant bit, and bit index 63 at the most significant. * Given a bit index, * the word containing it is long[index/64], and it is at bit number index%64 within that word. * <p> * numWords are the number of elements in the array that contain * set bits (non-zero longs). * numWords should be &lt= bits.length, and * any existing words in the array at position &gt= numWords should be zero. * */ public OpenBitSet(long[] bits, int numWords) { this.bits = bits; this.wlen = numWords; } /** Contructs an OpenBitset from a BitSet */ public OpenBitSet(BitSet bits) { this(bits.length()); } /** Returns the current capacity in bits (1 greater than the index of the last bit) */ public long capacity() { return bits.length << OFFSET; } /** * Returns the current capacity of this set. Included for * compatibility. This is *not* equal to {@link #cardinality} */ public long size() { return capacity(); } // @Override -- not until Java 1.6 public int length() { return bits.length << OFFSET; } /** Returns true if there are no set bits */ public boolean isEmpty() { return cardinality()==0; } /** Expert: returns the long[] storing the bits */ public long[] getBits() { return bits; } /** Expert: sets a new long[] to use as the bit storage */ public void setBits(long[] bits) { this.bits = bits; } /** Expert: gets the number of longs in the array that are in use */ public int getNumWords() { return wlen; } /** Expert: sets the number of longs in the array that are in use */ public void setNumWords(int nWords) { this.wlen=nWords; } /** Returns true or false for the specified bit index. */ public boolean get(int index) { int i = index >> OFFSET; // div 64 // signed shift will keep a negative index and force an // array-index-out-of-bounds-exception, removing the need for an explicit check. if (i>=bits.length) return false; int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } /** Returns true or false for the specified bit index. * The index should be less than the OpenBitSet size */ public boolean fastGet(int index) { int i = index >> OFFSET; // div 64 // signed shift will keep a negative index and force an // array-index-out-of-bounds-exception, removing the need for an explicit check. int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } /** Returns true or false for the specified bit index */ public boolean get(long index) { int i = (int)(index >> OFFSET); // div 64 if (i>=bits.length) return false; int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } /** Returns true or false for the specified bit index. * The index should be less than the OpenBitSet size. */ public boolean fastGet(long index) { int i = (int)(index >> OFFSET); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } /* // alternate implementation of get() public boolean get1(int index) { int i = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 return ((bits[i]>>>bit) & 0x01) != 0; // this does a long shift and a bittest (on x86) vs // a long shift, and a long AND, (the test for zero is prob a no-op) // testing on a P4 indicates this is slower than (bits[i] & bitmask) != 0; } */ /** returns 1 if the bit is set, 0 if not. * The index should be less than the OpenBitSet size */ public int getBit(int index) { int i = index >> OFFSET; // div 64 int bit = index & 0x3f; // mod 64 return ((int)(bits[i]>>>bit)) & 0x01; } /* public boolean get2(int index) { int word = index >> 6; // div 64 int bit = index & 0x0000003f; // mod 64 return (bits[word] << bit) < 0; // hmmm, this would work if bit order were reversed // we could right shift and check for parity bit, if it was available to us. } */ /** sets a bit, expanding the set size if necessary */ public void set(long index) { int wordNum = expandingWordNum(index); int bit = (int)index & 0x3f; long bitmask = 1L << bit; bits[wordNum] |= bitmask; } /** Sets the bit at the specified index. * The index should be less than the OpenBitSet size. */ public void fastSet(int index) { int wordNum = index >> OFFSET; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] |= bitmask; } /** Sets the bit at the specified index. * The index should be less than the OpenBitSet size. */ public void fastSet(long index) { int wordNum = (int)(index >> OFFSET); int bit = (int)index & 0x3f; long bitmask = 1L << bit; bits[wordNum] |= bitmask; } /** Sets a range of bits, expanding the set size if necessary * * @param startIndex lower index * @param endIndex one-past the last bit to set */ public void set(long startIndex, long endIndex) { if (endIndex <= startIndex) return; int startWord = (int)(startIndex>> OFFSET); // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = expandingWordNum(endIndex-1); long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord] |= (startmask & endmask); return; } bits[startWord] |= startmask; Arrays.fill(bits, startWord+1, endWord, -1L); bits[endWord] |= endmask; } protected int expandingWordNum(long index) { int wordNum = (int)(index >> OFFSET); if (wordNum>=wlen) { ensureCapacity(index+1); wlen = wordNum+1; } return wordNum; } /** clears a bit. * The index should be less than the OpenBitSet size. */ public void fastClear(int index) { int wordNum = index >> OFFSET; int bit = index & 0x03f; long bitmask = 1L << bit; bits[wordNum] &= ~bitmask; // hmmm, it takes one more instruction to clear than it does to set... any // way to work around this? If there were only 63 bits per word, we could // use a right shift of 10111111...111 in binary to position the 0 in the // correct place (using sign extension). // Could also use Long.rotateRight() or rotateLeft() *if* they were converted // by the JVM into a native instruction. // bits[word] &= Long.rotateLeft(0xfffffffe,bit); } /** clears a bit. * The index should be less than the OpenBitSet size. */ public void fastClear(long index) { int wordNum = (int)(index >> OFFSET); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] &= ~bitmask; } /** clears a bit, allowing access beyond the current set size without changing the size.*/ public void clear(long index) { int wordNum = (int)(index >> OFFSET); // div 64 if (wordNum>=wlen) return; int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] &= ~bitmask; } /** Clears a range of bits. Clearing past the end does not change the size of the set. * * @param startIndex lower index * @param endIndex one-past the last bit to clear */ public void clear(int startIndex, int endIndex) { if (endIndex <= startIndex) return; int startWord = (startIndex>> OFFSET); if (startWord >= wlen) return; // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = ((endIndex-1)>> OFFSET); long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap // invert masks since we are clearing startmask = ~startmask; endmask = ~endmask; if (startWord == endWord) { bits[startWord] &= (startmask | endmask); return; } bits[startWord] &= startmask; int middle = Math.min(wlen, endWord); Arrays.fill(bits, startWord+1, middle, 0L); if (endWord < wlen) { bits[endWord] &= endmask; } } /** Clears a range of bits. Clearing past the end does not change the size of the set. * * @param startIndex lower index * @param endIndex one-past the last bit to clear */ public void clear(long startIndex, long endIndex) { if (endIndex <= startIndex) return; int startWord = (int)(startIndex>> OFFSET); if (startWord >= wlen) return; // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = (int)((endIndex-1)>> OFFSET); long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap // invert masks since we are clearing startmask = ~startmask; endmask = ~endmask; if (startWord == endWord) { bits[startWord] &= (startmask | endmask); return; } bits[startWord] &= startmask; int middle = Math.min(wlen, endWord); Arrays.fill(bits, startWord+1, middle, 0L); if (endWord < wlen) { bits[endWord] &= endmask; } } /** Sets a bit and returns the previous value. * The index should be less than the OpenBitSet size. */ public boolean getAndSet(int index) { int wordNum = index >> OFFSET; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; boolean val = (bits[wordNum] & bitmask) != 0; bits[wordNum] |= bitmask; return val; } /** Sets a bit and returns the previous value. * The index should be less than the OpenBitSet size. */ public boolean getAndSet(long index) { int wordNum = (int)(index >> OFFSET); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; boolean val = (bits[wordNum] & bitmask) != 0; bits[wordNum] |= bitmask; return val; } /** flips a bit. * The index should be less than the OpenBitSet size. */ public void fastFlip(int index) { int wordNum = index >> OFFSET; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; } /** flips a bit. * The index should be less than the OpenBitSet size. */ public void fastFlip(long index) { int wordNum = (int)(index >> OFFSET); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; } /** flips a bit, expanding the set size if necessary */ public void flip(long index) { int wordNum = expandingWordNum(index); int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; } /** flips a bit and returns the resulting bit value. * The index should be less than the OpenBitSet size. */ public boolean flipAndGet(int index) { int wordNum = index >> OFFSET; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; return (bits[wordNum] & bitmask) != 0; } /** flips a bit and returns the resulting bit value. * The index should be less than the OpenBitSet size. */ public boolean flipAndGet(long index) { int wordNum = (int)(index >> OFFSET); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; return (bits[wordNum] & bitmask) != 0; } /** Flips a range of bits, expanding the set size if necessary * * @param startIndex lower index * @param endIndex one-past the last bit to flip */ public void flip(long startIndex, long endIndex) { if (endIndex <= startIndex) return; int startWord = (int)(startIndex>> OFFSET); // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = expandingWordNum(endIndex-1); /*** Grrr, java shifting wraps around so -1L>>>64 == -1 * for that reason, make sure not to use endmask if the bits to flip will * be zero in the last word (redefine endWord to be the last changed...) long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000 long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111 ***/ long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord] ^= (startmask & endmask); return; } bits[startWord] ^= startmask; for (int i=startWord+1; i<endWord; i++) { bits[i] = ~bits[i]; } bits[endWord] ^= endmask; } /* public static int pop(long v0, long v1, long v2, long v3) { // derived from pop_array by setting last four elems to 0. // exchanges one pop() call for 10 elementary operations // saving about 7 instructions... is there a better way? long twosA=v0 & v1; long ones=v0^v1; long u2=ones^v2; long twosB =(ones&v2)|(u2&v3); ones=u2^v3; long fours=(twosA&twosB); long twos=twosA^twosB; return (pop(fours)<<2) + (pop(twos)<<1) + pop(ones); } */ /** @return the number of set bits */ public long cardinality() { return BitUtil.pop_array(bits,0,wlen); } /** Returns the popcount or cardinality of the intersection of the two sets. * Neither set is modified. */ public static long intersectionCount(OpenBitSet a, OpenBitSet b) { return BitUtil.pop_intersect(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen)); } /** Returns the popcount or cardinality of the union of the two sets. * Neither set is modified. */ public static long unionCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.pop_union(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen)); if (a.wlen < b.wlen) { tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen-a.wlen); } else if (a.wlen > b.wlen) { tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen); } return tot; } /** Returns the popcount or cardinality of "a and not b" * or "intersection(a, not(b))". * Neither set is modified. */ public static long andNotCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.pop_andnot(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen)); if (a.wlen > b.wlen) { tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen); } return tot; } /** Returns the popcount or cardinality of the exclusive-or of the two sets. * Neither set is modified. */ public static long xorCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.pop_xor(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen)); if (a.wlen < b.wlen) { tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen-a.wlen); } else if (a.wlen > b.wlen) { tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen); } return tot; } /** Returns the index of the first set bit starting at the index specified. * -1 is returned if there are no more set bits. */ public int nextSetBit(int index) { int i = index>> OFFSET; if (i>=wlen) return -1; int subIndex = index & 0x3f; // index within the word long word = bits[i] >> subIndex; // skip all the bits to the right of index if (word!=0) { return (i<< OFFSET) + subIndex + BitUtil.ntz(word); } while(++i < wlen) { word = bits[i]; if (word!=0) return (i<< OFFSET) + BitUtil.ntz(word); } return -1; } public int mark(int blocks_needed) { int count; int starting_block; int b = 0; boolean over_the_top = false; int wdth = wlen * 64; while (true) { if (b < wdth && bits[b >>> OFFSET] == ALLSET) { /* 64 full blocks. Let's run away from this! */ b = (b & ~0x3f) + 64; while (b < wdth && bits[b >>> OFFSET] == ALLSET) { b += 64; } } if (b >= wdth) { /* Only wrap around once. */ if (!over_the_top) { b = 0; over_the_top = true; continue; } else { return -1; } } starting_block = b; for (count = 0; count < blocks_needed; count++) { if ((bits[b >>> OFFSET] & (1 << (b & 0x3f))) != 0) break; b++; if (b >= wdth) { /* time to wrap around if we still haven't */ if (!over_the_top) { b=0; over_the_top=true; break; } else { return -1; } } } if (count == blocks_needed) { set(starting_block, b+blocks_needed); return starting_block; } b++; } } /** Returns the index of the first set bit starting at the index specified. * -1 is returned if there are no more set bits. */ public long nextSetBit(long index) { int i = (int)(index>>> OFFSET); if (i>=wlen) return -1; int subIndex = (int)index & 0x3f; // index within the word long word = bits[i] >>> subIndex; // skip all the bits to the right of index if (word!=0) { return (((long)i)<< OFFSET) + (subIndex + BitUtil.ntz(word)); } while(++i < wlen) { word = bits[i]; if (word!=0) return (((long)i)<< OFFSET) + BitUtil.ntz(word); } return -1; } @Override public Object clone() { try { OpenBitSet obs = (OpenBitSet)super.clone(); obs.bits = obs.bits.clone(); // hopefully an array clone is as fast(er) than arraycopy return obs; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } /** this = this AND other */ public void intersect(OpenBitSet other) { int newLen= Math.min(this.wlen,other.wlen); long[] thisArr = this.bits; long[] otherArr = other.bits; // testing against zero can be more efficient int pos=newLen; while(--pos>=0) { thisArr[pos] &= otherArr[pos]; } if (this.wlen > newLen) { // fill zeros from the new shorter length to the old length Arrays.fill(bits,newLen,this.wlen,0); } this.wlen = newLen; } /** this = this OR other */ public void union(OpenBitSet other) { int newLen = Math.max(wlen,other.wlen); ensureCapacityWords(newLen); long[] thisArr = this.bits; long[] otherArr = other.bits; int pos=Math.min(wlen,other.wlen); while(--pos>=0) { thisArr[pos] |= otherArr[pos]; } if (this.wlen < newLen) { System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen-this.wlen); } this.wlen = newLen; } /** Remove all elements set in other. this = this AND_NOT other */ public void remove(OpenBitSet other) { int idx = Math.min(wlen,other.wlen); long[] thisArr = this.bits; long[] otherArr = other.bits; while(--idx>=0) { thisArr[idx] &= ~otherArr[idx]; } } /** this = this XOR other */ public void xor(OpenBitSet other) { int newLen = Math.max(wlen,other.wlen); ensureCapacityWords(newLen); long[] thisArr = this.bits; long[] otherArr = other.bits; int pos=Math.min(wlen,other.wlen); while(--pos>=0) { thisArr[pos] ^= otherArr[pos]; } if (this.wlen < newLen) { System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen-this.wlen); } this.wlen = newLen; } // some BitSet compatability methods //** see {@link intersect} */ public void and(OpenBitSet other) { intersect(other); } //** see {@link union} */ public void or(OpenBitSet other) { union(other); } //** see {@link andNot} */ public void andNot(OpenBitSet other) { remove(other); } /** returns true if the sets have any elements in common */ public boolean intersects(OpenBitSet other) { int pos = Math.min(this.wlen, other.wlen); long[] thisArr = this.bits; long[] otherArr = other.bits; while (--pos>=0) { if ((thisArr[pos] & otherArr[pos])!=0) return true; } return false; } /** Expand the long[] with the size given as a number of words (64 bit longs). * getNumWords() is unchanged by this call. */ public void ensureCapacityWords(int numWords) { if (bits.length < numWords) { bits = ArrayUtil.grow(bits, numWords); } } /** Ensure that the long[] is big enough to hold numBits, expanding it if necessary. * getNumWords() is unchanged by this call. */ public void ensureCapacity(long numBits) { ensureCapacityWords(bits2words(numBits)); } /** Lowers numWords, the number of words in use, * by checking for trailing zero words. */ public void trimTrailingZeros() { int idx = wlen-1; while (idx>=0 && bits[idx]==0) idx--; wlen = idx+1; } /** returns the number of 64 bit words it would take to hold numBits */ public static int bits2words(long numBits) { return (int)(((numBits-1)>>> OFFSET)+1); } /** returns true if both sets have the same bits set */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OpenBitSet)) return false; OpenBitSet a; OpenBitSet b = (OpenBitSet)o; // make a the larger set. if (b.wlen > this.wlen) { a = b; b=this; } else { a=this; } // check for any set bits out of the range of b for (int i=a.wlen-1; i>=b.wlen; i--) { if (a.bits[i]!=0) return false; } for (int i=b.wlen-1; i>=0; i--) { if (a.bits[i] != b.bits[i]) return false; } return true; } @Override public int hashCode() { // Start with a zero hash and use a mix that results in zero if the input is zero. // This effectively truncates trailing zeros without an explicit check. long h = 0; for (int i = bits.length; --i>=0;) { h ^= bits[i]; h = (h << 1) | (h >>> 63); // rotate left } // fold leftmost bits into right and add a constant to prevent // empty sets from returning 0, which is too common. return (int)((h>>32) ^ h) + 0x98761234; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thimbleware.jmemcached.util; /** * Methods for manipulating arrays. * * @lucene.internal */ final class ArrayUtil { public static long[] grow(long[] array, int minSize) { if (array.length < minSize) { long[] newArray = new long[Math.max(array.length << 1, minSize)]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } else return array; } public static long[] grow(long[] array) { return grow(array, 1 + array.length); } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thimbleware.jmemcached.util; /** A variety of high efficiency bit twiddling routines. * @lucene.internal */ final class BitUtil { /** Returns the number of bits set in the long */ public static int pop(long x) { /* Hacker's Delight 32 bit pop function: * http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc * int pop(unsigned x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0F0F0F0F; x = x + (x >> 8); x = x + (x >> 16); return x & 0x0000003F; } ***/ // 64 bit java version of the C function from above x = x - ((x >>> 1) & 0x5555555555555555L); x = (x & 0x3333333333333333L) + ((x >>>2 ) & 0x3333333333333333L); x = (x + (x >>> 4)) & 0x0F0F0F0F0F0F0F0FL; x = x + (x >>> 8); x = x + (x >>> 16); x = x + (x >>> 32); return ((int)x) & 0x7F; } /*** Returns the number of set bits in an array of longs. */ public static long pop_array(long A[], int wordOffset, int numWords) { /* * Robert Harley and David Seal's bit counting algorithm, as documented * in the revisions of Hacker's Delight * http://www.hackersdelight.org/revisions.pdf * http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc * * This function was adapted to Java, and extended to use 64 bit words. * if only we had access to wider registers like SSE from java... * * This function can be transformed to compute the popcount of other functions * on bitsets via something like this: * sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g' * */ int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, A[i], A[i+1]) { long b=A[i], c=A[i+1]; long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, A[i+2], A[i+3]) { long b=A[i+2], c=A[i+3]; long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, A[i+4], A[i+5]) { long b=A[i+4], c=A[i+5]; long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, A[i+6], A[i+7]) { long b=A[i+6], c=A[i+7]; long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } // handle trailing words in a binary-search manner... // derived from the loop above by setting specific elements to 0. // the original method in Hackers Delight used a simple for loop: // for (i = i; i < n; i++) // Add in the last elements // tot = tot + pop(A[i]); if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=A[i], c=A[i+1]; long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=A[i+2], c=A[i+3]; long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=A[i], c=A[i+1]; long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop(A[i]); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /** Returns the popcount or cardinality of the two sets after an intersection. * Neither array is modified. */ public static long pop_intersect(long A[], long B[], int wordOffset, int numWords) { // generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g' int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] & B[i]), (A[i+1] & B[i+1])) { long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] & B[i+2]), (A[i+3] & B[i+3])) { long b=(A[i+2] & B[i+2]), c=(A[i+3] & B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] & B[i+4]), (A[i+5] & B[i+5])) { long b=(A[i+4] & B[i+4]), c=(A[i+5] & B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] & B[i+6]), (A[i+7] & B[i+7])) { long b=(A[i+6] & B[i+6]), c=(A[i+7] & B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] & B[i+2]), c=(A[i+3] & B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] & B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /** Returns the popcount or cardinality of the union of two sets. * Neither array is modified. */ public static long pop_union(long A[], long B[], int wordOffset, int numWords) { // generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \| B[\1]\)/g' int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] | B[i]), (A[i+1] | B[i+1])) { long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] | B[i+2]), (A[i+3] | B[i+3])) { long b=(A[i+2] | B[i+2]), c=(A[i+3] | B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] | B[i+4]), (A[i+5] | B[i+5])) { long b=(A[i+4] | B[i+4]), c=(A[i+5] | B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] | B[i+6]), (A[i+7] | B[i+7])) { long b=(A[i+6] | B[i+6]), c=(A[i+7] | B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] | B[i+2]), c=(A[i+3] | B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] | B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /** Returns the popcount or cardinality of A & ~B * Neither array is modified. */ public static long pop_andnot(long A[], long B[], int wordOffset, int numWords) { // generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& ~B[\1]\)/g' int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] & ~B[i]), (A[i+1] & ~B[i+1])) { long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] & ~B[i+2]), (A[i+3] & ~B[i+3])) { long b=(A[i+2] & ~B[i+2]), c=(A[i+3] & ~B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] & ~B[i+4]), (A[i+5] & ~B[i+5])) { long b=(A[i+4] & ~B[i+4]), c=(A[i+5] & ~B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] & ~B[i+6]), (A[i+7] & ~B[i+7])) { long b=(A[i+6] & ~B[i+6]), c=(A[i+7] & ~B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] & ~B[i+2]), c=(A[i+3] & ~B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] & ~B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } public static long pop_xor(long A[], long B[], int wordOffset, int numWords) { int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] ^ B[i]), (A[i+1] ^ B[i+1])) { long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] ^ B[i+2]), (A[i+3] ^ B[i+3])) { long b=(A[i+2] ^ B[i+2]), c=(A[i+3] ^ B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] ^ B[i+4]), (A[i+5] ^ B[i+5])) { long b=(A[i+4] ^ B[i+4]), c=(A[i+5] ^ B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] ^ B[i+6]), (A[i+7] ^ B[i+7])) { long b=(A[i+6] ^ B[i+6]), c=(A[i+7] ^ B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] ^ B[i+2]), c=(A[i+3] ^ B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] ^ B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /* python code to generate ntzTable def ntz(val): if val==0: return 8 i=0 while (val&0x01)==0: i = i+1 val >>= 1 return i print ','.join([ str(ntz(i)) for i in range(256) ]) ***/ /** table of number of trailing zeros in a byte */ public static final byte[] ntzTable = {8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0}; /** Returns number of trailing zeros in a 64 bit long value. */ public static int ntz(long val) { // A full binary search to determine the low byte was slower than // a linear search for nextSetBit(). This is most likely because // the implementation of nextSetBit() shifts bits to the right, increasing // the probability that the first non-zero byte is in the rhs. // // This implementation does a single binary search at the top level only // so that all other bit shifting can be done on ints instead of longs to // remain friendly to 32 bit architectures. In addition, the case of a // non-zero first byte is checked for first because it is the most common // in dense bit arrays. int lower = (int)val; int lowByte = lower & 0xff; if (lowByte != 0) return ntzTable[lowByte]; if (lower!=0) { lowByte = (lower>>>8) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 8; lowByte = (lower>>>16) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 16; // no need to mask off low byte for the last byte in the 32 bit word // no need to check for zero on the last byte either. return ntzTable[lower>>>24] + 24; } else { // grab upper 32 bits int upper=(int)(val>>32); lowByte = upper & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 32; lowByte = (upper>>>8) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 40; lowByte = (upper>>>16) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 48; // no need to mask off low byte for the last byte in the 32 bit word // no need to check for zero on the last byte either. return ntzTable[upper>>>24] + 56; } } /** Returns number of trailing zeros in a 32 bit int value. */ public static int ntz(int val) { // This implementation does a single binary search at the top level only. // In addition, the case of a non-zero first byte is checked for first // because it is the most common in dense bit arrays. int lowByte = val & 0xff; if (lowByte != 0) return ntzTable[lowByte]; lowByte = (val>>>8) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 8; lowByte = (val>>>16) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 16; // no need to mask off low byte for the last byte. // no need to check for zero on the last byte either. return ntzTable[val>>>24] + 24; } /** returns 0 based index of first set bit * (only works for x!=0) * <br/> This is an alternate implementation of ntz() */ public static int ntz2(long x) { int n = 0; int y = (int)x; if (y==0) {n+=32; y = (int)(x>>>32); } // the only 64 bit shift necessary if ((y & 0x0000FFFF) == 0) { n+=16; y>>>=16; } if ((y & 0x000000FF) == 0) { n+=8; y>>>=8; } return (ntzTable[ y & 0xff ]) + n; } /** returns 0 based index of first set bit * <br/> This is an alternate implementation of ntz() */ public static int ntz3(long x) { // another implementation taken from Hackers Delight, extended to 64 bits // and converted to Java. // Many 32 bit ntz algorithms are at http://www.hackersdelight.org/HDcode/ntz.cc int n = 1; // do the first step as a long, all others as ints. int y = (int)x; if (y==0) {n+=32; y = (int)(x>>>32); } if ((y & 0x0000FFFF) == 0) { n+=16; y>>>=16; } if ((y & 0x000000FF) == 0) { n+=8; y>>>=8; } if ((y & 0x0000000F) == 0) { n+=4; y>>>=4; } if ((y & 0x00000003) == 0) { n+=2; y>>>=2; } return n - (y & 1); } /** returns true if v is a power of two or zero*/ public static boolean isPowerOfTwo(int v) { return ((v & (v-1)) == 0); } /** returns true if v is a power of two or zero*/ public static boolean isPowerOfTwo(long v) { return ((v & (v-1)) == 0); } /** returns the next highest power of two, or the current value if it's already a power of two or zero*/ public static int nextHighestPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } /** returns the next highest power of two, or the current value if it's already a power of two or zero*/ public static long nextHighestPowerOfTwo(long v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v |= v >> 32; v++; return v; } }
Java
/** * Copyright 2008 ThimbleWare Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thimbleware.jmemcached; import com.thimbleware.jmemcached.util.BufferUtils; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.nio.ByteBuffer; /** * Represents information about a cache entry. */ public final class LocalCacheElement implements CacheElement { private long expire ; private int flags; private ChannelBuffer data; private Key key; private long casUnique = 0L; private boolean blocked = false; private long blockedUntil; public LocalCacheElement() { } public LocalCacheElement(Key key) { this.key = key; } public LocalCacheElement(Key key, int flags, long expire, long casUnique) { this.key = key; this.flags = flags; this.expire = expire; this.casUnique = casUnique; } /** * @return the current time in seconds */ public static int Now() { return (int) (System.currentTimeMillis() / 1000); } public int size() { return getData().capacity(); } public LocalCacheElement append(LocalCacheElement appendElement) { int newLength = size() + appendElement.size(); LocalCacheElement appendedElement = new LocalCacheElement(getKey(), getFlags(), getExpire(), 0L); ChannelBuffer appended = ChannelBuffers.buffer(newLength); ChannelBuffer existing = getData(); ChannelBuffer append = appendElement.getData(); appended.writeBytes(existing); appended.writeBytes(append); appended.readerIndex(0); existing.readerIndex(0); append.readerIndex(0); appendedElement.setData(appended); appendedElement.setCasUnique(appendedElement.getCasUnique() + 1); return appendedElement; } public LocalCacheElement prepend(LocalCacheElement prependElement) { int newLength = size() + prependElement.size(); LocalCacheElement prependedElement = new LocalCacheElement(getKey(), getFlags(), getExpire(), 0L); ChannelBuffer prepended = ChannelBuffers.buffer(newLength); ChannelBuffer prepend = prependElement.getData(); ChannelBuffer existing = getData(); prepended.writeBytes(prepend); prepended.writeBytes(existing); existing.readerIndex(0); prepend.readerIndex(0); prepended.readerIndex(0); prependedElement.setData(prepended); prependedElement.setCasUnique(prependedElement.getCasUnique() + 1); return prependedElement; } public static class IncrDecrResult { int oldValue; LocalCacheElement replace; public IncrDecrResult(int oldValue, LocalCacheElement replace) { this.oldValue = oldValue; this.replace = replace; } } public IncrDecrResult add(int mod) { // TODO handle parse failure! int modVal = BufferUtils.atoi(getData()) + mod; // change value if (modVal < 0) { modVal = 0; } // check for underflow ChannelBuffer newData = BufferUtils.itoa(modVal); LocalCacheElement replace = new LocalCacheElement(getKey(), getFlags(), getExpire(), 0L); replace.setData(newData); replace.setCasUnique(replace.getCasUnique() + 1); return new IncrDecrResult(modVal, replace); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LocalCacheElement that = (LocalCacheElement) o; if (blocked != that.blocked) return false; if (blockedUntil != that.blockedUntil) return false; if (casUnique != that.casUnique) return false; if (expire != that.expire) return false; if (flags != that.flags) return false; if (data != null ? !data.equals(that.data) : that.data != null) return false; if (key != null ? !key.equals(that.key) : that.key != null) return false; return true; } @Override public int hashCode() { int result = (int) (expire ^ (expire >>> 32)); result = 31 * result + flags; result = 31 * result + (data != null ? data.hashCode() : 0); result = 31 * result + (key != null ? key.hashCode() : 0); result = 31 * result + (int) (casUnique ^ (casUnique >>> 32)); result = 31 * result + (blocked ? 1 : 0); result = 31 * result + (int) (blockedUntil ^ (blockedUntil >>> 32)); return result; } public static LocalCacheElement key(Key key) { return new LocalCacheElement(key); } public long getExpire() { return expire; } public int getFlags() { return flags; } public ChannelBuffer getData() { data.readerIndex(0); return data; } public Key getKey() { return key; } public long getCasUnique() { return casUnique; } public boolean isBlocked() { return blocked; } public long getBlockedUntil() { return blockedUntil; } public void setCasUnique(long casUnique) { this.casUnique = casUnique; } public void block(long blockedUntil) { this.blocked = true; this.blockedUntil = blockedUntil; } public void setData(ChannelBuffer data) { data.readerIndex(0); this.data = data; } public static LocalCacheElement readFromBuffer(ChannelBuffer in) { int bufferSize = in.readInt(); long expiry = in.readLong(); int keyLength = in.readInt(); ChannelBuffer key = in.slice(in.readerIndex(), keyLength); in.skipBytes(keyLength); LocalCacheElement localCacheElement = new LocalCacheElement(new Key(key)); localCacheElement.expire = expiry; localCacheElement.flags = in.readInt(); int dataLength = in.readInt(); localCacheElement.data = in.slice(in.readerIndex(), dataLength); in.skipBytes(dataLength); localCacheElement.casUnique = in.readInt(); localCacheElement.blocked = in.readByte() == 1; localCacheElement.blockedUntil = in.readLong(); return localCacheElement; } public int bufferSize() { return 4 + 8 + 4 + key.bytes.capacity() + 4 + 4 + 4 + data.capacity() + 8 + 1 + 8; } public void writeToBuffer(ChannelBuffer out) { out.writeInt(bufferSize()); out.writeLong(expire) ; out.writeInt(key.bytes.capacity()); out.writeBytes(key.bytes); out.writeInt(flags); out.writeInt(data.capacity()); out.writeBytes(data); out.writeLong(casUnique); out.writeByte(blocked ? 1 : 0); out.writeLong(blockedUntil); } }
Java
/** * Copyright 2008 ThimbleWare Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thimbleware.jmemcached; import com.thimbleware.jmemcached.protocol.binary.MemcachedBinaryPipelineFactory; import com.thimbleware.jmemcached.protocol.text.MemcachedPipelineFactory; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.group.ChannelGroupFuture; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.ServerSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.util.concurrent.Executors; /** * The actual daemon - responsible for the binding and configuration of the network configuration. */ public class MemCacheDaemon<CACHE_ELEMENT extends CacheElement> { final Logger log = LoggerFactory.getLogger(MemCacheDaemon.class); public static String memcachedVersion = "0.9"; private int frameSize = 32768 * 1024; private boolean binary = false; private boolean verbose; private int idleTime; private InetSocketAddress addr; private Cache<CACHE_ELEMENT> cache; private boolean running = false; private ServerSocketChannelFactory channelFactory; private DefaultChannelGroup allChannels; public MemCacheDaemon() { } public MemCacheDaemon(Cache<CACHE_ELEMENT> cache) { this.cache = cache; } /** * Bind the network connection and start the network processing threads. */ public void start() { // TODO provide tweakable options here for passing in custom executors. channelFactory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); allChannels = new DefaultChannelGroup("jmemcachedChannelGroup"); ServerBootstrap bootstrap = new ServerBootstrap(channelFactory); ChannelPipelineFactory pipelineFactory; if (binary) pipelineFactory = createMemcachedBinaryPipelineFactory(cache, memcachedVersion, verbose, idleTime, allChannels); else pipelineFactory = createMemcachedPipelineFactory(cache, memcachedVersion, verbose, idleTime, frameSize, allChannels); bootstrap.setPipelineFactory(pipelineFactory); bootstrap.setOption("sendBufferSize", 65536 ); bootstrap.setOption("receiveBufferSize", 65536); Channel serverChannel = bootstrap.bind(addr); allChannels.add(serverChannel); log.info("Listening on " + String.valueOf(addr.getHostName()) + ":" + addr.getPort()); running = true; } protected ChannelPipelineFactory createMemcachedBinaryPipelineFactory( Cache cache, String memcachedVersion, boolean verbose, int idleTime, DefaultChannelGroup allChannels) { return new MemcachedBinaryPipelineFactory(cache, memcachedVersion, verbose, idleTime, allChannels); } protected ChannelPipelineFactory createMemcachedPipelineFactory( Cache cache, String memcachedVersion, boolean verbose, int idleTime, int receiveBufferSize, DefaultChannelGroup allChannels) { return new MemcachedPipelineFactory(cache, memcachedVersion, verbose, idleTime, receiveBufferSize, allChannels); } public void stop() { log.info("terminating daemon; closing all channels"); ChannelGroupFuture future = allChannels.close(); future.awaitUninterruptibly(); if (!future.isCompleteSuccess()) { throw new RuntimeException("failure to complete closing all network channels"); } log.info("channels closed, freeing cache storage"); try { cache.close(); } catch (IOException e) { throw new RuntimeException("exception while closing storage", e); } channelFactory.releaseExternalResources(); running = false; log.info("successfully shut down"); } public void setVerbose(boolean verbose) { this.verbose = verbose; } public void setIdleTime(int idleTime) { this.idleTime = idleTime; } public void setAddr(InetSocketAddress addr) { this.addr = addr; } public Cache<CACHE_ELEMENT> getCache() { return cache; } public void setCache(Cache<CACHE_ELEMENT> cache) { this.cache = cache; } public boolean isRunning() { return running; } public boolean isBinary() { return binary; } public void setBinary(boolean binary) { this.binary = binary; } }
Java
/** * Copyright 2008 ThimbleWare Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thimbleware.jmemcached; import com.thimbleware.jmemcached.storage.CacheStorage; import org.jboss.netty.buffer.ChannelBuffers; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Set; import java.util.concurrent.*; /** * Default implementation of the cache handler, supporting local memory cache elements. */ public final class CacheImpl extends AbstractCache<LocalCacheElement> implements Cache<LocalCacheElement> { final CacheStorage<Key, LocalCacheElement> storage; final DelayQueue<DelayedMCElement> deleteQueue; private final ScheduledExecutorService scavenger; /** * @inheritDoc */ public CacheImpl(CacheStorage<Key, LocalCacheElement> storage) { super(); this.storage = storage; deleteQueue = new DelayQueue<DelayedMCElement>(); scavenger = Executors.newScheduledThreadPool(1); scavenger.scheduleAtFixedRate(new Runnable(){ public void run() { asyncEventPing(); } }, 10, 2, TimeUnit.SECONDS); } /** * @inheritDoc */ public DeleteResponse delete(Key key, int time) { boolean removed = false; // delayed remove if (time != 0) { // block the element and schedule a delete; replace its entry with a blocked element LocalCacheElement placeHolder = new LocalCacheElement(key, 0, 0, 0L); placeHolder.setData(ChannelBuffers.buffer(0)); placeHolder.block(Now() + (long)time); storage.replace(key, placeHolder); // this must go on a queue for processing later... deleteQueue.add(new DelayedMCElement(placeHolder)); } else removed = storage.remove(key) != null; if (removed) return DeleteResponse.DELETED; else return DeleteResponse.NOT_FOUND; } /** * @inheritDoc */ public StoreResponse add(LocalCacheElement e) { final long origCasUnique = e.getCasUnique(); e.setCasUnique(casCounter.getAndIncrement()); final boolean stored = storage.putIfAbsent(e.getKey(), e) == null; // we should restore the former cas so that the object isn't left dirty if (!stored) { e.setCasUnique(origCasUnique); } return stored ? StoreResponse.STORED : StoreResponse.NOT_STORED; } /** * @inheritDoc */ public StoreResponse replace(LocalCacheElement e) { return storage.replace(e.getKey(), e) != null ? StoreResponse.STORED : StoreResponse.NOT_STORED; } /** * @inheritDoc */ public StoreResponse append(LocalCacheElement element) { LocalCacheElement old = storage.get(element.getKey()); if (old == null || isBlocked(old) || isExpired(old)) { getMisses.incrementAndGet(); return StoreResponse.NOT_FOUND; } else { return storage.replace(old.getKey(), old, old.append(element)) ? StoreResponse.STORED : StoreResponse.NOT_STORED; } } /** * @inheritDoc */ public StoreResponse prepend(LocalCacheElement element) { LocalCacheElement old = storage.get(element.getKey()); if (old == null || isBlocked(old) || isExpired(old)) { getMisses.incrementAndGet(); return StoreResponse.NOT_FOUND; } else { return storage.replace(old.getKey(), old, old.prepend(element)) ? StoreResponse.STORED : StoreResponse.NOT_STORED; } } /** * @inheritDoc */ public StoreResponse set(LocalCacheElement e) { setCmds.incrementAndGet();//update stats e.setCasUnique(casCounter.getAndIncrement()); storage.put(e.getKey(), e); return StoreResponse.STORED; } /** * @inheritDoc */ public StoreResponse cas(Long cas_key, LocalCacheElement e) { // have to get the element LocalCacheElement element = storage.get(e.getKey()); if (element == null || isBlocked(element)) { getMisses.incrementAndGet(); return StoreResponse.NOT_FOUND; } if (element.getCasUnique() == cas_key) { // casUnique matches, now set the element e.setCasUnique(casCounter.getAndIncrement()); if (storage.replace(e.getKey(), element, e)) return StoreResponse.STORED; else { getMisses.incrementAndGet(); return StoreResponse.NOT_FOUND; } } else { // cas didn't match; someone else beat us to it return StoreResponse.EXISTS; } } /** * @inheritDoc */ public Integer get_add(Key key, int mod) { LocalCacheElement old = storage.get(key); if (old == null || isBlocked(old) || isExpired(old)) { getMisses.incrementAndGet(); return null; } else { LocalCacheElement.IncrDecrResult result = old.add(mod); return storage.replace(old.getKey(), old, result.replace) ? result.oldValue : null; } } protected boolean isBlocked(CacheElement e) { return e.isBlocked() && e.getBlockedUntil() > Now(); } protected boolean isExpired(CacheElement e) { return e.getExpire() != 0 && e.getExpire() < Now(); } /** * @inheritDoc */ public LocalCacheElement[] get(Key ... keys) { getCmds.incrementAndGet();//updates stats LocalCacheElement[] elements = new LocalCacheElement[keys.length]; int x = 0; int hits = 0; int misses = 0; for (Key key : keys) { LocalCacheElement e = storage.get(key); if (e == null || isExpired(e) || e.isBlocked()) { misses++; elements[x] = null; } else { hits++; elements[x] = e; } x++; } getMisses.addAndGet(misses); getHits.addAndGet(hits); return elements; } /** * @inheritDoc */ public boolean flush_all() { return flush_all(0); } /** * @inheritDoc */ public boolean flush_all(int expire) { // TODO implement this, it isn't right... but how to handle efficiently? (don't want to linear scan entire cacheStorage) storage.clear(); return true; } /** * @inheritDoc */ public void close() throws IOException { scavenger.shutdown();; storage.close(); } /** * @inheritDoc */ @Override protected Set<Key> keys() { return storage.keySet(); } /** * @inheritDoc */ @Override public long getCurrentItems() { return storage.size(); } /** * @inheritDoc */ @Override public long getLimitMaxBytes() { return storage.getMemoryCapacity(); } /** * @inheritDoc */ @Override public long getCurrentBytes() { return storage.getMemoryUsed(); } /** * @inheritDoc */ @Override public void asyncEventPing() { DelayedMCElement toDelete = deleteQueue.poll(); if (toDelete != null) { storage.remove(toDelete.element.getKey()); } } /** * Delayed key blocks get processed occasionally. */ protected static class DelayedMCElement implements Delayed { private CacheElement element; public DelayedMCElement(CacheElement element) { this.element = element; } public long getDelay(TimeUnit timeUnit) { return timeUnit.convert(element.getBlockedUntil() - Now(), TimeUnit.MILLISECONDS); } public int compareTo(Delayed delayed) { if (!(delayed instanceof CacheImpl.DelayedMCElement)) return -1; else return element.getKey().toString().compareTo(((DelayedMCElement) delayed).element.getKey().toString()); } } }
Java
package com.thimbleware.jmemcached; import com.thimbleware.jmemcached.storage.hash.SizedItem; import org.jboss.netty.buffer.ChannelBuffer; import java.io.Serializable; import java.nio.ByteBuffer; /** */ public interface CacheElement extends Serializable, SizedItem { public final static long THIRTY_DAYS = 2592000000L; int size(); int hashCode(); long getExpire(); int getFlags(); ChannelBuffer getData(); void setData(ChannelBuffer data); Key getKey(); long getCasUnique(); void setCasUnique(long casUnique); boolean isBlocked(); void block(long blockedUntil); long getBlockedUntil(); CacheElement append(LocalCacheElement element); CacheElement prepend(LocalCacheElement element); LocalCacheElement.IncrDecrResult add(int mod); }
Java
package com.thimbleware.jmemcached.storage.bytebuffer; import com.thimbleware.jmemcached.util.OpenBitSet; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import java.io.IOException; /** * Memory mapped block storage mechanism with a free-list maintained by TreeMap * * Allows memory for storage to be mapped outside of the VM's main memory, and outside the purvey * of the GC. * * Should offer O(Log(N)) search and free of blocks. */ public class ByteBufferBlockStore { protected ChannelBuffer storageBuffer; private long freeBytes; private long storeSizeBytes; private final int blockSizeBytes; private OpenBitSet allocated; private static final ByteBufferBlockStoreFactory BYTE_BUFFER_BLOCK_STORE_FACTORY = new ByteBufferBlockStoreFactory(); /** * Exception thrown on inability to allocate a new block */ public static class BadAllocationException extends RuntimeException { public BadAllocationException(String s) { super(s); } } public static BlockStoreFactory getFactory() { return BYTE_BUFFER_BLOCK_STORE_FACTORY; } public static class ByteBufferBlockStoreFactory implements BlockStoreFactory<ByteBufferBlockStore> { public ByteBufferBlockStore manufacture(long sizeBytes, int blockSizeBytes) { try { ChannelBuffer buffer = ChannelBuffers.buffer((int) sizeBytes); return new ByteBufferBlockStore(buffer, sizeBytes, blockSizeBytes); } catch (IOException e) { throw new RuntimeException(e); } } } /** * Construct a new memory mapped block storage against a filename, with a certain size * and block size. * @param storageBuffer * @param blockSizeBytes the size of a block in the store * @throws java.io.IOException thrown on failure to open the store or map the file */ private ByteBufferBlockStore(ChannelBuffer storageBuffer, long sizeBytes, int blockSizeBytes) throws IOException { this.storageBuffer = storageBuffer; this.blockSizeBytes = blockSizeBytes; initialize((int)sizeBytes); } /** * Constructor used only be subclasses, allowing them to provide their own buffer. */ protected ByteBufferBlockStore(int blockSizeBytes) { this.blockSizeBytes = blockSizeBytes; } protected void initialize(int storeSizeBytes) { // set the size of the store in bytes this.storeSizeBytes = storageBuffer.capacity(); // the number of free bytes starts out as the entire store freeBytes = storeSizeBytes; // clear the buffer storageBuffer.clear(); allocated = new OpenBitSet(storeSizeBytes / blockSizeBytes); clear(); } /** * Rounds up a requested size to the nearest block width. * @param size the requested size * @param blockSize the block size to use * @return the actual mount to use */ public static long roundUp( long size, long blockSize ) { return size - 1L + blockSize - (size - 1L) % blockSize; } /** * Close the store, destroying all data and closing the backing file * @throws java.io.IOException thrown on failure to close file */ public void close() throws IOException { // clear the region list clear(); // freeResources(); // null out the storage to allow the GC to get rid of it storageBuffer = null; } protected void freeResources() throws IOException { // noop } private int markPos(int numBlocks) { int mark = allocated.mark(numBlocks); if (mark == -1) throw new BadAllocationException("unable to allocate room; all blocks consumed"); return mark; } private void clear(int start, int numBlocks) { allocated.clear(start, start + numBlocks); } /** * Allocate a region in the block storage * * @param desiredSize size (in bytes) desired for the region * @param expiry expiry time in ms since epoch *@param timestamp allocation timestamp of the entry * @return the region descriptor */ public Region alloc(int desiredSize, long expiry, long timestamp) { final long desiredBlockSize = roundUp(desiredSize, blockSizeBytes); int numBlocks = (int) (desiredBlockSize / blockSizeBytes); int pos = markPos(numBlocks); freeBytes -= desiredBlockSize; // get the buffer to it int position = pos * blockSizeBytes; ChannelBuffer slice = storageBuffer.slice(position, desiredSize); slice.writerIndex(0); slice.readerIndex(0); return new Region(desiredSize, numBlocks, pos, slice, expiry, timestamp); } public ChannelBuffer get(int startBlock, int size) { return storageBuffer.slice(startBlock * blockSizeBytes, size); } public void free(Region region) { freeBytes += (region.usedBlocks * blockSizeBytes); region.valid = false; region.slice = null; int pos = region.startBlock; clear(pos, region.size / blockSizeBytes); } public void clear() { // say goodbye to the region list allocated = new OpenBitSet(allocated.size()); // reset the # of free bytes back to the max size freeBytes = storeSizeBytes; } public long getStoreSizeBytes() { return storeSizeBytes; } public int getBlockSizeBytes() { return blockSizeBytes; } public long getFreeBytes() { return freeBytes; } }
Java
package com.thimbleware.jmemcached.storage.bytebuffer; import com.thimbleware.jmemcached.Key; import com.thimbleware.jmemcached.LocalCacheElement; import com.thimbleware.jmemcached.storage.CacheStorage; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * Implementation of the cache using the block buffer storage back end. */ public final class BlockStorageCacheStorage implements CacheStorage<Key, LocalCacheElement> { Partition[] partitions; volatile int ceilingBytes; volatile int maximumItems; volatile int numberItems; final long maximumSizeBytes; public BlockStorageCacheStorage(int blockStoreBuckets, int ceilingBytesParam, int blockSizeBytes, long maximumSizeBytes, int maximumItemsVal, BlockStoreFactory factory) { this.partitions = new Partition[blockStoreBuckets]; long bucketSizeBytes = maximumSizeBytes / blockStoreBuckets; for (int i = 0; i < blockStoreBuckets; i++) { this.partitions[i] = new Partition(factory.manufacture(bucketSizeBytes, blockSizeBytes)); } this.numberItems = 0; this.ceilingBytes = 0; this.maximumItems = 0; this.maximumSizeBytes = maximumSizeBytes; } private Partition pickPartition(Key key) { return partitions[hash(key.hashCode()) & (partitions.length - 1)]; } public final long getMemoryCapacity() { long capacity = 0; for (Partition byteBufferBlockStore : partitions) { capacity += byteBufferBlockStore.blockStore.getStoreSizeBytes(); } return capacity; } public final long getMemoryUsed() { long memUsed = 0; for (Partition byteBufferBlockStore : partitions) { memUsed += (byteBufferBlockStore.blockStore.getStoreSizeBytes() - byteBufferBlockStore.blockStore.getFreeBytes()); } return memUsed; } public final int capacity() { return maximumItems; } public final void close() throws IOException { // first clear all items clear(); // then ask the block store to close for (Partition byteBufferBlockStore : partitions) { byteBufferBlockStore.blockStore.close(); } this.partitions = null; } public final LocalCacheElement putIfAbsent(Key key, LocalCacheElement item) { Partition partition = pickPartition(key); partition.storageLock.readLock().lock(); try { Region region = partition.find(key); // not there? add it if (region == null) { partition.storageLock.readLock().unlock(); partition.storageLock.writeLock().lock(); try { numberItems++; partition.add(key, item); } finally { partition.storageLock.readLock().lock(); partition.storageLock.writeLock().unlock(); } return null; } else { // there? return its value return region.toValue(); } } finally { partition.storageLock.readLock().unlock(); } } /** * {@inheritDoc} */ public final boolean remove(Object okey, Object value) { if (!(okey instanceof Key) || (!(value instanceof LocalCacheElement))) return false; Key key = (Key) okey; Partition partition = pickPartition(key); try { partition.storageLock.readLock().lock(); Region region = partition.find(key); if (region == null) return false; else { partition.storageLock.readLock().unlock(); partition.storageLock.writeLock().lock(); try { partition.blockStore.free(region); partition.remove(key, region); numberItems++; return true; } finally { partition.storageLock.readLock().lock(); partition.storageLock.writeLock().unlock(); } } } finally { partition.storageLock.readLock().unlock(); } } public final boolean replace(Key key, LocalCacheElement original, LocalCacheElement replace) { Partition partition = pickPartition(key); partition.storageLock.readLock().lock(); try { Region region = partition.find(key); // not there? that's a fail if (region == null) return false; // there, check for equivalence of value LocalCacheElement el = null; el = region.toValue(); if (!el.equals(original)) { return false; } else { partition.storageLock.readLock().unlock(); partition.storageLock.writeLock().lock(); try { partition.remove(key, region); partition.add(key, replace); return true; } finally { partition.storageLock.readLock().lock(); partition.storageLock.writeLock().unlock(); } } } finally { partition.storageLock.readLock().unlock(); } } public final LocalCacheElement replace(Key key, LocalCacheElement replace) { Partition partition = pickPartition(key); partition.storageLock.readLock().lock(); try { Region region = partition.find(key); // not there? that's a fail if (region == null) return null; // there, LocalCacheElement el = null; el = region.toValue(); partition.storageLock.readLock().unlock(); partition.storageLock.writeLock().lock(); try { partition.remove(key, region); partition.add(key, replace); return el; } finally { partition.storageLock.readLock().lock(); partition.storageLock.writeLock().unlock(); } } finally { partition.storageLock.readLock().unlock(); } } public final int size() { return numberItems; } public final boolean isEmpty() { return numberItems == 0; } public final boolean containsKey(Object okey) { if (!(okey instanceof Key)) return false; Key key = (Key) okey; Partition partition = pickPartition(key); try { partition.storageLock.readLock().lock(); return partition.has(key); } finally { partition.storageLock.readLock().unlock(); } } public final boolean containsValue(Object o) { throw new UnsupportedOperationException("operation not supported"); } public final LocalCacheElement get(Object okey) { if (!(okey instanceof Key)) return null; Key key = (Key) okey; Partition partition = pickPartition(key); try { partition.storageLock.readLock().lock(); Region region = partition.find(key); if (region == null) return null; return region.toValue(); } finally { partition.storageLock.readLock().unlock(); } } public final LocalCacheElement put(final Key key, final LocalCacheElement item) { Partition partition = pickPartition(key); partition.storageLock.readLock().lock(); try { Region region = partition.find(key); partition.storageLock.readLock().unlock(); partition.storageLock.writeLock().lock(); try { LocalCacheElement old = null; if (region != null) { old = region.toValue(); } if (region != null) partition.remove(key, region); partition.add(key, item); numberItems++; return old; } finally { partition.storageLock.readLock().lock(); partition.storageLock.writeLock().unlock(); } } finally { partition.storageLock.readLock().unlock(); } } public final LocalCacheElement remove(Object okey) { if (!(okey instanceof Key)) return null; Key key = (Key) okey; Partition partition = pickPartition(key); try { partition.storageLock.readLock().lock(); Region region = partition.find(key); if (region == null) return null; else { partition.storageLock.readLock().unlock(); partition.storageLock.writeLock().lock(); try { LocalCacheElement old = null; old = region.toValue(); partition.blockStore.free(region); partition.remove(key, region); numberItems--; return old; } finally { partition.storageLock.readLock().lock(); partition.storageLock.writeLock().unlock(); } } } finally { partition.storageLock.readLock().unlock(); } } public final void putAll(Map<? extends Key, ? extends LocalCacheElement> map) { // absent, lock the store and put the new value in for (Entry<? extends Key, ? extends LocalCacheElement> entry : map.entrySet()) { Key key = entry.getKey(); LocalCacheElement item; item = entry.getValue(); put(key, item); } } public final void clear() { for (Partition partition : partitions) { partition.storageLock.writeLock().lock(); numberItems += partition.keys().size() * - 1; try { partition.clear(); } finally { partition.storageLock.writeLock().unlock(); } } } public Set<Key> keySet() { Set<Key> keys = new HashSet<Key>(); for (Partition partition : partitions) { keys.addAll(partition.keys()); } return keys; } public Collection<LocalCacheElement> values() { throw new UnsupportedOperationException("operation not supported"); } public Set<Entry<Key, LocalCacheElement>> entrySet() { throw new UnsupportedOperationException("operation not supported"); } protected static int hash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. h += (h << 15) ^ 0xffffcd7d; h ^= (h >>> 10); h += (h << 3); h ^= (h >>> 6); h += (h << 2) + (h << 14); return h ^ (h >>> 16); } }
Java
package com.thimbleware.jmemcached.storage.bytebuffer; import com.thimbleware.jmemcached.Key; import com.thimbleware.jmemcached.LocalCacheElement; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferInputStream; import java.io.IOException; import java.io.ObjectInputStream; /** * Represents a number of allocated blocks in the store */ public final class Region { /** * Size in bytes of the requested area */ public final int size; /** * Size in blocks of the requested area */ public final int usedBlocks; /** * Offset into the memory region */ final int startBlock; final long timestamp; final long expiry; /** * Flag which is true if the region is valid and in use. * Set to false on free() */ public boolean valid = false; public ChannelBuffer slice; public Region(int size, int usedBlocks, int startBlock, ChannelBuffer slice, long expiry, long timestamp) { this.size = size; this.usedBlocks = usedBlocks; this.startBlock = startBlock; this.slice = slice; this.expiry = expiry; this.timestamp = timestamp; this.valid = true; } public Key keyFromRegion() { slice.readerIndex(0); int length = slice.readInt(); return new Key(slice.slice(slice.readerIndex(), length)); } public LocalCacheElement toValue() { slice.readerIndex(0); return LocalCacheElement.readFromBuffer(slice); } }
Java
package com.thimbleware.jmemcached.storage.bytebuffer; /** */ public interface BlockStoreFactory<BS extends ByteBufferBlockStore> { BS manufacture(long sizeBytes, int blockSizeBytes); }
Java
package com.thimbleware.jmemcached.storage.bytebuffer; import com.thimbleware.jmemcached.Key; import com.thimbleware.jmemcached.LocalCacheElement; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import java.util.*; import java.util.concurrent.locks.ReentrantReadWriteLock; /** */ public final class Partition { private static final int NUM_BUCKETS = 32768; ReentrantReadWriteLock storageLock = new ReentrantReadWriteLock(); ChannelBuffer[] buckets = new ChannelBuffer[NUM_BUCKETS]; ByteBufferBlockStore blockStore; int numberItems; Partition(ByteBufferBlockStore blockStore) { this.blockStore = blockStore; } public Region find(Key key) { int bucket = findBucketNum(key); if (buckets[bucket] == null) return null; ChannelBuffer regions = buckets[bucket].slice(); regions.readerIndex(0); while (regions.readableBytes() > 0) { int totsize = regions.readInt(); int rsize = regions.readInt(); int rusedBlocks = regions.readInt(); int rstartBlock = regions.readInt(); long expiry = regions.readLong(); long timestamp = regions.readLong(); int rkeySize = regions.readInt(); if (rkeySize == key.bytes.capacity()) { ChannelBuffer rkey = regions.readSlice(rkeySize); key.bytes.readerIndex(0); if (rkey.equals(key.bytes)) return new Region(rsize, rusedBlocks, rstartBlock, blockStore.get(rstartBlock, rsize), expiry, timestamp); } else { regions.skipBytes(rkeySize); } } return null; } public boolean has(Key key) { int bucket = findBucketNum(key); if (buckets[bucket] == null) return false; ChannelBuffer regions = buckets[bucket].slice(); regions.readerIndex(0); while (regions.readableBytes() > 0) { int totsize = regions.readInt(); regions.skipBytes(28); int rkeySize = regions.readInt(); if (rkeySize == key.bytes.capacity()) { ChannelBuffer rkey = regions.readSlice(rkeySize); key.bytes.readerIndex(0); if (rkey.equals(key.bytes)) return true; } else { regions.skipBytes(rkeySize); } } return false; } private int findBucketNum(Key key) { int hash = BlockStorageCacheStorage.hash(key.hashCode()); return hash & (buckets.length - 1); } public void remove(Key key, Region region) { int bucket = findBucketNum(key); ChannelBuffer newRegion = ChannelBuffers.dynamicBuffer(128); ChannelBuffer regions = buckets[bucket].slice(); if (regions == null) return; regions.readerIndex(0); while (regions.readableBytes() > 0) { // read key portion then region portion int pos = regions.readerIndex(); int totsize = regions.readInt(); regions.skipBytes(28); int rkeySize = regions.readInt(); ChannelBuffer rkey = regions.readBytes(rkeySize); if (rkeySize != key.bytes.capacity() || !rkey.equals(key.bytes)) { newRegion.writeBytes(regions.slice(pos, regions.readerIndex())); } } buckets[bucket] = newRegion; numberItems--; } public Region add(Key key, LocalCacheElement e) { Region region = blockStore.alloc(e.bufferSize(), e.getExpire(), System.currentTimeMillis()); e.writeToBuffer(region.slice); int bucket = findBucketNum(key); ChannelBuffer outbuf = ChannelBuffers.directBuffer(32 + key.bytes.capacity()); outbuf.writeInt(region.size); outbuf.writeInt(region.usedBlocks); outbuf.writeInt(region.startBlock); outbuf.writeLong(region.expiry); outbuf.writeLong(region.timestamp); outbuf.writeInt(key.bytes.capacity()); key.bytes.readerIndex(0); outbuf.writeBytes(key.bytes); ChannelBuffer regions = buckets[bucket]; if (regions == null) { regions = ChannelBuffers.dynamicBuffer(128); buckets[bucket] = regions; } regions.writeInt(outbuf.capacity()); regions.writeBytes(outbuf); numberItems++; return region; } public void clear() { for (ChannelBuffer bucket : buckets) { if (bucket != null) bucket.clear(); } blockStore.clear(); numberItems = 0; } public Collection<Key> keys() { Set<Key> keys = new HashSet<Key>(); for (ChannelBuffer regionsa : buckets) { if (regionsa != null) { ChannelBuffer regions = regionsa.slice(); regions.readerIndex(0); while (regions.readableBytes() > 0) { // read key portion then region portion int totsize = regions.readInt(); regions.skipBytes(28); int rkeySize = regions.readInt(); ChannelBuffer rkey = regions.readBytes(rkeySize); keys.add(new Key(rkey)); } } } return keys; } public int getNumberItems() { return numberItems; } }
Java
package com.thimbleware.jmemcached.storage.mmap; import com.thimbleware.jmemcached.storage.bytebuffer.BlockStoreFactory; import com.thimbleware.jmemcached.storage.bytebuffer.ByteBufferBlockStore; import org.jboss.netty.buffer.ChannelBuffers; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import static java.nio.channels.FileChannel.MapMode.*; /** * Memory mapped block storage mechanism with a free-list maintained by TreeMap * * Allows memory for storage to be mapped outside of the VM's main memory, and outside the purvey * of the GC. * * Should offer O(Log(N)) search and free of blocks. */ public final class MemoryMappedBlockStore extends ByteBufferBlockStore { private File physicalFile; private RandomAccessFile fileStorage; private static final MemoryMappedBlockStoreFactory MEMORY_MAPPED_BLOCK_STORE_FACTORY = new MemoryMappedBlockStoreFactory(); /** * Construct a new memory mapped block storage against a filename, with a certain size * and block size. * @param maxBytes the number of bytes to allocate in the file * @param file the file to use * @param blockSizeBytes the size of a block in the store * @throws java.io.IOException thrown on failure to open the store or map the file */ private MemoryMappedBlockStore(long maxBytes, File file, int blockSizeBytes) throws IOException { super(blockSizeBytes); storageBuffer = ChannelBuffers.wrappedBuffer(getMemoryMappedFileStorage(maxBytes, file)); initialize(storageBuffer.capacity()); } public static BlockStoreFactory getFactory() { return MEMORY_MAPPED_BLOCK_STORE_FACTORY; } private MappedByteBuffer getMemoryMappedFileStorage(long maxBytes, File file) throws IOException { this.physicalFile = file; // open the file for read-write fileStorage = new RandomAccessFile(file, "rw"); fileStorage.seek(maxBytes); return fileStorage.getChannel().map(PRIVATE, 0, maxBytes); } @Override protected void freeResources() throws IOException { super.freeResources(); // close the actual file fileStorage.close(); // delete the file; it is no longer of any use physicalFile.delete(); physicalFile = null; fileStorage = null; } public static class MemoryMappedBlockStoreFactory implements BlockStoreFactory<MemoryMappedBlockStore> { public MemoryMappedBlockStore manufacture(long sizeBytes, int blockSizeBytes) { try { final File tempFile = File.createTempFile("jmemcached", "blockStore"); tempFile.deleteOnExit(); return new MemoryMappedBlockStore(sizeBytes, tempFile, blockSizeBytes); } catch (IOException e) { throw new RuntimeException(e); } } } }
Java
package com.thimbleware.jmemcached.storage; import com.thimbleware.jmemcached.storage.hash.SizedItem; import java.io.IOException; import java.util.concurrent.ConcurrentMap; /** * The interface for cache storage. Essentially a concurrent map but with methods for investigating the heap * state of the storage unit and with additional support for explicit resource-cleanup (close()). */ public interface CacheStorage<K, V extends SizedItem> extends ConcurrentMap<K, V> { /** * @return the capacity (in bytes) of the storage */ long getMemoryCapacity(); /** * @return the current usage (in bytes) of the storage */ long getMemoryUsed(); /** * @return the capacity (in # of items) of the storage */ int capacity(); /** * Close the storage unit, deallocating any resources it might be currently holding. * @throws java.io.IOException thrown if IO faults occur anywhere during close. */ void close() throws IOException; }
Java
package com.thimbleware.jmemcached.storage.hash; /* * Copyright 2009 Benjamin Manes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.thimbleware.jmemcached.storage.CacheStorage; import java.io.Serializable; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * A {@link ConcurrentMap} with a doubly-linked list running through its entries. * <p/> * This class provides the same semantics as a {@link ConcurrentHashMap} in terms of * iterators, acceptable keys, and concurrency characteristics, but perform slightly * worse due to the added expense of maintaining the linked list. It differs from * {@link java.util.LinkedHashMap} in that it does not provide predictable iteration * order. * <p/> * This map is intended to be used for caches and provides the following eviction policies: * <ul> * <li> First-in, First-out: Also known as insertion order. This policy has excellent * concurrency characteristics and an adequate hit rate. * <li> Second-chance: An enhanced FIFO policy that marks entries that have been retrieved * and saves them from being evicted until the next pass. This enhances the FIFO policy * by making it aware of "hot" entries, which increases its hit rate to be equal to an * LRU's under normal workloads. In the worst case, where all entries have been saved, * this policy degrades to a FIFO. * <li> Least Recently Used: An eviction policy based on the observation that entries that * have been used recently will likely be used again soon. This policy provides a good * approximation of an optimal algorithm, but suffers by being expensive to maintain. * The cost of reordering entries on the list during every access operation reduces * the concurrency and performance characteristics of this policy. * </ul> * * @author <a href="mailto:ben.manes@reardencommerce.com">Ben Manes</a> * @see http://code.google.com/p/concurrentlinkedhashmap/ */ public final class ConcurrentLinkedHashMap<K, V extends SizedItem> extends AbstractMap<K, V> implements Serializable, CacheStorage<K, V> { private static final EvictionListener<?, ?> nullListener = new EvictionListener<Object, Object>() { public void onEviction(Object key, Object value) { } }; private static final long serialVersionUID = 8350170357874293408L; final ConcurrentMap<K, Node<K, V>> data; final EvictionListener<K, V> listener; final AtomicInteger capacity; final EvictionPolicy policy; final AtomicInteger length; final Node<K, V> sentinel; final Lock lock; final AtomicLong memoryCapacity; final AtomicLong memoryUsed; /** * Creates a map with the specified eviction policy, maximum capacity, and at the default concurrency level. * * @param policy The eviction policy to apply when the size exceeds the maximum capacity. * @param maximumCapacity The maximum capacity to coerces to. The size may exceed it temporarily. */ @SuppressWarnings("unchecked") public static <K, V extends SizedItem> ConcurrentLinkedHashMap<K, V> create(EvictionPolicy policy, int maximumCapacity, long maximumMemoryCapacity) { return create(policy, maximumCapacity, maximumMemoryCapacity, 16, (EvictionListener<K, V>) nullListener); } /** * Creates a map with the specified eviction policy, maximum capacity, eviction listener, and at the * default concurrency level. * * @param policy The eviction policy to apply when the size exceeds the maximum capacity. * @param maximumCapacity The maximum capacity to coerces to. The size may exceed it temporarily. * @param listener The listener registered for notification when an entry is evicted. */ public static <K, V extends SizedItem> ConcurrentLinkedHashMap<K, V> create(EvictionPolicy policy, int maximumCapacity, long maximumMemoryCapacity, EvictionListener<K, V> listener) { return create(policy, maximumCapacity, maximumMemoryCapacity, 16, listener); } /** * Creates a map with the specified eviction policy, maximum capacity, and concurrency level. * * @param policy The eviction policy to apply when the size exceeds the maximum capacity. * @param maximumCapacity The maximum capacity to coerces to. The size may exceed it temporarily. * @param concurrencyLevel The estimated number of concurrently updating threads. The implementation * performs internal sizing to try to accommodate this many threads. */ @SuppressWarnings("unchecked") public static <K, V extends SizedItem> ConcurrentLinkedHashMap<K, V> create(EvictionPolicy policy, int maximumCapacity, long maximumMemoryCapacity, int concurrencyLevel) { return create(policy, maximumCapacity, maximumMemoryCapacity, concurrencyLevel, (EvictionListener<K, V>) nullListener); } /** * Creates a map with the specified eviction policy, maximum capacity, eviction listener, and concurrency level. * * @param policy The eviction policy to apply when the size exceeds the maximum capacity. * @param maximumCapacity The maximum capacity to coerces to. The size may exceed it temporarily. * @param concurrencyLevel The estimated number of concurrently updating threads. The implementation * performs internal sizing to try to accommodate this many threads. * @param listener The listener registered for notification when an entry is evicted. */ public static <K, V extends SizedItem> ConcurrentLinkedHashMap<K, V> create(EvictionPolicy policy, int maximumCapacity, long maximumMemoryCapacity, int concurrencyLevel, EvictionListener<K, V> listener) { return new ConcurrentLinkedHashMap<K, V>(policy, maximumCapacity, maximumMemoryCapacity, concurrencyLevel, listener); } /** * Creates a map with the specified eviction policy, maximum capacity, eviction listener, and concurrency level. * * @param policy The eviction policy to apply when the size exceeds the maximum capacity. * @param maximumCapacity The maximum capacity to coerces to. The size may exceed it temporarily. * @param concurrencyLevel The estimated number of concurrently updating threads. The implementation * performs internal sizing to try to accommodate this many threads. * @param listener The listener registered for notification when an entry is evicted. */ private ConcurrentLinkedHashMap(EvictionPolicy policy, int maximumCapacity, long maximumMemoryCapacity, int concurrencyLevel, EvictionListener<K, V> listener) { if ((policy == null) || (maximumCapacity < 0) || (concurrencyLevel <= 0) || (listener == null)) { throw new IllegalArgumentException(); } this.data = new ConcurrentHashMap<K, Node<K, V>>(maximumCapacity, 0.75f, concurrencyLevel); this.capacity = new AtomicInteger(maximumCapacity); this.length = new AtomicInteger(); this.listener = listener; this.policy = policy; this.lock = new ReentrantLock(); this.sentinel = new Node<K, V>(lock); this.memoryUsed = new AtomicLong(0); this.memoryCapacity = new AtomicLong(maximumMemoryCapacity); } /** * Determines whether the map has exceeded its capacity. * * @return Whether the map has overflowed and an entry should be evicted. */ private boolean isOverflow() { return size() > capacity() || getMemoryUsed() > getMemoryCapacity(); } public long getMemoryCapacity() { return memoryCapacity.get(); } public long getMemoryUsed() { return memoryUsed.get(); } /** * Sets the maximum capacity of the map and eagerly evicts entries until it shrinks to the appropriate size. * * @param capacity The maximum capacity of the map. */ public void setCapacity(int capacity) { if (capacity < 0) { throw new IllegalArgumentException(); } this.capacity.set(capacity); while (evict()) { } } /** * Sets the maximum capacity of the map and eagerly evicts entries until it shrinks to the appropriate size. * * @param capacity The maximum capacity of the map. */ public void setMemoryCapacity(int capacity) { if (capacity < 0) { throw new IllegalArgumentException(); } this.memoryCapacity.set(capacity); while (evict()) { } } /** * Retrieves the maximum capacity of the map. * * @return The maximum capacity. */ public int capacity() { return capacity.get(); } public void close() { clear(); } /** * {@inheritDoc} */ @Override public int size() { int size = length.get(); return (size >= 0) ? size : 0; } /** * {@inheritDoc} */ @Override public void clear() { for (K key : keySet()) { remove(key); } } /** * {@inheritDoc} */ @Override public boolean containsKey(Object key) { return data.containsKey(key); } /** * {@inheritDoc} */ @Override public boolean containsValue(Object value) { if (value == null) { throw new IllegalArgumentException(); } return data.containsValue(new Node<Object, Object>(null, value, null, lock)); } /** * Evicts a single entry if the map exceeds the maximum capacity. */ private boolean evict() { while (isOverflow()) { Node<K, V> node = sentinel.getNext(); if (node == sentinel) { return false; } else if (policy.onEvict(this, node)) { // Attempt to remove the node if it's still available if (data.remove(node.getKey(), new Identity(node))) { length.decrementAndGet(); memoryUsed.addAndGet(-1 * node.getValue().size()); node.remove(); listener.onEviction(node.getKey(), node.getValue()); return true; } } } return false; } /** * {@inheritDoc} */ @Override public V get(Object key) { Node<K, V> node = data.get(key); if (node != null) { policy.onAccess(this, node); return node.getValue(); } return null; } /** * {@inheritDoc} */ @Override public V put(K key, V value) { if (value == null) { throw new IllegalArgumentException(); } Node<K, V> old = putIfAbsent(new Node<K, V>(key, value, sentinel, lock)); memoryUsed.addAndGet(value.size()); if (old == null) { return null; } else { memoryUsed.addAndGet(-1 * old.getValue().size()); return old.getAndSetValue(value); } } /** * {@inheritDoc} */ public V putIfAbsent(K key, V value) { if (value == null) { throw new IllegalArgumentException(); } Node<K, V> old = putIfAbsent(new Node<K, V>(key, value, sentinel, lock)); if (old == null) { memoryUsed.addAndGet(value.size()); return null; } else return old.getValue(); } /** * Adds a node to the list and data store if it does not already exist. * * @param node An unlinked node to add. * @return The previous value in the data store. */ private Node<K, V> putIfAbsent(Node<K, V> node) { Node<K, V> old = data.putIfAbsent(node.getKey(), node); if (old == null) { length.incrementAndGet(); node.appendToTail(); evict(); } else { policy.onAccess(this, old); } return old; } /** * {@inheritDoc} */ @Override public V remove(Object key) { Node<K, V> node = data.remove(key); if (node == null) { return null; } length.decrementAndGet(); memoryUsed.addAndGet(-1 * node.getValue().size()); node.remove(); return node.getValue(); } /** * {@inheritDoc} */ public boolean remove(Object key, Object value) { Node<K, V> node = data.get(key); if ((node != null) && node.value.equals(value) && data.remove(key, new Identity(node))) { length.decrementAndGet(); memoryUsed.addAndGet(-1 * node.getValue().size()); node.remove(); return true; } return false; } /** * {@inheritDoc} */ public V replace(K key, V value) { if (value == null) { throw new IllegalArgumentException(); } Node<K, V> node = data.get(key); if (node == null) return null; else { memoryUsed.addAndGet(-1 * node.getValue().size()); memoryUsed.addAndGet(value.size()); return node.getAndSetValue(value); } } /** * {@inheritDoc} */ public boolean replace(K key, V oldValue, V newValue) { if (newValue == null) { throw new IllegalArgumentException(); } Node<K, V> node = data.get(key); if (node == null) return false; else { final boolean val = node.casValue(oldValue, newValue); if (val) { memoryUsed.addAndGet(-1 * oldValue.size()); memoryUsed.addAndGet(newValue.size()); } return val; } } /** * {@inheritDoc} */ @Override public Set<K> keySet() { return new KeySet(); } /** * {@inheritDoc} */ @Override public Collection<V> values() { return new Values(); } /** * {@inheritDoc} */ @Override public Set<Entry<K, V>> entrySet() { return new EntrySet(); } /** * A listener registered for notification when an entry is evicted. */ public interface EvictionListener<K, V> { /** * A call-back notification that the entry was evicted. * * @param key The evicted key. * @param value The evicted value. */ void onEviction(K key, V value); } /** * The replacement policy to apply to determine which entry to discard when the capacity has been reached. */ public enum EvictionPolicy { /** * Evicts entries based on insertion order. */ FIFO() { @Override <K, V extends SizedItem> void onAccess(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) { // do nothing } @Override <K, V extends SizedItem> boolean onEvict(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) { return true; } }, /** * Evicts entries based on insertion order, but gives an entry a "second chance" if it has been requested recently. */ SECOND_CHANCE() { @Override <K, V extends SizedItem> void onAccess(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) { node.setMarked(true); } @Override <K, V extends SizedItem> boolean onEvict(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) { if (node.isMarked()) { node.moveToTail(); node.setMarked(false); return false; } return true; } }, /** * Evicts entries based on how recently they are used, with the least recent evicted first. */ LRU() { @Override <K, V extends SizedItem> void onAccess(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) { node.moveToTail(); } @Override <K, V extends SizedItem> boolean onEvict(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) { return true; } }; /** * Performs any operations required by the policy after a node was successfully retrieved. */ abstract <K, V extends SizedItem> void onAccess(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node); /** * Determines whether to evict the node at the head of the list. */ abstract <K, V extends SizedItem> boolean onEvict(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node); } /** * A node on the double-linked list. This list cross-cuts the data store. */ @SuppressWarnings("unchecked") protected static final class Node<K, V> implements Serializable { private static final long serialVersionUID = 1461281468985304519L; private static final AtomicReferenceFieldUpdater<Node, Object> valueUpdater = AtomicReferenceFieldUpdater.newUpdater(Node.class, Object.class, "value"); private static final Node UNLINKED = new Node(null); private final K key; private final Lock lock; private final Node<K, V> sentinel; private volatile V value; private volatile boolean marked; private volatile Node<K, V> prev; private volatile Node<K, V> next; /** * Creates a new sentinel node. */ public Node(Lock lock) { this.sentinel = this; this.value = null; this.lock = lock; this.prev = this; this.next = this; this.key = null; } /** * Creates a new, unlinked node. */ public Node(K key, V value, Node<K, V> sentinel, Lock lock) { this.sentinel = sentinel; this.next = UNLINKED; this.prev = UNLINKED; this.value = value; this.lock = lock; this.key = key; } /** * Appends the node to the tail of the list. */ public void appendToTail() { lock.lock(); try { // Allow moveToTail() to no-op or removal to spin-wait next = sentinel; // Read the tail on the stack to avoid unnecessary volatile reads final Node<K, V> tail = sentinel.prev; sentinel.prev = this; tail.next = this; prev = tail; } finally { lock.unlock(); } } /** * Removes the node from the list. * <p/> * If the node has not yet been appended to the tail it will wait for that operation to complete. */ public void remove() { for (; ;) { if (isUnlinked()) { continue; // await appending } lock.lock(); try { if (isUnlinked()) { continue; // await appending } prev.next = next; next.prev = prev; next = UNLINKED; // mark as unlinked } finally { lock.unlock(); } return; } } /** * Moves the node to the tail. * <p/> * If the node has been unlinked or is already at the tail, no-ops. */ public void moveToTail() { if (isTail() || isUnlinked()) { return; } lock.lock(); try { if (isTail() || isUnlinked()) { return; } // unlink prev.next = next; next.prev = prev; // link next = sentinel; // ordered for isAtTail() prev = sentinel.prev; sentinel.prev = this; prev.next = this; } finally { lock.unlock(); } } /** * Checks whether the node is linked on the list chain. * * @return Whether the node has not yet been linked on the list. */ public boolean isUnlinked() { return (next == UNLINKED); } /** * Checks whether the node is the last linked on the list chain. * * @return Whether the node is at the tail of the list. */ public boolean isTail() { return (next == sentinel); } /* * Key operators */ public K getKey() { return key; } /* * Value operators */ public V getValue() { return (V) valueUpdater.get(this); } public V getAndSetValue(V value) { return (V) valueUpdater.getAndSet(this, value); } public boolean casValue(V expect, V update) { return valueUpdater.compareAndSet(this, expect, update); } /* * Previous node operators */ public Node<K, V> getPrev() { return prev; } /* * Next node operators */ public Node<K, V> getNext() { return next; } /* * Access frequency operators */ public boolean isMarked() { return marked; } public void setMarked(boolean marked) { this.marked = marked; } /** * Only ensures that the values are equal, as the key may be <tt>null</tt> for look-ups. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof Node)) { return false; } V value = getValue(); Node<?, ?> node = (Node<?, ?>) obj; return (value == null) ? (node.getValue() == null) : value.equals(node.getValue()); } @Override public int hashCode() { return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode()); } @Override public String toString() { lock.lock(); try { return String.format("key=%s - prev=%s ; next=%s", valueOf(key), valueOf(prev.key), valueOf(next.key)); } finally { lock.unlock(); } } private String valueOf(K key) { return (key == null) ? "sentinel" : key.toString(); } } /** * Allows {@link #equals(Object)} to compare using object identity. */ private static final class Identity { private final Object delegate; public Identity(Object delegate) { this.delegate = delegate; } @Override public boolean equals(Object o) { return (o == delegate); } } /** * An adapter to safely externalize the keys. */ private final class KeySet extends AbstractSet<K> { private final ConcurrentLinkedHashMap<K, V> map = ConcurrentLinkedHashMap.this; @Override public int size() { return map.size(); } @Override public void clear() { map.clear(); } @Override public Iterator<K> iterator() { return new KeyIterator(); } @Override public boolean contains(Object obj) { return map.containsKey(obj); } @Override public boolean remove(Object obj) { return (map.remove(obj) != null); } @Override public Object[] toArray() { return map.data.keySet().toArray(); } @Override public <T> T[] toArray(T[] array) { return map.data.keySet().toArray(array); } } /** * An adapter to safely externalize the keys. */ private final class KeyIterator implements Iterator<K> { private final EntryIterator iterator = new EntryIterator(ConcurrentLinkedHashMap.this.data.values().iterator()); public boolean hasNext() { return iterator.hasNext(); } public K next() { return iterator.next().getKey(); } public void remove() { iterator.remove(); } } /** * An adapter to represent the data store's values in the external type. */ private final class Values extends AbstractCollection<V> { private final ConcurrentLinkedHashMap<K, V> map = ConcurrentLinkedHashMap.this; @Override public int size() { return map.size(); } @Override public void clear() { map.clear(); } @Override public Iterator<V> iterator() { return new ValueIterator(); } @Override public boolean contains(Object o) { return map.containsValue(o); } @Override public Object[] toArray() { Collection<V> values = new ArrayList<V>(size()); for (V value : this) { values.add(value); } return values.toArray(); } @Override public <T> T[] toArray(T[] array) { Collection<V> values = new ArrayList<V>(size()); for (V value : this) { values.add(value); } return values.toArray(array); } } /** * An adapter to represent the data store's values in the external type. */ private final class ValueIterator implements Iterator<V> { private final EntryIterator iterator = new EntryIterator(ConcurrentLinkedHashMap.this.data.values().iterator()); public boolean hasNext() { return iterator.hasNext(); } public V next() { return iterator.next().getValue(); } public void remove() { iterator.remove(); } } /** * An adapter to represent the data store's entry set in the external type. */ private final class EntrySet extends AbstractSet<Entry<K, V>> { private final ConcurrentLinkedHashMap<K, V> map = ConcurrentLinkedHashMap.this; @Override public int size() { return map.size(); } @Override public void clear() { map.clear(); } @Override public Iterator<Entry<K, V>> iterator() { return new EntryIterator(map.data.values().iterator()); } @Override public boolean contains(Object obj) { if (!(obj instanceof Entry)) { return false; } Entry<?, ?> entry = (Entry<?, ?>) obj; Node<K, V> node = map.data.get(entry.getKey()); return (node != null) && (node.value.equals(entry.getValue())); } @Override public boolean add(Entry<K, V> entry) { return (map.putIfAbsent(entry.getKey(), entry.getValue()) == null); } @Override public boolean remove(Object obj) { if (!(obj instanceof Entry)) { return false; } Entry<?, ?> entry = (Entry<?, ?>) obj; return map.remove(entry.getKey(), entry.getValue()); } @Override public Object[] toArray() { Collection<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(size()); for (Entry<K, V> entry : this) { entries.add(new SimpleEntry<K, V>(entry)); } return entries.toArray(); } @Override public <T> T[] toArray(T[] array) { Collection<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(size()); for (Entry<K, V> entry : this) { entries.add(new SimpleEntry<K, V>(entry)); } return entries.toArray(array); } } /** * An adapter to represent the data store's entry iterator in the external type. */ private final class EntryIterator implements Iterator<Entry<K, V>> { private final Iterator<Node<K, V>> iterator; private Entry<K, V> current; public EntryIterator(Iterator<Node<K, V>> iterator) { this.iterator = iterator; } public boolean hasNext() { return iterator.hasNext(); } public Entry<K, V> next() { current = new NodeEntry(iterator.next()); return current; } public void remove() { if (current == null) { throw new IllegalStateException(); } ConcurrentLinkedHashMap.this.remove(current.getKey(), current.getValue()); current = null; } } /** * An entry that is tied to the map instance to allow updates through the entry or the map to be visible. */ private final class NodeEntry implements Entry<K, V> { private final ConcurrentLinkedHashMap<K, V> map = ConcurrentLinkedHashMap.this; private final Node<K, V> node; public NodeEntry(Node<K, V> node) { this.node = node; } public K getKey() { return node.getKey(); } public V getValue() { if (node.isUnlinked()) { V value = map.get(getKey()); if (value != null) { return value; } } return node.getValue(); } public V setValue(V value) { return map.replace(getKey(), value); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof Entry)) { return false; } Entry<?, ?> entry = (Entry<?, ?>) obj; return eq(getKey(), entry.getKey()) && eq(getValue(), entry.getValue()); } @Override public int hashCode() { K key = getKey(); V value = getValue(); return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode()); } @Override public String toString() { return getKey() + "=" + getValue(); } private boolean eq(Object o1, Object o2) { return (o1 == null) ? (o2 == null) : o1.equals(o2); } } /** * This duplicates {@link java.util.AbstractMap.SimpleEntry} until the class is made accessible (public in JDK-6). */ private static class SimpleEntry<K, V> implements Entry<K, V> { private final K key; private V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } public SimpleEntry(Entry<K, V> e) { this.key = e.getKey(); this.value = e.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof Entry)) { return false; } Entry<?, ?> entry = (Entry<?, ?>) obj; return eq(key, entry.getKey()) && eq(value, entry.getValue()); } @Override public int hashCode() { return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode()); } @Override public String toString() { return key + "=" + value; } private static boolean eq(Object o1, Object o2) { return (o1 == null) ? (o2 == null) : o1.equals(o2); } } }
Java
package com.thimbleware.jmemcached.storage.hash; /** */ public interface SizedItem { int size(); }
Java
package com.thimbleware.jmemcached; import java.io.IOException; import java.util.Set; import java.util.Map; /** */ public interface Cache<CACHE_ELEMENT extends CacheElement> { /** * Enum defining response statuses from set/add type commands */ public enum StoreResponse { STORED, NOT_STORED, EXISTS, NOT_FOUND } /** * Enum defining responses statuses from removal commands */ public enum DeleteResponse { DELETED, NOT_FOUND } /** * Handle the deletion of an item from the cache. * * @param key the key for the item * @param time an amount of time to block this entry in the cache for further writes * @return the message response */ DeleteResponse delete(Key key, int time); /** * Add an element to the cache * * @param e the element to add * @return the store response code */ StoreResponse add(CACHE_ELEMENT e); /** * Replace an element in the cache * * @param e the element to replace * @return the store response code */ StoreResponse replace(CACHE_ELEMENT e); /** * Append bytes to the end of an element in the cache * * @param element the element to append * @return the store response code */ StoreResponse append(CACHE_ELEMENT element); /** * Prepend bytes to the end of an element in the cache * * @param element the element to append * @return the store response code */ StoreResponse prepend(CACHE_ELEMENT element); /** * Set an element in the cache * * @param e the element to set * @return the store response code */ StoreResponse set(CACHE_ELEMENT e); /** * Set an element in the cache but only if the element has not been touched * since the last 'gets' * @param cas_key the cas key returned by the last gets * @param e the element to set * @return the store response code */ StoreResponse cas(Long cas_key, CACHE_ELEMENT e); /** * Increment/decremen t an (integer) element in the cache * @param key the key to increment * @param mod the amount to add to the value * @return the message response */ Integer get_add(Key key, int mod); /** * Get element(s) from the cache * @param keys the key for the element to lookup * @return the element, or 'null' in case of cache miss. */ CACHE_ELEMENT[] get(Key ... keys); /** * Flush all cache entries * @return command response */ boolean flush_all(); /** * Flush all cache entries with a timestamp after a given expiration time * @param expire the flush time in seconds * @return command response */ boolean flush_all(int expire); /** * Close the cache, freeing all resources on which it depends. * @throws IOException */ void close() throws IOException; /** * @return the # of items in the cache */ long getCurrentItems(); /** * @return the maximum size of the cache (in bytes) */ long getLimitMaxBytes(); /** * @return the current cache usage (in bytes) */ long getCurrentBytes(); /** * @return the number of get commands executed */ int getGetCmds(); /** * @return the number of set commands executed */ int getSetCmds(); /** * @return the number of get hits */ int getGetHits(); /** * @return the number of stats */ int getGetMisses(); /** * Retrieve stats about the cache. If an argument is specified, a specific category of stats is requested. * @param arg a specific extended stat sub-category * @return a map of stats */ Map<String, Set<String>> stat(String arg); /** * Called periodically by the network event loop to process any pending events. * (such as delete queues, etc.) */ void asyncEventPing(); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image sharpening methods. * * @author alanv@google.com (Alan Viverette) */ public class Enhance { static { System.loadLibrary("lept"); } /** * Performs unsharp masking (edge enhancement). * <p> * Notes: * <ul> * <li>We use symmetric smoothing filters of odd dimension, typically use * sizes of 3, 5, 7, etc. The <code>halfwidth</code> parameter for these is * (size - 1)/2; i.e., 1, 2, 3, etc.</li> * <li>The <code>fract</code> parameter is typically taken in the range: 0.2 * &lt; <code>fract</code> &lt; 0.7</li> * </ul> * * @param halfwidth The half-width of the smoothing filter. * @param fraction The fraction of edge to be added back into the source * image. * @return an edge-enhanced Pix image or copy if no enhancement requested */ public static Pix unsharpMasking(Pix pixs, int halfwidth, float fraction) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeUnsharpMasking(pixs.mNativePix, halfwidth, fraction); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeUnsharpMasking(int nativePix, int halfwidth, float fract); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Wrapper for Leptonica's native BOX. * * @author alanv@google.com (Alan Viverette) */ public class Box { static { System.loadLibrary("lept"); } /** The index of the X coordinate within the geometry array. */ public static final int INDEX_X = 0; /** The index of the Y coordinate within the geometry array. */ public static final int INDEX_Y = 1; /** The index of the width within the geometry array. */ public static final int INDEX_W = 2; /** The index of the height within the geometry array. */ public static final int INDEX_H = 3; /** * A pointer to the native Box object. This is used internally by native * code. */ final int mNativeBox; private boolean mRecycled = false; /** * Creates a new Box wrapper for the specified native BOX. * * @param nativeBox A pointer to the native BOX. */ Box(int nativeBox) { mNativeBox = nativeBox; mRecycled = false; } /** * Creates a box with the specified geometry. All dimensions should be * non-negative and specified in pixels. * * @param x X-coordinate of the top-left corner of the box. * @param y Y-coordinate of the top-left corner of the box. * @param w Width of the box. * @param h Height of the box. */ public Box(int x, int y, int w, int h) { if (x < 0 || y < 0 || w < 0 || h < 0) { throw new IllegalArgumentException("All box dimensions must be non-negative"); } int nativeBox = nativeCreate(x, y, w, h); if (nativeBox == 0) { throw new OutOfMemoryError(); } mNativeBox = nativeBox; mRecycled = false; } /** * Returns the box's x-coordinate in pixels. * * @return The box's x-coordinate in pixels. */ public int getX() { return nativeGetX(mNativeBox); } /** * Returns the box's y-coordinate in pixels. * * @return The box's y-coordinate in pixels. */ public int getY() { return nativeGetY(mNativeBox); } /** * Returns the box's width in pixels. * * @return The box's width in pixels. */ public int getWidth() { return nativeGetWidth(mNativeBox); } /** * Returns the box's height in pixels. * * @return The box's height in pixels. */ public int getHeight() { return nativeGetHeight(mNativeBox); } /** * Returns an array containing the coordinates of this box. See INDEX_* * constants for indices. * * @return an array of box oordinates */ public int[] getGeometry() { int[] geometry = new int[4]; if (getGeometry(geometry)) { return geometry; } return null; } /** * Fills an array containing the coordinates of this box. See INDEX_* * constants for indices. * * @param geometry A 4+ element integer array to fill with coordinates. * @return <code>true</code> on success */ public boolean getGeometry(int[] geometry) { if (geometry.length < 4) { throw new IllegalArgumentException("Geometry array must be at least 4 elements long"); } return nativeGetGeometry(mNativeBox, geometry); } /** * Releases resources and frees any memory associated with this Box. */ public void recycle() { if (!mRecycled) { nativeDestroy(mNativeBox); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } // *************** // * NATIVE CODE * // *************** private static native int nativeCreate(int x, int y, int w, int h); private static native int nativeGetX(int nativeBox); private static native int nativeGetY(int nativeBox); private static native int nativeGetWidth(int nativeBox); private static native int nativeGetHeight(int nativeBox); private static native void nativeDestroy(int nativeBox); private static native boolean nativeGetGeometry(int nativeBox, int[] geometry); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image rotation and skew detection methods. * * @author alanv@google.com (Alan Viverette) */ public class Skew { static { System.loadLibrary("lept"); } // Text alignment defaults /** Default range for sweep, will detect rotation of + or - 30 degrees. */ public final static float SWEEP_RANGE = 30.0f; /** Default sweep delta, reasonably accurate within 0.05 degrees. */ public final static float SWEEP_DELTA = 5.0f; /** Default sweep reduction, one-eighth the size of the original image. */ public final static int SWEEP_REDUCTION = 8; /** Default sweep reduction, one-fourth the size of the original image. */ public final static int SEARCH_REDUCTION = 4; /** Default search minimum delta, reasonably accurate within 0.05 degrees. */ public final static float SEARCH_MIN_DELTA = 0.01f; /** * Finds and returns the skew angle using default parameters. * * @param pixs Input pix (1 bpp). * @return the detected skew angle, or 0.0 on failure */ public static float findSkew(Pix pixs) { return findSkew(pixs, SWEEP_RANGE, SWEEP_DELTA, SWEEP_REDUCTION, SEARCH_REDUCTION, SEARCH_MIN_DELTA); } /** * Finds and returns the skew angle, doing first a sweep through a set of * equal angles, and then doing a binary search until convergence. * <p> * Notes: * <ol> * <li>In computing the differential line sum variance score, we sum the * result over scanlines, but we always skip: * <ul> * <li>at least one scanline * <li>not more than 10% of the image height * <li>not more than 5% of the image width * </ul> * </ol> * * @param pixs Input pix (1 bpp). * @param sweepRange Half the full search range, assumed about 0; in * degrees. * @param sweepDelta Angle increment of sweep; in degrees. * @param sweepReduction Sweep reduction factor = 1, 2, 4 or 8. * @param searchReduction Binary search reduction factor = 1, 2, 4 or 8; and * must not exceed redsweep. * @param searchMinDelta Minimum binary search increment angle; in degrees. * @return the detected skew angle, or 0.0 on failure */ public static float findSkew(Pix pixs, float sweepRange, float sweepDelta, int sweepReduction, int searchReduction, float searchMinDelta) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeFindSkew(pixs.mNativePix, sweepRange, sweepDelta, sweepReduction, searchReduction, searchMinDelta); } // *************** // * NATIVE CODE * // *************** private static native float nativeFindSkew(int nativePix, float sweepRange, float sweepDelta, int sweepReduction, int searchReduction, float searchMinDelta); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image scaling methods. * * @author alanv@google.com (Alan Viverette) */ public class Scale { static { System.loadLibrary("lept"); } public enum ScaleType { /* Scale in X and Y independently, so that src matches dst exactly. */ FILL, /* * Compute a scale that will maintain the original src aspect ratio, but * will also ensure that src fits entirely inside dst. May shrink or * expand src to fit dst. */ FIT, /* * Compute a scale that will maintain the original src aspect ratio, but * will also ensure that src fits entirely inside dst. May shrink src to * fit dst, but will not expand it. */ FIT_SHRINK, } /** * Scales the Pix to a specified width and height using a specified scaling * type (fill, stretch, etc.). Returns a scaled image or a clone of the Pix * if no scaling is required. * * @param pixs * @param width * @param height * @param type * @return a scaled image or a clone of the Pix if no scaling is required */ public static Pix scaleToSize(Pix pixs, int width, int height, ScaleType type) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int pixWidth = pixs.getWidth(); int pixHeight = pixs.getHeight(); float scaleX = width / (float) pixWidth; float scaleY = height / (float) pixHeight; switch (type) { case FILL: // Retains default scaleX and scaleY values break; case FIT: scaleX = Math.min(scaleX, scaleY); scaleY = scaleX; break; case FIT_SHRINK: scaleX = Math.min(1.0f, Math.min(scaleX, scaleY)); scaleY = scaleX; break; } return scale(pixs, scaleX, scaleY); } /** * Scales the Pix to specified scale. If no scaling is required, returns a * clone of the source Pix. * * @param pixs the source Pix * @param scale dimension scaling factor * @return a Pix scaled according to the supplied factors */ public static Pix scale(Pix pixs, float scale) { return scale(pixs, scale, scale); } /** * Scales the Pix to specified x and y scale. If no scaling is required, * returns a clone of the source Pix. * * @param pixs the source Pix * @param scaleX x-dimension (width) scaling factor * @param scaleY y-dimension (height) scaling factor * @return a Pix scaled according to the supplied factors */ public static Pix scale(Pix pixs, float scaleX, float scaleY) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (scaleX <= 0.0f) throw new IllegalArgumentException("X scaling factor must be positive"); if (scaleY <= 0.0f) throw new IllegalArgumentException("Y scaling factor must be positive"); int nativePix = nativeScale(pixs.mNativePix, scaleX, scaleY); if (nativePix == 0) throw new RuntimeException("Failed to natively scale pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeScale(int nativePix, float scaleX, float scaleY); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Rect; import java.io.File; import java.util.ArrayList; import java.util.Iterator; /** * Java representation of a native PIXA object. This object contains multiple * PIX objects and their associated bounding BOX objects. * * @author alanv@google.com (Alan Viverette) */ public class Pixa implements Iterable<Pix> { static { System.loadLibrary("lept"); } /** A pointer to the native PIXA object. This is used internally by native code. */ final int mNativePixa; /** The specified width of this Pixa. */ final int mWidth; /** The specified height of this Pixa. */ final int mHeight; private boolean mRecycled; /** * Creates a new Pixa with the specified minimum capacity. The Pixa will * expand automatically as new Pix are added. * * @param size The minimum capacity of this Pixa. * @return a new Pixa or <code>null</code> on error */ public static Pixa createPixa(int size) { return createPixa(size, 0, 0); } /** * Creates a new Pixa with the specified minimum capacity. The Pixa will * expand automatically as new Pix are added. * <p> * If non-zero, the specified width and height will be used to specify the * bounds of output images. * * * @param size The minimum capacity of this Pixa. * @param width (Optional) The width of this Pixa, use 0 for default. * @param height (Optional) The height of this Pixa, use 0 for default. * @return a new Pixa or <code>null</code> on error */ public static Pixa createPixa(int size, int width, int height) { int nativePixa = nativeCreate(size); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, width, height); } /** * Creates a wrapper for the specified native Pixa pointer. * * @param nativePixa Native pointer to a PIXA object. * @param width The width of the PIXA. * @param height The height of the PIXA. */ public Pixa(int nativePixa, int width, int height) { mNativePixa = nativePixa; mWidth = width; mHeight = height; mRecycled = false; } /** * Returns a pointer to the native PIXA object. This is used by native code. * * @return a pointer to the native PIXA object */ public int getNativePixa() { return mNativePixa; } /** * Creates a shallow copy of this Pixa. Contained Pix are cloned, and the * resulting Pixa may be recycled separately from the original. * * @return a shallow copy of this Pixa */ public Pixa copy() { int nativePixa = nativeCopy(mNativePixa); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, mWidth, mHeight); } /** * Sorts this Pixa using the specified field and order. See * Constants.L_SORT_BY_* and Constants.L_SORT_INCREASING or * Constants.L_SORT_DECREASING. * * @param field The field to sort by. See Constants.L_SORT_BY_*. * @param order The order in which to sort. Must be either * Constants.L_SORT_INCREASING or Constants.L_SORT_DECREASING. * @return a sorted copy of this Pixa */ public Pixa sort(int field, int order) { int nativePixa = nativeSort(mNativePixa, field, order); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, mWidth, mHeight); } /** * Returns the number of elements in this Pixa. * * @return the number of elements in this Pixa */ public int size() { return nativeGetCount(mNativePixa); } /** * Recycles this Pixa and frees natively allocated memory. You may not * access or modify the Pixa after calling this method. * <p> * Any Pix obtained from this Pixa or copies of this Pixa will still be * accessible until they are explicitly recycled or finalized by the garbage * collector. */ public synchronized void recycle() { if (!mRecycled) { nativeDestroy(mNativePixa); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } /** * Merges the contents of another Pixa into this one. * * @param otherPixa * @return <code>true</code> on success */ public boolean join(Pixa otherPixa) { return nativeJoin(mNativePixa, otherPixa.mNativePixa); } /** * Adds a Pix to this Pixa. * * @param pix The Pix to add. * @param mode The mode in which to add this Pix, typically * Constants.L_CLONE. */ public void addPix(Pix pix, int mode) { nativeAddPix(mNativePixa, pix.mNativePix, mode); } /** * Adds a Box to this Pixa. * * @param box The Box to add. * @param mode The mode in which to add this Box, typically * Constants.L_CLONE. */ public void addBox(Box box, int mode) { nativeAddBox(mNativePixa, box.mNativeBox, mode); } /** * Adds a Pix and associated Box to this Pixa. * * @param pix The Pix to add. * @param box The Box to add. * @param mode The mode in which to add this Pix and Box, typically * Constants.L_CLONE. */ public void add(Pix pix, Box box, int mode) { nativeAdd(mNativePixa, pix.mNativePix, box.mNativeBox, mode); } /** * Returns the Box at the specified index, or <code>null</code> on error. * * @param index The index of the Box to return. * @return the Box at the specified index, or <code>null</code> on error */ public Box getBox(int index) { int nativeBox = nativeGetBox(mNativePixa, index); if (nativeBox == 0) { return null; } return new Box(nativeBox); } /** * Returns the Pix at the specified index, or <code>null</code> on error. * * @param index The index of the Pix to return. * @return the Pix at the specified index, or <code>null</code> on error */ public Pix getPix(int index) { int nativePix = nativeGetPix(mNativePixa, index); if (nativePix == 0) { return null; } return new Pix(nativePix); } /** * Returns the width of this Pixa, or 0 if one was not set when it was * created. * * @return the width of this Pixa, or 0 if one was not set when it was * created */ public int getWidth() { return mWidth; } /** * Returns the height of this Pixa, or 0 if one was not set when it was * created. * * @return the height of this Pixa, or 0 if one was not set when it was * created */ public int getHeight() { return mHeight; } /** * Returns a bounding Rect for this Pixa, which may be (0,0,0,0) if width * and height were not specified on creation. * * @return a bounding Rect for this Pixa */ public Rect getRect() { return new Rect(0, 0, mWidth, mHeight); } /** * Returns a bounding Rect for the Box at the specified index. * * @param index The index of the Box to get the bounding Rect of. * @return a bounding Rect for the Box at the specified index */ public Rect getBoxRect(int index) { int[] dimensions = getBoxGeometry(index); if (dimensions == null) { return null; } int x = dimensions[Box.INDEX_X]; int y = dimensions[Box.INDEX_Y]; int w = dimensions[Box.INDEX_W]; int h = dimensions[Box.INDEX_H]; Rect bound = new Rect(x, y, x + w, y + h); return bound; } /** * Returns a geometry array for the Box at the specified index. See * Box.INDEX_* for indices. * * @param index The index of the Box to get the geometry of. * @return a bounding Rect for the Box at the specified index */ public int[] getBoxGeometry(int index) { int[] dimensions = new int[4]; if (getBoxGeometry(index, dimensions)) { return dimensions; } return null; } /** * Fills an array with the geometry of the Box at the specified index. See * Box.INDEX_* for indices. * * @param index The index of the Box to get the geometry of. * @param dimensions The array to fill with Box geometry. Must be at least 4 * elements. * @return <code>true</code> on success */ public boolean getBoxGeometry(int index, int[] dimensions) { return nativeGetBoxGeometry(mNativePixa, index, dimensions); } /** * Returns an ArrayList of Box bounding Rects. * * @return an ArrayList of Box bounding Rects */ public ArrayList<Rect> getBoxRects() { final int pixaCount = nativeGetCount(mNativePixa); final int[] buffer = new int[4]; final ArrayList<Rect> rects = new ArrayList<Rect>(pixaCount); for (int i = 0; i < pixaCount; i++) { getBoxGeometry(i, buffer); final int x = buffer[Box.INDEX_X]; final int y = buffer[Box.INDEX_Y]; final Rect bound = new Rect(x, y, x + buffer[Box.INDEX_W], y + buffer[Box.INDEX_H]); rects.add(bound); } return rects; } /** * Replaces the Pix and Box at the specified index with the specified Pix * and Box, both of which may be recycled after calling this method. * * @param index The index of the Pix to replace. * @param pix The Pix to replace the existing Pix. * @param box The Box to replace the existing Box. */ public void replacePix(int index, Pix pix, Box box) { nativeReplacePix(mNativePixa, index, pix.mNativePix, box.mNativeBox); } /** * Merges the Pix at the specified indices and removes the Pix at the second * index. * * @param indexA The index of the first Pix. * @param indexB The index of the second Pix, which will be removed after * merging. */ public void mergeAndReplacePix(int indexA, int indexB) { nativeMergeAndReplacePix(mNativePixa, indexA, indexB); } /** * Writes the components of this Pix to a bitmap-formatted file using a * random color map. * * @param file The file to write to. * @return <code>true</code> on success */ public boolean writeToFileRandomCmap(File file) { return nativeWriteToFileRandomCmap(mNativePixa, file.getAbsolutePath(), mWidth, mHeight); } @Override public Iterator<Pix> iterator() { return new PixIterator(); } private class PixIterator implements Iterator<Pix> { private int mIndex; private PixIterator() { mIndex = 0; } @Override public boolean hasNext() { final int size = size(); return (size > 0 && mIndex < size); } @Override public Pix next() { return getPix(mIndex++); } @Override public void remove() { throw new UnsupportedOperationException(); } } // *************** // * NATIVE CODE * // *************** private static native int nativeCreate(int size); private static native int nativeCopy(int nativePixa); private static native int nativeSort(int nativePixa, int field, int order); private static native boolean nativeJoin(int nativePixa, int otherPixa); private static native int nativeGetCount(int nativePixa); private static native void nativeDestroy(int nativePixa); private static native void nativeAddPix(int nativePixa, int nativePix, int mode); private static native void nativeAddBox(int nativePixa, int nativeBox, int mode); private static native void nativeAdd(int nativePixa, int nativePix, int nativeBox, int mode); private static native boolean nativeWriteToFileRandomCmap( int nativePixa, String fileName, int width, int height); private static native void nativeReplacePix( int nativePixa, int index, int nativePix, int nativeBox); private static native void nativeMergeAndReplacePix(int nativePixa, int indexA, int indexB); private static native int nativeGetBox(int nativePix, int index); private static native int nativeGetPix(int nativePix, int index); private static native boolean nativeGetBoxGeometry(int nativePixa, int index, int[] dimensions); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import java.io.File; /** * @author alanv@google.com (Alan Viverette) */ public class WriteFile { static { System.loadLibrary("lept"); } /* Default JPEG quality */ public static final int DEFAULT_QUALITY = 85; /* Default JPEG progressive encoding */ public static final boolean DEFAULT_PROGRESSIVE = true; /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @return a byte array where each byte represents a single 8-bit pixel */ public static byte[] writeBytes8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (pixs.getDepth() != 8) { Pix pix8 = Convert.convertTo8(pixs); pixs.recycle(); pixs = pix8; } byte[] data = new byte[size]; writeBytes8(pixs, data); return data; } /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @param data A byte array large enough to hold the pixels of pixs. * @return the number of bytes written to data */ public static int writeBytes8(Pix pixs, byte[] data) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (data.length < size) throw new IllegalArgumentException("Data array must be large enough to hold image bytes"); int bytesWritten = nativeWriteBytes8(pixs.mNativePix, data); return bytesWritten; } /** * Writes all the images in a Pixa array to individual files using the * specified format. The output file extension will be determined by the * format. * <p> * Output file names will take the format <path>/<prefix><index>.<extension> * * @param pixas The source Pixa image array. * @param path The output directory. * @param prefix The prefix to give output files. * @param format The format to use for output files. * @return <code>true</code> on success */ public static boolean writeFiles(Pixa pixas, File path, String prefix, int format) { if (pixas == null) throw new IllegalArgumentException("Source pixa must be non-null"); if (path == null) throw new IllegalArgumentException("Destination path non-null"); if (prefix == null) throw new IllegalArgumentException("Filename prefix must be non-null"); throw new RuntimeException("writeFiles() is not currently supported"); } /** * Write a Pix to a byte array using the specified encoding from * Constants.IFF_*. * * @param pixs The source image. * @param format A format from Constants.IFF_*. * @return a byte array containing encoded bytes */ public static byte[] writeMem(Pix pixs, int format) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeWriteMem(pixs.mNativePix, format); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Uses default quality and progressive encoding settings. * * @param pixs Source image. * @param file The file to write. * @return <code>true</code> on success */ public static boolean writeImpliedFormat(Pix pixs, File file) { return writeImpliedFormat(pixs, file, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Notes: * <ol> * <li>This determines the output format from the filename extension. * <li>The last two args are ignored except for requests for jpeg files. * <li>The jpeg default quality is 75. * </ol> * * @param pixs Source image. * @param file The file to write. * @param quality (Only for lossy formats) Quality between 1 - 100, 0 for * default. * @param progressive (Only for JPEG) Whether to encode as progressive. * @return <code>true</code> on success */ public static boolean writeImpliedFormat( Pix pixs, File file, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (file == null) throw new IllegalArgumentException("File must be non-null"); return nativeWriteImpliedFormat( pixs.mNativePix, file.getAbsolutePath(), quality, progressive); } /** * Writes a Pix to an Android Bitmap object. The output Bitmap will always * be in ARGB_8888 format, but the input Pixs may be any bit-depth. * * @param pixs The source image. * @return a Bitmap containing a copy of the source image, or <code>null * </code> on failure */ public static Bitmap writeBitmap(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); final int[] dimensions = pixs.getDimensions(); final int width = dimensions[Pix.INDEX_W]; final int height = dimensions[Pix.INDEX_H]; //final int depth = dimensions[Pix.INDEX_D]; final Bitmap.Config config = Bitmap.Config.ARGB_8888; final Bitmap bitmap = Bitmap.createBitmap(width, height, config); if (nativeWriteBitmap(pixs.mNativePix, bitmap)) { return bitmap; } bitmap.recycle(); return null; } // *************** // * NATIVE CODE * // *************** private static native int nativeWriteBytes8(int nativePix, byte[] data); private static native boolean nativeWriteFiles(int nativePix, String rootname, int format); private static native byte[] nativeWriteMem(int nativePix, int format); private static native boolean nativeWriteImpliedFormat( int nativePix, String fileName, int quality, boolean progressive); private static native boolean nativeWriteBitmap(int nativePix, Bitmap bitmap); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image adaptive mapping methods. * * @author alanv@google.com (Alan Viverette) */ public class AdaptiveMap { static { System.loadLibrary("lept"); } // Background normalization constants /** Image reduction value; possible values are 1, 2, 4, 8 */ private final static int NORM_REDUCTION = 16; /** Desired tile size; actual size may vary */ private final static int NORM_SIZE = 3; /** Background brightness value; values over 200 may result in clipping */ private final static int NORM_BG_VALUE = 200; /** * Normalizes an image's background using default parameters. * * @param pixs A source pix image. * @return the source pix image with a normalized background */ public static Pix backgroundNormMorph(Pix pixs) { return backgroundNormMorph(pixs, NORM_REDUCTION, NORM_SIZE, NORM_BG_VALUE); } /** * Normalizes an image's background to a specified value. * <p> * Notes: * <ol> * <li>This is a top-level interface for normalizing the image intensity by * mapping the image so that the background is near the input value 'bgval'. * <li>The input image is either grayscale or rgb. * <li>For each component in the input image, the background value is * estimated using a grayscale closing; hence the 'Morph' in the function * name. * <li>An optional binary mask can be specified, with the foreground pixels * typically over image regions. The resulting background map values will be * determined by surrounding pixels that are not under the mask foreground. * The origin (0,0) of this mask is assumed to be aligned with the origin of * the input image. This binary mask must not fully cover pixs, because then * there will be no pixels in the input image available to compute the * background. * <li>The map is computed at reduced size (given by 'reduction') from the * input pixs and optional pixim. At this scale, pixs is closed to remove * the background, using a square Sel of odd dimension. The product of * reduction * size should be large enough to remove most of the text * foreground. * <li>No convolutional smoothing needs to be done on the map before * inverting it. * <li>A 'bgval' target background value for the normalized image. This * should be at least 128. If set too close to 255, some clipping will occur * in the result. * </ol> * * @param pixs A source pix image. * @param normReduction Reduction at which morphological closings are done. * @param normSize Size of square Sel for the closing. * @param normBgValue Target background value. * @return the source pix image with a normalized background */ public static Pix backgroundNormMorph( Pix pixs, int normReduction, int normSize, int normBgValue) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeBackgroundNormMorph( pixs.mNativePix, normReduction, normSize, normBgValue); if (nativePix == 0) throw new RuntimeException("Failed to normalize image background"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeBackgroundNormMorph( int nativePix, int reduction, int size, int bgval); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image binarization methods. * * @author alanv@google.com (Alan Viverette) */ public class Binarize { static { System.loadLibrary("lept"); } // Otsu thresholding constants /** Desired tile X dimension; actual size may vary */ public final static int OTSU_SIZE_X = 32; /** Desired tile Y dimension; actual size may vary */ public final static int OTSU_SIZE_Y = 32; /** Desired X smoothing value */ public final static int OTSU_SMOOTH_X = 2; /** Desired Y smoothing value */ public final static int OTSU_SMOOTH_Y = 2; /** Fraction of the max Otsu score, typically 0.1 */ public final static float OTSU_SCORE_FRACTION = 0.1f; /** * Performs locally-adaptive Otsu threshold binarization with default * parameters. * * @param pixs An 8 bpp PIX source image. * @return A 1 bpp thresholded PIX image. */ public static Pix otsuAdaptiveThreshold(Pix pixs) { return otsuAdaptiveThreshold( pixs, OTSU_SIZE_X, OTSU_SIZE_Y, OTSU_SMOOTH_X, OTSU_SMOOTH_Y, OTSU_SCORE_FRACTION); } /** * Performs locally-adaptive Otsu threshold binarization. * <p> * Notes: * <ol> * <li>The Otsu method finds a single global threshold for an image. This * function allows a locally adapted threshold to be found for each tile * into which the image is broken up. * <li>The array of threshold values, one for each tile, constitutes a * highly downscaled image. This array is optionally smoothed using a * convolution. The full width and height of the convolution kernel are (2 * * smoothX + 1) and (2 * smoothY + 1). * <li>The minimum tile dimension allowed is 16. If such small tiles are * used, it is recommended to use smoothing, because without smoothing, each * small tile determines the splitting threshold independently. A tile that * is entirely in the image bg will then hallucinate fg, resulting in a very * noisy binarization. The smoothing should be large enough that no tile is * only influenced by one type (fg or bg) of pixels, because it will force a * split of its pixels. * <li>To get a single global threshold for the entire image, use input * values of sizeX and sizeY that are larger than the image. For this * situation, the smoothing parameters are ignored. * <li>The threshold values partition the image pixels into two classes: one * whose values are less than the threshold and another whose values are * greater than or equal to the threshold. This is the same use of * 'threshold' as in pixThresholdToBinary(). * <li>The scorefract is the fraction of the maximum Otsu score, which is * used to determine the range over which the histogram minimum is searched. * See numaSplitDistribution() for details on the underlying method of * choosing a threshold. * <li>This uses enables a modified version of the Otsu criterion for * splitting the distribution of pixels in each tile into a fg and bg part. * The modification consists of searching for a minimum in the histogram * over a range of pixel values where the Otsu score is within a defined * fraction, scoreFraction, of the max score. To get the original Otsu * algorithm, set scoreFraction == 0. * </ol> * * @param pixs An 8 bpp PIX source image. * @param sizeX Desired tile X dimension; actual size may vary. * @param sizeY Desired tile Y dimension; actual size may vary. * @param smoothX Half-width of convolution kernel applied to threshold * array: use 0 for no smoothing. * @param smoothY Half-height of convolution kernel applied to threshold * array: use 0 for no smoothing. * @param scoreFraction Fraction of the max Otsu score; typ. 0.1 (use 0.0 * for standard Otsu). * @return A 1 bpp thresholded PIX image. */ public static Pix otsuAdaptiveThreshold( Pix pixs, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFraction) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixs.getDepth() != 8) throw new IllegalArgumentException("Source pix depth must be 8bpp"); int nativePix = nativeOtsuAdaptiveThreshold( pixs.mNativePix, sizeX, sizeY, smoothX, smoothY, scoreFraction); if (nativePix == 0) throw new RuntimeException("Failed to perform Otsu adaptive threshold on image"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeOtsuAdaptiveThreshold( int nativePix, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFract); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.File; /** * Image input and output methods. * * @author alanv@google.com (Alan Viverette) */ public class ReadFile { static { System.loadLibrary("lept"); } /** * Creates a 32bpp Pix object from encoded data. Supported formats are BMP * and JPEG. * * @param encodedData JPEG or BMP encoded byte data. * @return a 32bpp Pix object */ public static Pix readMem(byte[] encodedData) { if (encodedData == null) throw new IllegalArgumentException("Image data byte array must be non-null"); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; final Bitmap bmp = BitmapFactory.decodeByteArray(encodedData, 0, encodedData.length, opts); final Pix pix = readBitmap(bmp); bmp.recycle(); return pix; } /** * Creates an 8bpp Pix object from raw 8bpp grayscale pixels. * * @param pixelData 8bpp grayscale pixel data. * @param width The width of the input image. * @param height The height of the input image. * @return an 8bpp Pix object */ public static Pix readBytes8(byte[] pixelData, int width, int height) { if (pixelData == null) throw new IllegalArgumentException("Byte array must be non-null"); if (width <= 0) throw new IllegalArgumentException("Image width must be greater than 0"); if (height <= 0) throw new IllegalArgumentException("Image height must be greater than 0"); if (pixelData.length < width * height) throw new IllegalArgumentException("Array length does not match dimensions"); int nativePix = nativeReadBytes8(pixelData, width, height); if (nativePix == 0) throw new RuntimeException("Failed to read pix from memory"); return new Pix(nativePix); } /** * Replaces the bytes in an 8bpp Pix object with raw grayscale 8bpp pixels. * Width and height be identical to the input Pix. * * @param pixs The Pix whose bytes will be replaced. * @param pixelData 8bpp grayscale pixel data. * @param width The width of the input image. * @param height The height of the input image. * @return an 8bpp Pix object */ public static boolean replaceBytes8(Pix pixs, byte[] pixelData, int width, int height) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixelData == null) throw new IllegalArgumentException("Byte array must be non-null"); if (width <= 0) throw new IllegalArgumentException("Image width must be greater than 0"); if (height <= 0) throw new IllegalArgumentException("Image height must be greater than 0"); if (pixelData.length < width * height) throw new IllegalArgumentException("Array length does not match dimensions"); if (pixs.getWidth() != width) throw new IllegalArgumentException("Source pix width does not match image width"); if (pixs.getHeight() != height) throw new IllegalArgumentException("Source pix width does not match image width"); return nativeReplaceBytes8(pixs.mNativePix, pixelData, width, height); } /** * Creates a Pixa object from encoded files in a directory. Supported * formats are BMP and JPEG. * * @param dir The directory containing the files. * @param prefix The prefix of the files to load into a Pixa. * @return a Pixa object containing one Pix for each file */ public static Pixa readFiles(File dir, String prefix) { if (dir == null) throw new IllegalArgumentException("Directory must be non-null"); if (!dir.exists()) throw new IllegalArgumentException("Directory does not exist"); if (!dir.canRead()) throw new IllegalArgumentException("Cannot read directory"); // TODO: Remove or fix this. throw new RuntimeException("readFiles() is not current supported"); } /** * Creates a Pix object from encoded file data. Supported formats are BMP * and JPEG. * * @param file The JPEG or BMP-encoded file to read in as a Pix. * @return a Pix object */ public static Pix readFile(File file) { if (file == null) throw new IllegalArgumentException("File must be non-null"); if (!file.exists()) throw new IllegalArgumentException("File does not exist"); if (!file.canRead()) throw new IllegalArgumentException("Cannot read file"); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; final Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), opts); final Pix pix = readBitmap(bmp); bmp.recycle(); return pix; } /** * Creates a Pix object from Bitmap data. Currently supports only * ARGB_8888-formatted bitmaps. * * @param bmp The Bitmap object to convert to a Pix. * @return a Pix object */ public static Pix readBitmap(Bitmap bmp) { if (bmp == null) throw new IllegalArgumentException("Bitmap must be non-null"); if (bmp.getConfig() != Bitmap.Config.ARGB_8888) throw new IllegalArgumentException("Bitmap config must be ARGB_8888"); int nativePix = nativeReadBitmap(bmp); if (nativePix == 0) throw new RuntimeException("Failed to read pix from bitmap"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeReadMem(byte[] data, int size); private static native int nativeReadBytes8(byte[] data, int w, int h); private static native boolean nativeReplaceBytes8(int nativePix, byte[] data, int w, int h); private static native int nativeReadFiles(String dirname, String prefix); private static native int nativeReadFile(String filename); private static native int nativeReadBitmap(Bitmap bitmap); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Rect; /** * Java representation of a native Leptonica PIX object. * * @author alanv@google.com (Alan Viverette) */ public class Pix { static { System.loadLibrary("lept"); } /** Index of the image width within the dimensions array. */ public static final int INDEX_W = 0; /** Index of the image height within the dimensions array. */ public static final int INDEX_H = 1; /** Index of the image bit-depth within the dimensions array. */ public static final int INDEX_D = 2; /** Package-accessible pointer to native pix. */ final int mNativePix; private boolean mRecycled; /** * Creates a new Pix wrapper for the specified native PIX object. Never call * this twice on the same native pointer, because finalize() will attempt to * free native memory twice. * * @param nativePix A pointer to the native PIX object. */ public Pix(int nativePix) { mNativePix = nativePix; mRecycled = false; } public Pix(int width, int height, int depth) { if (width <= 0 || height <= 0) { throw new IllegalArgumentException("Pix width and height must be > 0"); } else if (depth != 1 && depth != 2 && depth != 4 && depth != 8 && depth != 16 && depth != 24 && depth != 32) { throw new IllegalArgumentException("Depth must be one of 1, 2, 4, 8, 16, or 32"); } mNativePix = nativeCreatePix(width, height, depth); mRecycled = false; } /** * Returns a pointer to the native Pix object. This is used by native code * and is only valid within the same process in which the Pix was created. * * @return a native pointer to the Pix object */ public int getNativePix() { return mNativePix; } /** * Return the raw bytes of the native PIX object. You can reconstruct the * Pix from this data using createFromPix(). * * @return a copy of this PIX object's raw data */ public byte[] getData() { int size = nativeGetDataSize(mNativePix); byte[] buffer = new byte[size]; if (!nativeGetData(mNativePix, buffer)) { throw new RuntimeException("native getData failed"); } return buffer; } /** * Returns an array of this image's dimensions. See Pix.INDEX_* for indices. * * @return an array of this image's dimensions or <code>null</code> on * failure */ public int[] getDimensions() { int[] dimensions = new int[4]; if (getDimensions(dimensions)) { return dimensions; } return null; } /** * Fills an array with this image's dimensions. The array must be at least 3 * elements long. * * @param dimensions An integer array with at least three elements. * @return <code>true</code> on success */ public boolean getDimensions(int[] dimensions) { return nativeGetDimensions(mNativePix, dimensions); } /** * Returns a clone of this Pix. This does NOT create a separate copy, just a * new pointer that can be recycled without affecting other clones. * * @return a clone (shallow copy) of the Pix */ @Override public Pix clone() { int nativePix = nativeClone(mNativePix); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Returns a deep copy of this Pix that can be modified without affecting * the original Pix. * * @return a copy of the Pix */ public Pix copy() { int nativePix = nativeCopy(mNativePix); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Inverts this Pix in-place. * * @return <code>true</code> on success */ public boolean invert() { return nativeInvert(mNativePix); } /** * Releases resources and frees any memory associated with this Pix. You may * not modify or access the pix after calling this method. */ public void recycle() { if (!mRecycled) { nativeDestroy(mNativePix); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } /** * Creates a new Pix from raw Pix data obtained from getData(). * * @param pixData Raw pix data obtained from getData(). * @param width The width of the original Pix. * @param height The height of the original Pix. * @param depth The bit-depth of the original Pix. * @return a new Pix or <code>null</code> on error */ public static Pix createFromPix(byte[] pixData, int width, int height, int depth) { int nativePix = nativeCreateFromData(pixData, width, height, depth); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Returns a Rect with the width and height of this Pix. * * @return a Rect with the width and height of this Pix */ public Rect getRect() { int w = getWidth(); int h = getHeight(); return new Rect(0, 0, w, h); } /** * Returns the width of this Pix. * * @return the width of this Pix */ public int getWidth() { return nativeGetWidth(mNativePix); } /** * Returns the height of this Pix. * * @return the height of this Pix */ public int getHeight() { return nativeGetHeight(mNativePix); } /** * Returns the depth of this Pix. * * @return the depth of this Pix */ public int getDepth() { return nativeGetDepth(mNativePix); } /** * Returns the {@link android.graphics.Color} at the specified location. * * @param x The x coordinate (0...width-1) of the pixel to return. * @param y The y coordinate (0...height-1) of the pixel to return. * @return The argb {@link android.graphics.Color} at the specified * coordinate. * @throws IllegalArgumentException If x, y exceeds the image bounds. */ public int getPixel(int x, int y) { if (x < 0 || x >= getWidth()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } else if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } return nativeGetPixel(mNativePix, x, y); } /** * Sets the {@link android.graphics.Color} at the specified location. * * @param x The x coordinate (0...width-1) of the pixel to set. * @param y The y coordinate (0...height-1) of the pixel to set. * @param color The argb {@link android.graphics.Color} to set at the * specified coordinate. * @throws IllegalArgumentException If x, y exceeds the image bounds. */ public void setPixel(int x, int y, int color) { if (x < 0 || x >= getWidth()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } else if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } nativeSetPixel(mNativePix, x, y, color); } // *************** // * NATIVE CODE * // *************** private static native int nativeCreatePix(int w, int h, int d); private static native int nativeCreateFromData(byte[] data, int w, int h, int d); private static native boolean nativeGetData(int nativePix, byte[] data); private static native int nativeGetDataSize(int nativePix); private static native int nativeClone(int nativePix); private static native int nativeCopy(int nativePix); private static native boolean nativeInvert(int nativePix); private static native void nativeDestroy(int nativePix); private static native boolean nativeGetDimensions(int nativePix, int[] dimensions); private static native int nativeGetWidth(int nativePix); private static native int nativeGetHeight(int nativePix); private static native int nativeGetDepth(int nativePix); private static native int nativeGetPixel(int nativePix, int x, int y); private static native void nativeSetPixel(int nativePix, int x, int y, int color); }
Java